=VLOOKUP(LEFT(A4,LEN(A4)-9),$D:$F,3,0)
I use this if my Lookup_Value
needs to be truncated because of the format the name is in the Table_Array. E.g. my Lookup_Value
is "Eastbay District", but the Table_Array
list I have only shows this as "Eastbay". "Eastbay District" minus 9 characters will result in "Eastbay".
I hope this helps!
This piece of vba worked for me:
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = Range("b2").Value
Database_name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
SQLStr = "SELECT * FROM ComputingNotesTable"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}
In this code you can put your address in a text box.
To simplify cleaning when using "out of source" build (i.e. you build in the build
directory), I use the following script:
$ cat ~/bin/cmake-clean-build
#!/bin/bash
if [ -d ../build ]; then
cd ..
rm -rf build
mkdir build
cd build
else
echo "build directory DOES NOT exist"
fi
Every time you need to clean up, you should source this script from the build
directory:
. cmake-clean-build
$(".ui-button-icon-only").hide();
Does Python have a string contains substring method?
99% of use cases will be covered using the keyword, in
, which returns True
or False
:
'substring' in any_string
For the use case of getting the index, use str.find
(which returns -1 on failure, and has optional positional arguments):
start = 0
stop = len(any_string)
any_string.find('substring', start, stop)
or str.index
(like find
but raises ValueError on failure):
start = 100
end = 1000
any_string.index('substring', start, end)
Use the in
comparison operator because
>>> 'foo' in '**foo**'
True
The opposite (complement), which the original question asked for, is not in
:
>>> 'foo' not in '**foo**' # returns False
False
This is semantically the same as not 'foo' in '**foo**'
but it's much more readable and explicitly provided for in the language as a readability improvement.
__contains__
The "contains" method implements the behavior for in
. This example,
str.__contains__('**foo**', 'foo')
returns True
. You could also call this function from the instance of the superstring:
'**foo**'.__contains__('foo')
But don't. Methods that start with underscores are considered semantically non-public. The only reason to use this is when implementing or extending the in
and not in
functionality (e.g. if subclassing str
):
class NoisyString(str):
def __contains__(self, other):
print(f'testing if "{other}" in "{self}"')
return super(NoisyString, self).__contains__(other)
ns = NoisyString('a string with a substring inside')
and now:
>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True
find
and index
to test for "contains"Don't use the following string methods to test for "contains":
>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2
>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'**oo**'.index('foo')
ValueError: substring not found
Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the in
comparison operator.
Also, these are not drop-in replacements for in
. You may have to handle the exception or -1
cases, and if they return 0
(because they found the substring at the beginning) the boolean interpretation is False
instead of True
.
If you really mean not any_string.startswith(substring)
then say it.
We can compare various ways of accomplishing the same goal.
import timeit
def in_(s, other):
return other in s
def contains(s, other):
return s.__contains__(other)
def find(s, other):
return s.find(other) != -1
def index(s, other):
try:
s.index(other)
except ValueError:
return False
else:
return True
perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}
And now we see that using in
is much faster than the others.
Less time to do an equivalent operation is better:
>>> perf_dict
{'in:True': 0.16450627865128808,
'in:False': 0.1609668098178645,
'__contains__:True': 0.24355481654697542,
'__contains__:False': 0.24382793854783813,
'find:True': 0.3067379407923454,
'find:False': 0.29860888058124146,
'index:True': 0.29647137792585454,
'index:False': 0.5502287584545229}
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
Actually there is a workaround. Copy the entire method, modify it's name, e.g. originalName() to originalName2() but modify the variable inside to take on whatever value you want, or pass it in as a parameter.
Then if you call this method directly from the console, it will have the same functionality but you will be able to modify the variable values.
If the method is called automatically then instead type into the console
originalName = null;
function originalName(original params..)
{
alert("modified internals");
add whatever original code you want
}
Although recently its use is undefined, a common and useful use for the form feed is to separate sections of code vertically, like so: (from http://ergoemacs.org/emacs/emacs_form_feed_section_paging.html)
c
can be used on lists (and not only on vectors):
# you have
l1 = list(2, 3)
l2 = list(4)
# you want
list(2, 3, 4)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
# you can do
c(l1, l2)
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
If you have a list of lists, you can do it (perhaps) more comfortably with do.call
, eg:
do.call(c, list(l1, l2))
The use of the deprecated new Buffer()
constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.
According to the deprecation warning new Buffer()
should be replaced with one of:
Buffer.alloc()
Buffer.allocUnsafe()
or Buffer.from()
Another option in order to avoid this issue would be using the safe-buffer package instead.
You can also try (when using yarn..):
yarn global add yarn
as mentioned here: Link
Another suggestion from the comments (thx to gkiely): self-update
Note: self-update is not available. See policies for enforcing versions within a project
In order to update your version of Yarn, run
curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
Well, I understand this question is Visual Studio GUI related, but maybe the asker can try this trick also. Just giving a different perspective in solving this problem.
I like to use terminal a lot for GIT, so here are the simple steps:
Pre-requisites...
Now,
Don't create any file inside the repository. Keep it empty. Copy its URL. It should be something like https://github.com/Username/ProjectName.git
Open up the terminal and redirect to your Visual Studio Project directory
Configure your credentials
git config --global user.name "your_git_username"
git config --global user.email "your_git_email"
Then type these commands
git init
git add .
git commit -m "First Migration Commit"
git remote add origin paste_your_URL_here
git push -u origin master
Done...Hope this helps
.dmp files are dumps of oracle databases created with the "exp" command. You can import them using the "imp" command.
If you have an oracle client intalled on your machine, you can executed the command
imp help=y
to find out how it works. What will definitely help is knowing from wich schema the data was exported and what the oracle version was.
I would do it like this:
variable = "string"
message = ""
for b in variable:
message = b+message
print (message)
and it prints: gnirts
https://github.com/Sarjeetsinghbabu/Gallery create intent for reqouest image list
int LAUNCH_SECOND_ACTIVITY = 101;
Intent i = new Intent(CallMainActivity2.this,
GalleryFoldersActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);
https://github.com/Sarjeetsinghbabu/Gallery
After selected image get list of model
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LAUNCH_SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.d(TAG, "onActivityResult: "+result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax()
method:
<script type="text/javascript">
$.ajax({
url: '@Url.Action("NameOfYourAction")',
type: 'GET',
cache: false,
success: function(result) {
// you could use the result.values dictionary here
}
});
</script>
I came up with another implementation documented at, http://blog.sangupta.com/2010/05/encodeuricomponent-and.html. The implementation can also handle Unicode bytes.
The Dictionary throws a KeyNotFound
exception in the event that the dictionary does not contain your key.
As suggested, ContainsKey
is the appropriate precaution. TryGetValue
is also effective.
This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
Insert the following into decompile.jar.sh
# Usage: decompile.jar.sh some.jar [-d]
# clean target folders
function clean_target {
rm -rf $unjar $src $jad_log
}
# clean all debug stuff
function clean_stuff {
rm -rf $unjar $jad_log
}
# the main function
function work {
jar=$1
unjar=`basename $jar.unjar`
src=`basename $jar.src`
jad_log=jad.log
clean_target
unzip -q $jar -d $unjar
jad -d $src -ff -r -lnc -o -s java $unjar/**/*.class > $jad_log 2>&1
if [ ! $debug ]; then
clean_stuff
fi
if [ -d $src ]
then
echo "$jar has been decompiled to $src"
else
echo "Got some problems check output or run in debug mode"
fi
}
function usage {
echo "This script extract and decompile JAR file"
echo "Usage: $0 some.jar [-d]"
echo " where: some.jar is the target to decompile"
echo " use -d for debug mode"
}
# check params
if [ -n "$1" ]
then
if [ "$2" == "-d" ]; then
debug=true
set -x
fi
work $1
else
usage
fi
Ready to use, just type dj your.jar
and you will get your.jar.src
folder with sources. Use -d
option for debug mode.
In my case, I have Eclipse Maven project. I had the same issue and I posted detailed explanation of the issue and answer here Eclipse Maven - Code Completion fails "This compilation unit is not on the build path of a Java project" and "Failed to Download Index" Error
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
_x000D_
There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license
http://www.mathworks.com/products/image/
There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.
If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.
When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me
eg:
$ curl ifconfig.me/ip
Over the years I have seen many of these sites come and go, I find this DNS based method more robust:
$ dig +short myip.opendns.com @resolver1.opendns.com
I have this handy alias in my ~/.bashrc
:
alias wip='dig +short myip.opendns.com @resolver1.opendns.com'
Possibly, you closed the 'file1'.
Just use 'w' flag, that create new file:
file1 = open('recentlyUpdated.yaml', 'w')
mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists)...
(see also https://docs.python.org/3/library/functions.html?highlight=open#open)
The best answers did not work for until I wrote this in the .emacs file:
(global-set-key (kbd "TAB") 'self-insert-command)
I have benchmark between HttpClient, WebClient, HttpWebResponse then call Rest Web Api
and result Call Rest Web Api Benchmark
---------------------Stage 1 ---- 10 Request
{00:00:17.2232544} ====>HttpClinet
{00:00:04.3108986} ====>WebRequest
{00:00:04.5436889} ====>WebClient
---------------------Stage 1 ---- 10 Request--Small Size
{00:00:17.2232544}====>HttpClinet
{00:00:04.3108986}====>WebRequest
{00:00:04.5436889}====>WebClient
---------------------Stage 3 ---- 10 sync Request--Small Size
{00:00:15.3047502}====>HttpClinet
{00:00:03.5505249}====>WebRequest
{00:00:04.0761359}====>WebClient
---------------------Stage 4 ---- 100 sync Request--Small Size
{00:03:23.6268086}====>HttpClinet
{00:00:47.1406632}====>WebRequest
{00:01:01.2319499}====>WebClient
---------------------Stage 5 ---- 10 sync Request--Max Size
{00:00:58.1804677}====>HttpClinet
{00:00:58.0710444}====>WebRequest
{00:00:38.4170938}====>WebClient
---------------------Stage 6 ---- 10 sync Request--Max Size
{00:01:04.9964278}====>HttpClinet
{00:00:59.1429764}====>WebRequest
{00:00:32.0584836}====>WebClient
_____ WebClient Is faster ()
var stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < 10; ++i)
{
CallGetHttpClient();
CallPostHttpClient();
}
stopWatch.Stop();
var httpClientValue = stopWatch.Elapsed;
stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < 10; ++i)
{
CallGetWebRequest();
CallPostWebRequest();
}
stopWatch.Stop();
var webRequesttValue = stopWatch.Elapsed;
stopWatch = new Stopwatch();
stopWatch.Start();
for (var i = 0; i < 10; ++i)
{
CallGetWebClient();
CallPostWebClient();
}
stopWatch.Stop();
var webClientValue = stopWatch.Elapsed;
//-------------------------Functions
private void CallPostHttpClient()
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
var responseTask = httpClient.PostAsync("PostJson", null);
responseTask.Wait();
var result = responseTask.Result;
var readTask = result.Content.ReadAsStringAsync().Result;
}
private void CallGetHttpClient()
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
var responseTask = httpClient.GetAsync("getjson");
responseTask.Wait();
var result = responseTask.Result;
var readTask = result.Content.ReadAsStringAsync().Result;
}
private string CallGetWebRequest()
{
var request = (HttpWebRequest)WebRequest.Create("https://localhost:44354/api/test/getjson");
request.Method = "GET";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
var content = string.Empty;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
}
}
return content;
}
private string CallPostWebRequest()
{
var apiUrl = "https://localhost:44354/api/test/PostJson";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl));
httpRequest.ContentType = "application/json";
httpRequest.Method = "POST";
httpRequest.ContentLength = 0;
using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
var json = new StreamReader(stream).ReadToEnd();
return json;
}
}
return "";
}
private string CallGetWebClient()
{
string apiUrl = "https://localhost:44354/api/test/getjson";
var client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
var json = client.DownloadString(apiUrl);
return json;
}
private string CallPostWebClient()
{
string apiUrl = "https://localhost:44354/api/test/PostJson";
var client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
var json = client.UploadString(apiUrl, "");
return json;
}
Returning an empty or zero-length string (e.g. ""
) to make a cell appear blank is a common practise in a worksheet formula but recreating that option when inserting the formula through the Range.Formula or Range.FormulaR1C1 property in VBA is unwieldy due to the necessity of having to double-up the double-quote characters within a quoted string.
The worksheet's native TEXT function can produce the same result without using quotes.
'formula to insert into C1 - =IF(A1<>"", B1, "")
range("C1").formula = "=IF(A1<>"""", B1, """")" '<~quote chars doubled up
range("C1").formula = "=IF(A1<>TEXT(,), B1, TEXT(,))" '<~with TEXT(,) instead
To my eye, using TEXT(,)
in place of ""
cleans up even a simple formula like the one above. The benefits become increasingly significant when used in more complicated formulas like the practise of appending an empty string to a VLOOKUP to avoid returning a zero to the cell when a lookup results in a blank or returning an empty string on no-match with IFERROR.
'formula to insert into D1 - =IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"", "")
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&"""", """")"
range("D1").formula = "=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&TEXT(,), TEXT(,))"
With TEXT(,)
replacing the old ""
method of delivering an empty string, you might get to stop using an abacus to determine whether you have the right number of quote characters in a formula string.
return;
will exit a method in C#.
See code snippet below
using System;
namespace Exercise_strings
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input string separated by -");
var stringInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(stringInput))
{
Console.WriteLine("Nothing entered");
return;
}
}
So in this case if a user enters a null string or whitespace, the use of the return method terminates the Main method elegantly.
Firstly you have to create state in app.js as below
.state('login', {
url: '/',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
and use below code in controller
$location.path('login');
Hope this will help you
It is mentioned in the .data()
documentation
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)
This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
The demo on my original answer below doesn't seem to work any more.
Updated answer
Again, from the .data()
documentation
The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
So for <div data-role="page"></div>
the following is true $('div').data('role') === 'page'
I'm fairly sure that $('div').data('data-role')
worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.
Also see jQuery Data vs Attr?
HTML
<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
<tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>
JavaScript (jQuery 1.6.2+)
var $changeMe = $('#changeMe');
var $log = $('#log');
var logger;
(logger = function(setter, getter, note) {
note = note || '';
eval('$changeMe' + setter);
var result = eval('$changeMe' + getter);
$log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");
$('#changeData').click(function() {
// set data-key to new value
logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
// try and set data-key via .attr and get via some methods
logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");
// bonus points
logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");
return false;
});
$('#changeData').click();
Original answer
For this HTML:
<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>
and this JavaScript (with jQuery 1.6.2)
console.log($('#foo').data('helptext'));
$('#changeData').click(function() {
$('#foo').data('helptext', 'Testing 123');
// $('#foo').attr('data-helptext', 'Testing 123');
console.log($('#foo').data('data-helptext'));
return false;
});
Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123');
does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123');
does.
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
You can use this command.
git diff --cached --name-only
The --cached
option of git diff
means to get staged files, and the --name-only
option means to get only names of the files.
Using a supposed name property as the map key:
for (Product p: productList) { s.put(p.getName(), p); }
Go in to your Xampp folder xampp/apache/conf/extra/httpd-xampp.conf
Edit the last paragraph:
#close XAMPP sites here
.
.
.
Deny from all
.
.
to
#close XAMPP sites here
.
.
.
Allow from all
.
.
or just watch this video: http://www.youtube.com/watch?v=ZUAKLUZa-AU.
This function found here, works fine for me
function jsonRemoveUnicodeSequences($struct) {
return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}
The quick and dirty way would be to simple bind to the keyup
event.
$('#mytxt').keyup(function(){_x000D_
$('#divlen').text('you typed ' + this.value.length + ' characters');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input type=text id=mytxt >_x000D_
<div id=divlen></div>
_x000D_
But better would be to bind a reusable function to several events. For example also to the change(), so you can also anticipate text changes such as pastes (with the context menu, shortcuts would also be caught by the keyup
)
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
scp is best for one file.
OR a combination of tar
& compression for smaller data sets
like source code trees with small resources (ie: images, sqlite etc).
It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.
As an exercise, you can do some gymnastics like piping tar
into ssh
and redirecting the results into a remote file. (saving the need to build
a swap or temporary clone aka zip or tar.gz)
However,
rsync simplify's this process and allows you to transfer data without consuming any additional disc space.
Also,
Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.
tl;dr
scp
== small scale (with room to build compressed files on the same drive)
rsync
== large scale (with the necessity to backup large data and no room left)
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
No, it is not okay to put a link
element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):
“This element defines a link. Unlike
A
, it may only appear in theHEAD
section of a document, although it may appear any number of times.”
The key lies in when you create the project in eclipse.
First step, you create the Java project in eclipse. Right click on the project and choose Team > Share>Git.
In the Configure Git Repository dialog, ensure that you select the option to create the Repository in the parent folder of the project.. Then you can push to github.
N.B: Eclipse will give you a warning about putting git repositories in your workspace. So when you create your project, set your project directory outside the default workspace.
f=open('filename','r').read()
f1=f.split('\n')
for i in range (len(f1)):
do_something_with(f1[i])
hope this helps.
Ask the user for the exact URL they're using in their browser. If they're entering https://your.site:80, they may receive the ssl_error_rx_record_too_long error.
This can be solved efficiently in O(n log (n)) as following. I am giving solution which tells if sum of any three numbers equal a given number.
import java.util.*;
public class MainClass {
public static void main(String[] args) {
int[] a = {-1, 0, 1, 2, 3, 5, -4, 6};
System.out.println(((Object) isThreeSumEqualsTarget(a, 11)).toString());
}
public static boolean isThreeSumEqualsTarget(int[] array, int targetNumber) {
//O(n log (n))
Arrays.sort(array);
System.out.println(Arrays.toString(array));
int leftIndex = 0;
int rightIndex = array.length - 1;
//O(n)
while (leftIndex + 1 < rightIndex - 1) {
//take sum of two corners
int sum = array[leftIndex] + array[rightIndex];
//find if the number matches exactly. Or get the closest match.
//here i am not storing closest matches. You can do it for yourself.
//O(log (n)) complexity
int binarySearchClosestIndex = binarySearch(leftIndex + 1, rightIndex - 1, targetNumber - sum, array);
//if exact match is found, we already got the answer
if (-1 == binarySearchClosestIndex) {
System.out.println(("combo is " + array[leftIndex] + ", " + array[rightIndex] + ", " + (targetNumber - sum)));
return true;
}
//if exact match is not found, we have to decide which pointer, left or right to move inwards
//we are here means , either we are on left end or on right end
else {
//we ended up searching towards start of array,i.e. we need a lesser sum , lets move inwards from right
//we need to have a lower sum, lets decrease right index
if (binarySearchClosestIndex == leftIndex + 1) {
rightIndex--;
} else if (binarySearchClosestIndex == rightIndex - 1) {
//we need to have a higher sum, lets decrease right index
leftIndex++;
}
}
}
return false;
}
public static int binarySearch(int start, int end, int elem, int[] array) {
int mid = 0;
while (start <= end) {
mid = (start + end) >>> 1;
if (elem < array[mid]) {
end = mid - 1;
} else if (elem > array[mid]) {
start = mid + 1;
} else {
//exact match case
//Suits more for this particular case to return -1
return -1;
}
}
return mid;
}
}
A word boundary is a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one.
The file hello.py is not an executable file. You need to specify a file like python.exe
try following:
import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
$alphas = range('A', 'Z');
In the accepted answer by @chuck, there is a comment saying it will not work in the case of FK.
it worked for me, case of EF6 .Net4.7.2
public class OnCallDay
{
public int Id { get; set; }
//[Key]
[Index("IX_OnCallDateEmployee", 1, IsUnique = true)]
public DateTime Date { get; set; }
[ForeignKey("Employee")]
[Index("IX_OnCallDateEmployee", 2, IsUnique = true)]
public string EmployeeId { get; set; }
public virtual ApplicationUser Employee{ get; set; }
}
I made an Objective-C version of Imagine Digitals swift answer above. I don't think I missed anything as it seems to work under preliminary testing, if you spot something let me know, and I'll update it
-(void) presentPopover
{
YourViewController* popoverContent = [[YourViewController alloc] init]; //this will be a subclass of UIViewController
UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:popoverContent];
nav.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController* popover = nav.popoverPresentationController;
popoverContent.preferredContentSize = CGSizeMake(500,600);
popover.delegate = self;
popover.sourceRect = CGRectMake(100,100,0,0); //I actually used popover.barButtonItem = self.myBarButton;
[self presentViewController:nav animated:YES completion:nil];
}
Remember to put the script after the call of "js/bootstrap", not before.
If above didn't help: check if locale is valid on client and server:
https://www.linuxbabe.com/linux-server/fix-ssh-locale-environment-variable-error
How do not pass locale through ssh
<?php
$currentpage = $_SERVER['REQUEST_URI'];
$eep=explode('/',$currentpage);
$ln=$eep[1];
if (in_array("en", $eep))
{
$lan='en';
}
if (in_array("es", $eep))
{
$lan='es';
}
?>
I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:
function lpad(n, e, d) {
var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
return o; }
Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.
A Protocol?
I found this, it appears to be a local setting for a computer...
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a CreateRoles
method in your startup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//Here you could create a super user who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration["AppSettings:UserName"],
Email = Configuration["AppSettings:UserEmail"],
};
//Ensure you have these values in your appsettings.json file
string userPWD = Configuration["AppSettings:UserPassword"];
var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);
if(_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the CreateRoles(serviceProvider).Wait();
method from the Configure
method in the Startup class.
ensure you have IServiceProvider
as a parameter in the Configure
class.
Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
One level up, I have used:
str_replace(basename(__DIR__) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';
or for php < 5.3:
str_replace(basename(dirname(__FILE__)) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';
I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py
This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.
Here is an optimized version of encoder for the accepted answer, that also supports line-breaking for MIME and other protocols (simlar optimization can be applied to the decoder):
char *base64_encode(const unsigned char *data,
size_t input_length,
size_t *output_length,
bool addLineBreaks)
*output_length = 4 * ((input_length + 2) / 3);
if (addLineBreaks) *output_length += *output_length / 38; // CRLF after each 76 chars
char *encoded_data = malloc(*output_length);
if (encoded_data == NULL) return NULL;
UInt32 octet_a;
UInt32 octet_b;
UInt32 octet_c;
UInt32 triple;
int lineCount = 0;
int sizeMod = size - (size % 3); // check if there is a partial triplet
// adding all octet triplets, before partial last triplet
for (; offset < sizeMod; )
{
octet_a = data[offset++];
octet_b = data[offset++];
octet_c = data[offset++];
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[mBufferPos++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 0 * 6) & 0x3F];
if (addLineBreaks)
{
if (++lineCount == 19)
{
encoded_data[mBufferPos++] = 13;
encoded_data[mBufferPos++] = 10;
lineCount = 0;
}
}
}
// last bytes
if (sizeMod < size)
{
octet_a = data[offset++]; // first octect always added
octet_b = offset < size ? data[offset++] : (UInt32)0; // conditional 2nd octet
octet_c = (UInt32)0; // last character is definitely padded
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[mBufferPos++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[mBufferPos++] = encoding_table[(triple >> 0 * 6) & 0x3F];
// add padding '='
sizeMod = size % 3;
// last character is definitely padded
encoded_data[mBufferPos - 1] = (byte)'=';
if (sizeMod == 1) encoded_data[mBufferPos - 2] = (byte)'=';
}
}
I use the suffixes
option in .merge()
:
dfNew = df.merge(df2, left_index=True, right_index=True,
how='outer', suffixes=('', '_y'))
dfNew.drop(dfNew.filter(regex='_y$').columns.tolist(),axis=1, inplace=True)
Thanks @ijoseph
At the command line paste the following
export QUERY_STRING="param1=abc¶m2=xyz" ;
POST_STRING="name=John&lastname=Doe" ; php -e -r
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"],
$_POST); include "index.php";'
I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream
>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>
However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!
You can also use this, it will check the string for lower and uppercase
var s = "a"
if(/[a-z]/.test(s)){
alert ('lower case true');
}
if(/[A-Z]/.test(s)) {
alert ('upper case true');
}
You could use an AlertDialog
for this and construct one using its Builder
class. The example below uses the default constructor that only takes in a Context
since the dialog will inherit the proper theme from the Context you pass in, but there's also a constructor that allows you to specify a specific theme resource as the second parameter if you desire to do so.
new AlertDialog.Builder(context)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Hello There is an example:
import numpy as np
import matplotlib.pyplot as ptl
def grafica_seno_coseno():
x = np.arange(-4,2*np.pi, 0.3)
y = 2*np.sin(x)
y2 = 3*np.cos(x)
ptl.plot(x, y, '-gD')
ptl.plot(x, y2, '-rD')
for xitem,yitem in np.nditer([x,y]):
etiqueta = "{:.1f}".format(xitem)
ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
for xitem,y2item in np.nditer([x,y2]):
etiqueta2 = "{:.1f}".format(xitem)
ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")
ptl.grid(True)
return ptl.show()
You can open any of the following files:
/etc/profile
~/.bash_profile
~/.bash_login (if .bash_profile does not exist)
~/.profile (if .bash_login does not exist)
And add:
export PATH="$PATH:your/new/path/here"
If this issue is happening in Wildfly 8 and JDK1.8,then we need to specify MaxMetaSpace settings instead of PermGen settings.
For example we need to add below configuration in setenv.sh file of wildfly.
JAVA_OPTS="$JAVA_OPTS -XX:MaxMetaspaceSize=256M"
For more information, please check Wildfly Heap Issue
Try This Simple and Effective
.home > span + .red{
border:1px solid red;
}
We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST
some data to www.abc.com/blog
and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog
from the same user. So it'll give the 409
error.
Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database.
Stick to using single quotes.
That's the primary use anyway. You can use single quotes for a column alias — where you want the column name you reference in your application code to be something other than what the column is actually called in the database. For example: PRODUCT.id
would be more readable as product_id
, so you use either of the following:
SELECT PRODUCT.id AS product_id
SELECT PRODUCT.id 'product_id'
Either works in Oracle, SQL Server, MySQL… but I know some have said that the TOAD IDE seems to give some grief when using the single quotes approach.
You do have to use single quotes when the column alias includes a space character, e.g., product id
, but it's not recommended practice for a column alias to be more than one word.
Try this:
Dim myarray As Variant
myarray = Array("Cat", "Dog", "Rabbit")
I was getting the same error in python 3.4.3 too and I tried using the solutions mentioned here and elsewhere with no success.
Microsoft makes a compiler available for Python 2.7 but it didn't do me much good since I am on 3.4.3.
Python since 3.3 has transitioned over to 2010 and you can download and install Visual C++ 2010 Express for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express
Here is the official blog post talking about the transition to 2010 for 3.3: http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html
Because previous versions gave a different error for vcvarsall.bat I would double check the version you are using with "pip -V"
C:\Users\B>pip -V
pip 6.0.8 from C:\Python34\lib\site-packages (python 3.4)
As a side note, I too tried using the latest version of VC++ (2013) first but it required installing 2010 express.
From that point forward it should work for anyone using the 32 bit version, if you are on the 64 bit version you will then get the ValueError: ['path'] message because VC++ 2010 doesn't have a 64 bit compuler. For that you have to get the Microsoft SDK 7.1. I can't hyperlink the instruction for 64 bit because I am limited to 2 links per post but its at
Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)
I needed one application to run on multiple subdomains. So in bootstrap/app.php
I added something like:
$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);
The preprocessor is looking for StdCUtil/split.h
in
./
(i.e. /root/Core/
, the directory that contains the #include statement). So ./
+ StdCUtil/split.h
= ./StdCUtil/split.h
and the file is missingand in
$INC_DIR
(i.e. ../StdCUtil/
= /root/Core/../StdCUtil/
= /root/StdCUtil/
). So ../StdCUtil/
+ StdCUtil/split.h
= ../StdCUtil/StdCUtil/split.h
and the file is missingYou can fix the error changing the $INC_DIR
variable (best solution):
$INC_DIR = ../
or the include directive:
#include "split.h"
but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.
Reference:
EDIT/UPDATE
It should also be
CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)
...
%.o: %.cpp $(DEPS)
$(CXX) -o $@ $< $(CXXFLAGS)
Let's say you have a column 'birth_day' in your table which is in string format, you should use the following query to filter using birth_day
date_Format(birth_day, 'yyyy-MM-dd')
You can use it in a query in the following way
select * from yourtable
where
date_Format(birth_day, 'yyyy-MM-dd') = '2019-04-16';
Edit:
Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs
See the working example: http://jsfiddle.net/U6aKT/
<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>
Try this :
DGV.AutoResizeColumns();
DGV.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.AllCells;
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
One possible solution is to encode the data in your app and use decoding at runtime (when you want to use that data). I also recommend to use progaurd to make it hard to read and understand the decompiled source code of your app . for example I put a encoded key in the app and then used a decode method in my app to decode my secret keys at runtime:
// "the real string is: "mypassword" ";
//encoded 2 times with an algorithm or you can encode with other algorithms too
public String getClientSecret() {
return Utils.decode(Utils
.decode("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
Decompiled source code of a proguarded app is this:
public String c()
{
return com.myrpoject.mypackage.g.h.a(com.myrpoject.mypackage.g.h.a("Ylhsd1lYTnpkMjl5WkE9PQ=="));
}
At least it's complicated enough for me. this is the way I do when I have no choice but store a value in my application. Of course we all know It's not the best way but it works for me.
/**
* @param input
* @return decoded string
*/
public static String decode(String input) {
// Receiving side
String text = "";
try {
byte[] data = Decoder.decode(input);
text = new String(data, "UTF-8");
return text;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error";
}
Decompiled version:
public static String a(String paramString)
{
try
{
str = new String(a.a(paramString), "UTF-8");
return str;
}
catch (UnsupportedEncodingException localUnsupportedEncodingException)
{
while (true)
{
localUnsupportedEncodingException.printStackTrace();
String str = "Error";
}
}
}
and you can find so many encryptor classes with a little search in google.
Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).
If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.
Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
You should be able to accomplish this by using location.href
if(window.location.hostname == "www.myweb.com"){
window.location.href = window.location.href + "?single";
}
Simply use the center
tag just after the body
tag, and end the center
tag just before body
ends:
<body>
<center>
... Your code here ...
</center>
</body>
This worked for me with all the browsers I have tried.
you can do something for a list object,
data("mtcars")
rownames(mtcars)
data <- list(mtcars ,mtcars, mtcars, mtcars);data
out1 <- NULL
for(i in seq_along(data)) {
out1[[i]] <- data[[i]][rownames(data[[i]]) != "Volvo 142E", ] }
out1
Or a data frame,
data("mtcars")
df <- mtcars
out1 <- NULL
for(i in 1:nrow(df)) {
row <- rownames(df[i,])
# do stuff with row
out1 <- df[rownames(df) != "Volvo 142E",]
}
out1
It is good that you've found your solution. But it is an interesting problem. I tried it out myself directly with sqlite3 (not going through rails) and did not get the same result, for me the order came out as expected.
What I suggest you to do if you want to continue digging in this problem is to start the sqlite3 command-line application and check the schema and the queries there:
This shows you the schema: .schema
And then just run the select statement as it showed up in the log files: SELECT * FROM "shows" ORDER BY date ASC, attending DESC
That way you see if:
Typescript from v1.4 has the type
keyword which declares a type alias (analogous to a typedef
in C/C++). You can declare your callback type thus:
type CallbackFunction = () => void;
which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:
type CallbackFunctionVariadic = (...args: any[]) => void;
Then you can say, for example,
let callback: CallbackFunctionVariadic = function(...args: any[]) {
// do some stuff
};
If you want a function that takes an arbitrary number of arguments and returns anything (including void):
type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;
You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:
type CallbackFunctionSomeVariadic =
(arg1: string, arg2: number, ...args: any[]) => void;
This can be useful for things like EventEmitter handlers.
Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.
You have a couple options, you could setTimeout()
or setInterval()
. Here's a great article that elaborates on how to use them.
The magic is that they're built in to JavaScript, you can use them with any library.
Was the Tomcat running before you restarted it? Was there any other app listening on this port?
The exception is thrown because there was nobody listening on the command port (see <Server port="..."
in $tomcat_home/conf/server.xml
).
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
You can do it like this using Lodash get
_.get(object, 'a[0].b.c');
You can use .rstrip('\n')
to only remove newlines from the end of the string:
for i in contents:
alist.append(i.rstrip('\n'))
This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip()
.
However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines()
method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read()
result and don't use file.readlines()
at all:
alist = t.read().splitlines()
+ (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {
//If scaleFactor is not touched, no scaling will occur
CGFloat scaleFactor = 1.0;
//Deciding which factor to use to scale the image (factor = targetSize / imageSize)
if (image.size.width > targetSize.width || image.size.height > targetSize.height)
if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
UIGraphicsBeginImageContext(targetSize);
//Creating the rect where the scaled image is drawn in
CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2,
(targetSize.height - image.size.height * scaleFactor) / 2,
image.size.width * scaleFactor, image.size.height * scaleFactor);
//Draw the image into the rect
[image drawInRect:rect];
//Saving the image, ending image context
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
I propose this one. Isn't she a beauty? ;)
You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):
declare @p1 dbo.string_list_type
insert into @p1 values(N'myFirstString')
insert into @p1 values(N'mySecondString')
Example use when executing a stored proc:
exec MyStoredProc @MyParam=@p1
You can use the scrollbar-width
rule. You can scrollbar-width: none;
to hide the scrollbar in Firefox and still be able to scroll freely.
body {
scrollbar-width: none;
}
You can use:
cell.getCellTypeEnum()
Further to compare the cell type, you have to use CellType as follows:-
if(cell.getCellTypeEnum() == CellType.STRING){
.
.
.
}
You can Refer to the documentation. Its pretty helpful:-
https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html
Strings aren't the only choice for representing numbers: you can use a list of integers to represent the order of each digit. Those can easily be converted to a string.
None of the answers reject base < 2; and most will run very slowly or crash with stack overflows for very large numbers (such as 56789 ** 43210). To avoid such failures, reduce quickly like this:
def n_to_base(n, b):
if b < 2: raise # invalid base
if abs(n) < b: return [n]
ret = [y for d in n_to_base(n, b*b) for y in divmod(d, b)]
return ret[1:] if ret[0] == 0 else ret # remove leading zeros
def base_to_n(v, b):
h = len(v) // 2
if h == 0: return v[0]
return base_to_n(v[:-h], b) * (b**h) + base_to_n(v[-h:], b)
assert ''.join(['0123456789'[x] for x in n_to_base(56789**43210,10)])==str(56789**43210)
Speedwise, n_to_base
is comparable with str
for large numbers (about 0.3s on my machine), but if you compare against hex
you may be surprised (about 0.3ms on my machine, or 1000x faster). The reason is because the large integer is stored in memory in base 256 (bytes). Each byte can simply be converted to a two-character hex string. This alignment only happens for bases that are powers of two, which is why there are special cases for 2,8, and 16 (and base64, ascii, utf16, utf32).
Consider the last digit of a decimal string. How does it relate to the sequence of bytes that forms its integer? Let's label the bytes s[i]
with s[0]
being the least significant (little endian). Then the last digit is sum([s[i]*(256**i) % 10 for i in range(n)])
. Well, it happens that 256**i ends with a 6 for i > 0 (6*6=36) so that last digit is (s[0]*5 + sum(s)*6)%10
. From this, you can see that the last digit depends on the sum of all the bytes. This nonlocal property is what makes converting to decimal harder.
Here's a variation of Oscar's first version that doesn't use a for-each loop.
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'q') {
// do something
break;
}
}
You could have a boolean variable that gets set to false before the loop, then make "do something" set the variable to true, which you could test for after the loop. The loop could also be wrapped in a function call then just use 'return true' instead of the break, and add a 'return false' statement after the for loop.
To define an array of strings it is more comfortable to use $var = @('User1 ', 'User2 ').
$servername = hostname
$smtpserver = 'localhost'
$emailTo = @('username1 <[email protected]>', 'username2<[email protected]>')
$emailFrom = 'SomeServer <[email protected]>'
Send-MailMessage -To $emailTo -Subject 'Low available memory' -Body 'Warning' -SmtpServer $smtpserver -From $emailFrom
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
This was happening for me because I had fromArrayName
instead of formArrayName
somewhere
And if you want to specify select's ID:
$("#nextPageLink").click(function(){
$('#myselect option:selected').next('option').attr('selected', 'selected');
$("#myselect").change();
});
If you click on item with id "nextPageLink", next option will be selected and onChange() event will be called. It may look like this:
$("#myselect").change(function(){
$('#myDivId').load(window.location.pathname,{myvalue:$("select#myselect").val()});
});
OnChange() event uses Ajax to load something into specified div.
window.location.pathname = actual address
OnChange() event is defined because it allowes you to change value not only using netx/prev button, but directly using standard selection. If value is changed, page does somethig automatically.
Yet another way to do it:
//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();
you can use webview to show the pdf inside an application , for that you have to :
Many pdf to html online converter available.
Example:
consent_web = (WebView) findViewById(R.id.consentweb);
consent_web.getSettings().setLoadWithOverviewMode(true);
consent_web.getSettings().setUseWideViewPort(true);
consent_web.loadUrl("file:///android_asset/spacs_html.html");
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
You need to do it on the UI thread. Use:
Dispatcher.BeginInvoke(new Action(() => {GetGridData(null, 0)}));
map
isn't particularly pythonic. I would recommend using list comprehensions instead:
map(f, iterable)
is basically equivalent to:
[f(x) for x in iterable]
map
on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:
[(a, b) for a in iterable_a for b in iterable_b]
The syntax is a little confusing -- that's basically equivalent to:
result = []
for a in iterable_a:
for b in iterable_b:
result.append((a, b))
If you are only doing GET requests and you need another simple solution from within your Chrome browser, just install the "Open Multiple URLs" extension:
https://chrome.google.com/webstore/detail/open-multiple-urls/oifijhaokejakekmnjmphonojcfkpbbh?hl=en
I've just ran 1500 url's at once, did lag google a bit but it works.
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
I had the same error, although in my case the problem was with the formatting of the DESTINATION path. The comments above are correct with respect to debugging the path string formatting, but there seems to be a bug in the File.Copy exception reporting where it still throws back the SOURCE path instead of the DESTINATION path. So don't forget to look here as well.
-TC
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
if your conditionals are like that (matching a single value), a simple more elegant way would be:
$results = User::where([
'this' => value,
'that' => value,
'this_too' => value,
...
])
->get();
but if you need to OR the clauses then make sure for each orWhere() clause you repeat the must meet conditionals.
$player = Player::where([
'name' => $name,
'team_id' => $team_id
])
->orWhere([
['nickname', $nickname],
['team_id', $team_id]
])
I use this:
logging.conf:
[loggers]
keys=root,applog
[handlers]
keys=rotateFileHandler,rotateConsoleHandler
[formatters]
keys=applog_format,console_format
[formatter_applog_format]
format=%(asctime)s-[%(levelname)-8s]:%(message)s
[formatter_console_format]
format=%(asctime)s-%(filename)s%(lineno)d[%(levelname)s]:%(message)s
[logger_root]
level=DEBUG
handlers=rotateFileHandler,rotateConsoleHandler
[logger_applog]
level=DEBUG
handlers=rotateFileHandler
qualname=simple_example
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=applog_format
args=('applog.log', 'a', 10000, 9)
[handler_rotateConsoleHandler]
class=StreamHandler
level=DEBUG
formatter=console_format
args=(sys.stdout,)
testapp.py:
import logging
import logging.config
def main():
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('applog')
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
#logging.shutdown()
if __name__ == '__main__':
main()
I like the answer of R. slightly tweaked:
float f = 1234.56789;
printf("%d.%.0f", f, 1000*(f-(int)f));
'1000' determines the precision.
Power to the 0.5 rounding.
EDIT
Ok, this answer was edited a few times and I lost track what I was thinking a few years back (and originally it did not fill all the criteria). So here is a new version (that fills all criteria and handles negative numbers correctly):
double f = 1234.05678900;
char s[100];
int decimals = 10;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);
And the test cases:
#import <stdio.h>
#import <stdlib.h>
#import <math.h>
int main(void){
double f = 1234.05678900;
char s[100];
int decimals;
decimals = 10;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf("10 decimals: %d%s\n", (int)f, s+1);
decimals = 3;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf(" 3 decimals: %d%s\n", (int)f, s+1);
f = -f;
decimals = 10;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf(" negative 10: %d%s\n", (int)f, s+1);
decimals = 3;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf(" negative 3: %d%s\n", (int)f, s+1);
decimals = 2;
f = 1.012;
sprintf(s,"%.*g", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));
printf(" additional : %d%s\n", (int)f, s+1);
return 0;
}
And the output of the tests:
10 decimals: 1234.056789
3 decimals: 1234.057
negative 10: -1234.056789
negative 3: -1234.057
additional : 1.01
Now, all criteria are met:
Unfortunately this answer is a two-liner as sprintf
does not return the string.
Doing the above :
x = x[~numpy.isnan(x)]
or
x = x[numpy.logical_not(numpy.isnan(x))]
I found that resetting to the same variable (x) did not remove the actual nan values and had to use a different variable. Setting it to a different variable removed the nans. e.g.
y = x[~numpy.isnan(x)]
Considering all of your API requests located with a url pattern of /api/..
you can tell spring to secure only this url pattern by using below configuration. Which means that you are telling spring what to secure instead of what to ignore.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
In your config.xml file add this line:
<preference name="loadUrlTimeoutValue" value="700000" />
sys.argv[0]
is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]
You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.
CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4
Mind that you need to use the wildcards in PATINDEX on either side.
To solve this error, it is enough to add from google.colab import files
in your code!
Replacing the \n
or the escaped <br/>
does the trick while keeping the rest of the HTML escaped:
$(document).tooltip({
content: function() {
var title = $(this).attr("title") || "";
return $("<a>").text(title).html().replace(/<br *\/?>/, "<br/>");
},
});
If you put in
SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009'
it will automatically convert the string '1/20/2009'
into the DateTime
format for a date of 1/20/2009 00:00:00
. So by using >=
you should get every user whose registration date is 1/20/2009 or more recent.
Edit: I put this in the comment section but I should probably link it here as well. This is an article detailing some more in depth ways of working with DateTime's in you queries: http://www.databasejournal.com/features/mssql/article.php/2209321/Working-with-SQL-Server-DateTime-Variables-Part-Three---Searching-for-Particular-Date-Values-and-Ranges.htm
In case someone need an equivalent for macOS like I did, here is it:
lsof -i tcp:8080
After you get the PID
of the process, you can kill it with:
kill -9 <PID>
Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).
This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.
Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).
Try putting it in quotes:
find . -name '*test.c'
For me issue with 'DOMAIN\MACHINENAME$' fixed by setting DefaultApplicationPool
Identity to NetworkService
.
myFile = open('today','r')
ips = {}
for line in myFile:
parts = line.split()
if parts[1] == 'Failure':
ips.setdefault(parts[0], 0)
ips[parts[0]] += 1
of = open('failed.py', 'w')
for ip in [k for k, v in ips.iteritems() if v >=5]:
of.write(k+'\n')
Check out setdefault, it makes the code a little more legible. Then you dump your data with the file object's write method.
If you don't hold a reference to the editor, as in Aeon's answer, you can also use the form:
var value = CKEDITOR.instances['my-editor'].getData();
Everybody that using: var myVar = 'token', is probably the worst idea. I can print it dirrectly in the console. You need to encrypt on the client side, then decrypt on server side.
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command
adb logcat > logcat.txt
In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy
for same height you should chage your css "display" Properties. For more detail see given example.
.list{_x000D_
display: table;_x000D_
flex-wrap: wrap;_x000D_
max-width: 500px;_x000D_
}_x000D_
_x000D_
.list-item{_x000D_
background-color: #ccc;_x000D_
display: table-cell;_x000D_
padding: 0.5em;_x000D_
width: 25%;_x000D_
margin-right: 1%;_x000D_
margin-bottom: 20px;_x000D_
}_x000D_
.list-content{_x000D_
width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h2>box 1</h2>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h1>h1</h1>_x000D_
</div>_x000D_
</li>
_x000D_
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
The simplest and best way to achieve this is to use the onmouseup()
JavaScript event rather than onclick()
That way you will fire JavaScript after you click and it won't interfere with the ASP OnClick()
event.
If you also want to name the constraint, use this:
ALTER TABLE myTable
ADD CONSTRAINT constraintName
UNIQUE (columnName);
https://developers.google.com/web/updates/2017/09/abortable-fetch
https://dom.spec.whatwg.org/#aborting-ongoing-activities
// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;
// fetch as usual
fetch(url, { signal }).then(response => {
...
}).catch(e => {
// catch the abort if you like
if (e.name === 'AbortError') {
...
}
});
// when you want to abort
controller.abort();
works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.
on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'
// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch
What do you get when you do puts lines
? That will give you a clue.
By default File.open
opens the file in text mode, so your \r\n
characters will be automatically converted to \n
. Maybe that's the reason lines
are always equal to lines2
. To prevent Ruby from parsing the line ends use the rb
mode:
C:\> copy con lala.txt a file with many lines ^Z C:\> irb irb(main):001:0> text = File.open('lala.txt').read => "a\nfile\nwith\nmany\nlines\n" irb(main):002:0> bin = File.open('lala.txt', 'rb').read => "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n" irb(main):003:0>
But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read
.
By default, the DirectoryIndex is set to:
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.
The order should be DirectoryIndex index.html index.php
// default is index.html
Reference: Here.
according to the mySQL reference manual this the syntax of using if and else statement :
IF search_condition THEN statement_list [ELSEIF search_condition THEN statement_list] ... [ELSE statement_list] END IF
So regarding your query :
x = IF((action=2)&&(state=0),1,2);
or you can use
IF ((action=2)&&(state=0)) then
state = 1;
ELSE
state = 2;
END IF;
There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
If you want to remove a particular directory from the rule (meaning, you want to remove the directory foo) ,you can use :
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/foo/$
RewriteRule !index\.php$ /index.php [L]
The rewriteRule above will rewrite all requestes to /index.php excluding requests for /foo/ .
To exclude all existent directries, you will need to use the following condition above your rule :
RewriteCond %{REQUEST_FILENAME} !-d
the following rule
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !index\.php$ /index.php [L]
rewrites everything (except directries) to /index.php .
Have you tried to delete and re install the device in your Apple Developer portal? If yes, try to upgrade your xcode to 4.3.2, I remember that I needed to update to xCode 4.3.2 after updating my iPhone to iOS 5.1
Regarding the original question asked in the title ...
sudo apt-get install libtcnative-1
or if you are on RHEL Linux yum install tomcat-native
The documentation states you need http://tomcat.apache.org/native-doc/
sudo apt-get install libapr1.0-dev libssl-dev
yum install apr-devel openssl-devel
Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Instead, the variable containing the List is used as if it were an array.
List[index]
See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx
Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.
The HTTP server, by itself, is best for serving up static content... html files, images, etc.
You just need to get selenium package imported, that you can do from command prompt using the command
pip install selenium
When you have to use it in any IDE just import this package, no other documentation required to be imported
For Eg :
import selenium
print(selenium.__filepath__)
This is just a general command you may use in starting to check the filepath of selenium
Just in case someone checked this thread and had the same issue as mine...
Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
I'm using NHibernate, I receive same error, during creating an object...
I was passing the key manually, and also specified a GUID generator in mapping, so hibernate generate same exact error for me, so once I removed the GUID, and left the field empty, everything went just fine.
this answer may not help you, but will help someone like me, who just your thread becasue of same error
function substringBetween(s, a, b) {
var p = s.indexOf(a) + a.length;
return s.substring(p, s.indexOf(b, p));
}
// substringBetween('MyLongString:StringIWant;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;:StringIDontWant;', ':', ';') -> StringIWant
SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.
The following bash script extracts all zip files in the current directory into new dirs with the filename of the zip file, i.e.:
The following files:
myfile1.zip
myfile2.zip
Will be extracted to:
./myfile1/files...
./myfile2/files...
Shell script:
#!/bin/sh
for zip in *.zip
do
dirname=`echo $zip | sed 's/\.zip$//'`
if mkdir "$dirname"
then
if cd "$dirname"
then
unzip ../"$zip"
cd ..
# rm -f $zip # Uncomment to delete the original zip file
else
echo "Could not unpack $zip - cd failed"
fi
else
echo "Could not unpack $zip - mkdir failed"
fi
done
In Java 8 you can do this with one line of code.
If your method doesn't take any parameters, you can use a method reference:
new Thread(MyClass::doWork).start();
Otherwise, you can call the method in a lambda expression:
new Thread(() -> doWork(someParam)).start();
I am using Google API for .Net, but no doubt you can find the same way to obtain this information using other version of API. As user872858 mentioned, scope userinfo.profile has been deprecated (google article) .
To obtain user profile info I use following code (re-written part from google's example):
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = Secrets,
Scopes = new[] { PlusService.Scope.PlusLogin,"https://www.googleapis.com/auth/plus.profile.emails.read" }
});
TokenResponse _token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
CancellationToken.None).Result;
// Create an authorization state from the returned token.
context.Session["authState"] = _token;
// Get tokeninfo for the access token if you want to verify.
Oauth2Service service = new Oauth2Service(
new Google.Apis.Services.BaseClientService.Initializer());
Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
request.AccessToken = _token.AccessToken;
Tokeninfo info = request.Execute();
if (info.VerifiedEmail.HasValue && info.VerifiedEmail.Value)
{
flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = Secrets,
Scopes = new[] { PlusService.Scope.PlusLogin }
});
UserCredential credential = new UserCredential(flow,
"me", _token);
_token = credential.Token;
_ps = new PlusService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = "Your app name",
HttpClientInitializer = credential
});
Person userProfile = _ps.People.Get("me").Execute();
}
Than, you can access almost anything using userProfile.
UPDATE: To get this code working you have to use appropriate scopes on google sign in button. For example my button:
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
data-clientid="646361778467-nb2uipj05c4adlk0vo66k96bv8inqles.apps.googleusercontent.com"
data-accesstype="offline"
data-redirecturi="postmessage"
data-theme="dark"
data-callback="onSignInCallback"
data-cookiepolicy="single_host_origin"
data-width="iconOnly">
</button>
This should work for every default repo:
git pull origin master
If your default branch is different than master
, you will need to specify the branch name:
git pull origin my_default_branch_name
Had the same problem in Windows 10 (don't know if this is relevant).
Had everything set up correctly, the ssh -vT git@myserver
command succeeded, but Gitlab still asked for my password.
Removing then re-creating the key in Gitlab was the trick for me.
if you want selector get the same id, use:
$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
Hi you need to find settings and add a new exclude pattern for history files
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen
.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.
Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.
Oracle SQL:
There is the "IN" Operator in Oracle SQL which can be used for that:
select
namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi');
Fall-through should be used only when it is used as a jump table into a block of code. If there is any part of the code with an unconditional break before more cases, all the case groups should end that way.
Anything else is "evil".
trim() is your choice, but if you want to use replace
method -- which might be more flexiable, you can try the following:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
No, only native iOS applications support push notifications.
UPDATE:
Mac OS X 10.9 & Safari 7 websites can now also send push notifications, but this still does not apply to iOS.
Read the Notification Programming Guide for Websites. Also check out WWDC 2013 Session 614.
SERIOUS DISCLAIMER
This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.
OK, I had to go to the customer premises and found a solution. I:
Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!
Use Where-Object
, like:
Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") |
Where-Object { $_.CreationTime -gt "03/01/2013" -and $_.CreationTime -lt "03/31/2013" }
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} |
Export-Csv 'PATH\scans.csv'
You can also check it using jQuery.. It's quite easy:
<html>
<head>
<title>jQuery: Check if Textbox is empty</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>
<body>
<form name="form1" method="post" action="">
<label for="city">City:</label>
<input type="text" name="city" id="city">
</form>
<button id="check">Check</button>
<script type="text/javascript">
$('#check').click(function () {
if ($('#city').val() == '') {
alert('Empty!!!');
} else {
alert('Contains: ' + $('#city').val());
}
});
</script>
</body>
</html>
Short Answer: After installing "Code Runner" extension, you just have to right-click the selected part of code you wish to execute and see it in the Output Tab.
Right click on project -> maven -> download sources
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
it's nil
in Ruby, not null
. And it's enough to say if @objectname
to test whether it's not nil. And no then
. You can find more on if
syntax here:
http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Control_Structures#if
Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).
You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.
Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.
So, if I have the following NewFile.xml:
<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />
And the eclipse encoding is UTF-8:
The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.
The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.
EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.
When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.
I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.
In my case, I had simply changed the way I created a table and inadvertently changed the field name I tried to query. Make sure the field names you reference in the query actually exist in the table/query you are querying.
When I got this error, I backed up my entire project folder. Then I did something like
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
...depending on your branch name (if it's not master).
Then I did git pull --rebase
. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.
Important! Vertical center is relative to the height of the parent
If the parent of the element you're trying to center has no defined height, none of the vertical centering solutions will work!
Now, onto vertical centering...
Bootstrap 5 (Updated 2020)
Bootstrap 5 is still flexbox based so vertical centering works the same way as Bootstrap 4. For example align-items-center and justify-content-center can used on the flexbox parent (row
or d-flex
). https://codeply.com/p/0VM5MJ7Had
Bootstrap 4
You can use the new flexbox & size utilities to make the container
full-height and display: flex
. These options don't require extra CSS (except that the height of the container (ie:html,body) must be 100%).
Option 1 align-self-center
on flexbox child
<div class="container d-flex h-100">
<div class="row justify-content-center align-self-center">
I'm vertically centered
</div>
</div>
https://codeply.com/go/fFqaDe5Oey
Option 2 align-items-center
on flexbox parent (.row
is display:flex; flex-direction:row
)
<div class="container h-100">
<div class="row align-items-center h-100">
<div class="col-6 mx-auto">
<div class="jumbotron">
I'm vertically centered
</div>
</div>
</div>
</div>
https://codeply.com/go/BumdFnmLuk
Option 3 justify-content-center
on flexbox parent (.card
is display:flex;flex-direction:column
)
<div class="container h-100">
<div class="row align-items-center h-100">
<div class="col-6 mx-auto">
<div class="card h-100 border-primary justify-content-center">
<div>
...card content...
</div>
</div>
</div>
</div>
</div>
https://codeply.com/go/3gySSEe7nd
More on Bootstrap 4 Vertical Centering
Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical alignment. http://www.codeply.com/go/WG15ZWC4lf
1 - Vertical Center Using Auto Margins:
Another way to vertically center is to use my-auto
. This will center the element within it's container. For example, h-100
makes the row full height, and my-auto
will vertically center the col-sm-12
column.
<div class="row h-100">
<div class="col-sm-12 my-auto">
<div class="card card-block w-25">Card</div>
</div>
</div>
Vertical Center Using Auto Margins Demo
my-auto
represents margins on the vertical y-axis and is equivalent to:
margin-top: auto;
margin-bottom: auto;
2 - Vertical Center with Flexbox:
Since Bootstrap 4 .row
is now display:flex
you can simply use align-self-center
on any column to vertically center it...
<div class="row">
<div class="col-6 align-self-center">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
or, use align-items-center
on the entire .row
to vertically center align all col-*
in the row...
<div class="row align-items-center">
<div class="col-6">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
Vertical Center Different Height Columns Demo
See this Q/A to center, but maintain equal height
3 - Vertical Center Using Display Utils:
Bootstrap 4 has display utils that can be used for display:table
, display:table-cell
, display:inline
, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.
<div class="row h-50">
<div class="col-sm-12 h-100 d-table">
<div class="card card-block d-table-cell align-middle">
I am centered vertically
</div>
</div>
</div>
Vertical Center Using Display Utils Demo
More examples
Vertical center image in <div>
Vertical center .row in .container
Vertical center and bottom in <div>
Vertical center child inside parent
Vertical center full screen jumbotron
Important! Did I mention height?
Remember vertical centering is relative to the height of the parent element. If you want to center on the entire page, in most cases, this should be your CSS...
body,html {
height: 100%;
}
Or use min-height: 100vh
(min-vh-100
in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.
Also see:
Vertical alignment in bootstrap 4
Bootstrap 4 Center Vertical and Horizontal Alignment
You could make the init
method return this
, and then chain the calls together, like this:
var userB = {
init: function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
return this;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var bob = Object.create(userB).init('Bob');
For python2 you can also do this
'%(author)s in %(publication)s'%{'author':unicode(self.author),
'publication':unicode(self.publication)}
which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)
Python2.6 onwards supports .format()
'{author} in {publication}'.format(author=self.author,
publication=self.publication)
If the table has already been created:
First do:
ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);
Then:
ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);
The answer from @gunn is correct, target="_blank
makes the link open in a new tab.
But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer"
.
<a style={{display: "table-cell"}} href = "someLink" target = "_blank"
rel = "noopener noreferrer">text</a>
There is no "quick-and-dirty" way of doing this. I usually do:
mystring= string.Concat(mystring.Take(mystring.Length-1));
You have to correctly override method equals() from class Object
Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.
Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.
For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().
But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.
There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.
Some of the collections that use hashCode()
Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily
For iOS 8, If there is no need to retain photo capture date and location, just drop photo files to the simulator.
To retain photo meta data, do the following:
Note: You need to replace {USER} with your user name and {UDID} with the UDID of the simulator. To find UDID for your simulator, from Terminal, run 'xcrun simctl list'.
Install Inspect-it
pip3 install inspect-it --user
Code
import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])
you can Make a snippet of this line
it will show you a list of the function call stack with a filename and line number
list from start to where you put this line
This is the only answer you got first when you search for default workspace, but any solution is not solved my problem, So I follow this step for a default workspace:
In Target:
D:\eclipse_path\eclipse.exe -clean -data D:\workspace_path\workspace
For using the same shortcuts and preference into this workspace, Export general --> preference from your working eclipse, it will generate one .epf file.
So, just import .epf file into your new workspace, and you are done.
No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:
Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.
svn checkout https://example.org/path/to/repo/bleh
svn add file1 file2...
svn commit
I am not aware of a quicker option.
Note: if you are on the same machine as your Subversion repository, the URL can use the file:
specifier with a path in place of https:
in the svn checkout
command. For example svn checkout file:///path/to/repo/bleh
.
PS. as pointed out in the comments and other answers, you can use something like svn import . <URL>
if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
If it's only a one dimensional list, this can be done without importing anything:
>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']
Just add a STYLE line and your progress becomes horizontal:
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/progress"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:max="100"
android:progress="45"/>
To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.
Another possible cause is to have the wrong order of RequestMapping attributes. As spring doc says:
An @RequestMapping handler method can have a very flexible signatures. The supported method arguments and return values are described in the following section. Most arguments can be used in arbitrary order with the only exception of BindingResult arguments. This is described in the next section.
If you scroll down the doc, you will see that the BindingResult has to be immediatelly after the model attribute, since we can have multiple model objects per request and thus multiple bindings
The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more than one model object and Spring will create a separate BindingResult instance for each of them so the following sample won’t work:
Here are two examples:
Invalid ordering of BindingResult and @ModelAttribute.
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... } Note, that there is a Model parameter in between Pet and BindingResult. To get this working you have to reorder the parameters as follows:
@RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
You should really post:
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
There is a library which allows you to use HttpClient with strongly-typed callbacks.
The data and the error are available directly via these callbacks.
When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.
This is because Observable<HttpResponse
<T
>> is tied to HttpResponse.
This tightly couples the http layer with the rest of your code.
This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.
With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.
The library is called angular-extended-http-client.
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
Very easy to use.
The strongly-typed callbacks are
Success:
T
>T
>Failure:
TError
>TError
>import { HttpClientExtModule } from 'angular-extended-http-client';
and in the @NgModule imports
imports: [
.
.
.
HttpClientExtModule
],
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
In your Service, you just create params with these callback types.
Then, pass them on to the HttpClientExt's get method.
import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
}
}
In your Component, your Service is injected and the getRaceInfo API called as shown below.
ngOnInit() {
this.service.getRaceInfo(response => this.result = response.result,
error => this.errorMsg = error.className);
}
Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.
You only deal with your Models in these strongly-typed callbacks.
Hence, The rest of your code only knows about your Models.
Also, you can still use the traditional route and return Observable<HttpResponse<
T>
> from Service API.