As of pandas 0.17.0, DataFrame.sort()
is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values
As such, the answer to your question would now be
df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
@everestial007 's solution worked for me. This is how I improved it for my use case, which is to have the columns of each different df with a different suffix so I can more easily differentiate between the dfs in the final merged dataframe.
from functools import reduce
import pandas as pd
dfs = [df1, df2, df3, df4]
suffixes = [f"_{i}" for i in range(len(dfs))]
# add suffixes to each df
dfs = [dfs[i].add_suffix(suffixes[i]) for i in range(len(dfs))]
# remove suffix from the merging column
dfs = [dfs[i].rename(columns={f"date{suffixes[i]}":"date"}) for i in range(len(dfs))]
# merge
dfs = reduce(lambda left,right: pd.merge(left,right,how='outer', on='date'), dfs)
The easiest way to find the best fit in R is to code the model as:
lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)
After using step down AIC regression
lm.s <- step(lm.1)
Here's a C implementation of @Jean-Paul's Smoothed Z-score for the Arduino microcontroller used to take accelerometer readings and decide whether the direction of an impact has come from the left or the right. This performs really well since this device returns a bounced signal. Here's this input to this peak detection algorithm from the device - showing an impact from the right followed by and impact from the left. You can see the initial spike then the oscillation of the sensor.
#include <stdio.h>
#include <math.h>
#include <string.h>
#define SAMPLE_LENGTH 1000
float stddev(float data[], int len);
float mean(float data[], int len);
void thresholding(float y[], int signals[], int lag, float threshold, float influence);
void thresholding(float y[], int signals[], int lag, float threshold, float influence) {
memset(signals, 0, sizeof(float) * SAMPLE_LENGTH);
float filteredY[SAMPLE_LENGTH];
memcpy(filteredY, y, sizeof(float) * SAMPLE_LENGTH);
float avgFilter[SAMPLE_LENGTH];
float stdFilter[SAMPLE_LENGTH];
avgFilter[lag - 1] = mean(y, lag);
stdFilter[lag - 1] = stddev(y, lag);
for (int i = lag; i < SAMPLE_LENGTH; i++) {
if (fabsf(y[i] - avgFilter[i-1]) > threshold * stdFilter[i-1]) {
if (y[i] > avgFilter[i-1]) {
signals[i] = 1;
} else {
signals[i] = -1;
}
filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1];
} else {
signals[i] = 0;
}
avgFilter[i] = mean(filteredY + i-lag, lag);
stdFilter[i] = stddev(filteredY + i-lag, lag);
}
}
float mean(float data[], int len) {
float sum = 0.0, mean = 0.0;
int i;
for(i=0; i<len; ++i) {
sum += data[i];
}
mean = sum/len;
return mean;
}
float stddev(float data[], int len) {
float the_mean = mean(data, len);
float standardDeviation = 0.0;
int i;
for(i=0; i<len; ++i) {
standardDeviation += pow(data[i] - the_mean, 2);
}
return sqrt(standardDeviation/len);
}
int main() {
printf("Hello, World!\n");
int lag = 100;
float threshold = 5;
float influence = 0;
float y[]= {1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
....
1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3, 2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1}
int signal[SAMPLE_LENGTH];
thresholding(y, signal, lag, threshold, influence);
return 0;
}
Hers's the result with influence = 0
Not great but here with influence = 1
which is very good.
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
Use jquery.ajaxchimp plugin to achieve that. It's dead easy!
<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
<input type="text" name="EMAIL" placeholder="e-mail address" />
<input type="submit" name="subscribe" value="subscribe!" />
<p class="result"></p>
</form>
JavaScript:
$(function() {
$('form').ajaxChimp({
callback: function(response) {
$('form .result').text(response.msg);
}
});
})
It's funny to see this question gets so many attentions and complicated solutions, which indeed shows a pain to not have a clean method with cmake.
Well, you can definitely cd build
to do you work, then do a rm -rf *
when you need to clean. However, rm -rf *
is a dangerous command given that many people are often not aware which dir they are in.
If you cd ..
, rm -rf build
and then mkdir build
and then cd build
, that's just too much typing.
So a good solution is to just stay out of the build folder and tell cmake the path:
to configure: cmake -B build
to build: cmake --build build
to clean: rm -rf build
to recreate build folder: you don't even need mkdir build
, just configure it with cmake -B build
and cmake will create it
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
EDIT: As pointed out in the comments, this is not the correct answer to the OPs question, but it is useful to know this command. This question showed up in Google for what I was looking for, and figured I'd leave this answer for the others to find.
SHOW CREATE TABLE `<yourtable>`;
I found this answer here: MySQL : show constraints on tables command
I needed this way because I wanted to see how the FK functioned, rather than just see if it existed or not.
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start(). The result is a new instance of class Thread, which is called join().
not need to run queries to sidable FKs on sql. If you have a FK from table A to B, you should:
You can also tell the destination not to check constraints
Use the built-in VBA function Val, if the numbers are at the front end of the string:
Dim str as String
Dim lng as Long
str = "1 149 xyz"
lng = Val(str)
lng = 1149
A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings
Right-click your C++ and chose the "Properties" item to get to the properties window.
Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
In the "Preprocessor definitions" add
_CRT_SECURE_NO_WARNINGS
but it would be a good idea to add
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
as to inherit predefined definitions
IMHO & for the most part this is a good approach.
In-case someone is still looking for a solution without dependency and If you have a file.
DataInputStream
byte[] data = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(data);
dis.close();
ByteArrayOutputStream
InputStream is = new FileInputStream(file);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[(int) file.length()];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
RandomAccessFile
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] data = new byte[(int) raf.length()];
raf.readFully(data);
To check if a path is an existing file:
Return
True
if path is an existing regular file. This follows symbolic links, so bothislink()
andisfile()
can be true for the same path.
After trying everything between Stackoverflow and Google, I finally found a solution : http://blogs.lessthandot.com/index.php/datamgmt/dbadmin/remote-procedure-call-failed/
TL;DR :
If you are (or were) running multiple versions of SQL Server on your machine, that Configuration Manager shortcut on your start menu might be pointing to an older version, which it shouldn't be. It was pointing to an old Sql Server 2008 instance in my case.
The solution was to :
Try setting the timeout value in your web service proxy class:
WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds
I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.
Antonio's answer
CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
is wrong; it may produce incorrect results!
For example, if "number" is 12345.67, the resulting string would be:
'12.346,67'
instead of
'12.345,67'
because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!
What you COULD use is
CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))
if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.
for i in range (1,10):
string="string"+str(i)
To get string0, string1 ..... string10
, you could do like
>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']
I'd suggest doing this with a combination of
overflow-y: hidden;
scrolling="no"
(for HTML4)seamless="seamless"
(for HTML5)* The seamless
attribute has been removed from the standard, and no browsers support it.
.foo {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
class="foo" _x000D_
scrolling="no" >_x000D_
</iframe>
_x000D_
In the popup window, overloads the method Show() with a parameter:
Public Overloads Sub Show(Caller As Window)
Me.Owner = Caller
MyBase.Show()
End Sub
Then in the Main window, call your overloaded method Show():
Dim Popup As PopupWindow
Popup = New PopupWindow
Popup.Show(Me)
Already answered above, but here's another approach you could take. I can't find the original post I adapted this from, but here's the code for the sake of your question. As noted above, the flatMap() function is what you'd be looking to utilize with Java 8. You can throw it in a utility class and just call "RandomUtils.combine(list1, list2, ...);" and you'd get a single List with all values. Just be careful with the wildcard - you could change this if you want a less generic method. You can also modify it for Sets - you just have to take care when using flatMap() on Sets to avoid data loss from equals/hashCode methods due to the nature of the Set interface.
Edit - If you use a generic method like this for the Set interface, and you happen to use Lombok, make sure you understand how Lombok handles equals/hashCode generation.
/**
* Combines multiple lists into a single list containing all elements of
* every list.
*
* @param <T> - The type of the lists.
* @param lists - The group of List implementations to combine
* @return a single List<?> containing all elements of the passed in lists.
*/
public static <T> List<?> combine(final List<?>... lists) {
return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
}
You can use join
with pop
+ tolist
. Performance is comparable to concat
with drop
+ tolist
, but some may find this syntax cleaner:
res = df.join(pd.DataFrame(df.pop('b').tolist()))
Benchmarking with other methods:
df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})
def joris1(df):
return pd.concat([df.drop('b', axis=1), df['b'].apply(pd.Series)], axis=1)
def joris2(df):
return pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
def jpp(df):
return df.join(pd.DataFrame(df.pop('b').tolist()))
df = pd.concat([df]*1000, ignore_index=True)
%timeit joris1(df.copy()) # 1.33 s per loop
%timeit joris2(df.copy()) # 7.42 ms per loop
%timeit jpp(df.copy()) # 7.68 ms per loop
See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx
I was able to implement the Child
form inside the parent.
In the Example below Form2
should change to the name of your child form.
NewMDIChild.MdiParent=me
is the main form since the control that opens (shows) the child form is the parent or Me
.
NewMDIChild.Show()
is your child form since you associated your child form with Dim NewMDIChild As New Form2()
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Dim NewMDIChild As New Form2()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
End Sub
Simple and it works.
It didn't work for me:
C:\Program Files\Git\mingw64\libexec\git-core
git-credential-manager.exe uninstall
Looking for Git installation(s)...
C:\Program Files\Git
Updated your /etc/gitconfig [git config --system]
Updated your ~/.gitconfig [git config --global]
Removing from 'C:\Program Files\Git'.
removal failed. U_U
Press any key to continue...
But with the --force
flag it worked:
C:\Program Files\Git\mingw64\libexec\git-core
git credential-manager uninstall --force
08:21:42.537616 exec_cmd.c:236 trace: resolved executable dir: C:/Program Files/Git/mingw64/libexec/git-core
e
08:21:42.538616 git.c:576 trace: exec: git-credential-manager uninstall --force
08:21:42.538616 run-command.c:640 trace: run_command: git-credential-manager uninstall --force
Looking for Git installation(s)...
C:\Program Files\Git
Updated your /etc/gitconfig [git config --system]
Updated your ~/.gitconfig [git config --global]
Success! Git Credential Manager for Windows was removed! ^_^
Press any key to continue...
I could see that trace after I run:
set git_trace=1
Also I added the Git username:
git config --global credential.username myGitUsername
Then:
C:\Program Files\Git\mingw64\libexec\git-core
git config --global credential.helper manager
In the end I put in this command:
git config --global credential.modalPrompt false
I check if the SSH agent is running - open a Bash window to run this command
eval "$(ssh-agent -s)"
Then in the computer users/yourName folder where .ssh is, add a connection (still in Bash):
ssh-add .ssh/id_rsa
or
ssh-add ~/.ssh/id_rsa(if you are not in that folder)
I checked all the settings that I add above:
C:\Program Files\Git\mingw64\libexec\git-core
git config --list
09:41:28.915183 exec_cmd.c:236 trace: resolved executable dir: C:/Program Files/Git/mingw64/libexec/git-cor
e
09:41:28.917182 git.c:344 trace: built-in: git config --list
09:41:28.918181 run-command.c:640 trace: run_command: unset GIT_PAGER_IN_USE; LESS=FRX LV=-c less
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
credential.modalprompt=false
credential.username=myGitUsername
And when I did git push
again I had to add username and password only for the first time.
git push
Please enter your GitHub credentials for https://[email protected]/
username: myGithubUsername
password: *************
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 316 bytes | 316.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
Since then using git push
, I don't have the message to enter my Git credentials any more.
D:\projects\react-redux\myProject (master -> origin) ([email protected])
? git push
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 314 bytes | 314.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To https://github.com/myGitUsername/myProject.git
8d38b18..f442d74 master -> master
After these settings I received an email too with the message:
A personal access token (git: https://[email protected]/
on LAP0110 at 25-Jun-2018 09:22) with gist and repo scopes was recently added
to your account. Visit https://github.com/settings/tokens for more information.
myfile.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
myfile.c
#include "myfile.h"
void function() {
}
In my case, I just needed to close my pop-up and redirect the user to his profile page when he clicks "ok" after reading some message I tried with a few hacks, including setTimeout + self.close(), but with IE, this was closing the whole tab...
Solution :
I replaced my link with a simple submit button.
<button type="submit" onclick="window.location.href='profile.html';">buttonText</button>
.
Nothing more.
This may sound stupid, but I didn't think to such a simple solution, since my pop-up did not have any form.
I hope it will help some front-end noobs like me !
The code below will show difference for found values only, i.e., if years = 0, then it will not show years.
$diffs = [
'years' => 'y',
'months' => 'm',
'days' => 'd',
'hours' => 'h',
'minutes' => 'i',
'seconds' => 's'
];
$interval = $timeout->diff($timein);
$diffArr = [];
foreach ($diffs as $k => $v) {
$d = $interval->format('%' . $v);
if ($d > 0) {
$diffArr[] = $d . ' ' . $k;
}
}
$diffStr = implode(', ', $diffArr);
echo 'Difference: ' . ($diffStr == '' ? '0' : $diffStr) . PHP_EOL;
To make the answer simple here is a program that reads integers from the file and sorting them
f = open("input.txt", 'r')
nums = f.readlines()
nums = [int(i) for i in nums]
After reading each line of the file converting each string to a digit
nums.sort()
Sorting the numbers
f.close()
f = open("input.txt", 'w')
for num in nums:
f.write("%d\n" %num)
f.close()
Writing them back As easy as that, Hope this helps
here it's the solution for if there have any assigned values inside the string.xml file.
<string name="styled_welcome_message"><![CDATA[We are <b> %1$s </b> glad to see you.]]></string>
set in to TextView:
textView?.setText(HtmlCompat.fromHtml(getString(R.string.styled_welcome_message, "sample"), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE)
I wrote a package (https://github.com/alexsanjoseph/compareDF) since I had the same issue.
> df1 <- data.frame(a = 1:5, b=letters[1:5], row = 1:5)
> df2 <- data.frame(a = 1:3, b=letters[1:3], row = 1:3)
> df_compare = compare_df(df1, df2, "row")
> df_compare$comparison_df
row chng_type a b
1 4 + 4 d
2 5 + 5 e
A more complicated example:
library(compareDF)
df1 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
"Hornet 4 Drive", "Duster 360", "Merc 240D"),
id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Mer"),
hp = c(110, 110, 181, 110, 245, 62),
cyl = c(6, 6, 4, 6, 8, 4),
qsec = c(16.46, 17.02, 33.00, 19.44, 15.84, 20.00))
df2 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
"Hornet 4 Drive", " Hornet Sportabout", "Valiant"),
id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Val"),
hp = c(110, 110, 93, 110, 175, 105),
cyl = c(6, 6, 4, 6, 8, 6),
qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22))
> df_compare$comparison_df
grp chng_type id1 id2 hp cyl qsec
1 1 - Hornet Sportabout Dus 175 8 17.02
2 2 + Datsun 710 Dat 181 4 33.00
3 2 - Datsun 710 Dat 93 4 18.61
4 3 + Duster 360 Dus 245 8 15.84
5 7 + Merc 240D Mer 62 4 20.00
6 8 - Valiant Val 105 6 20.22
The package also has an html_output command for quick checking
You can group those first according to some criteria. In this post I will just explain the underscore character and the right-arrow.
_._
contains a period. A period in Scala always indicates a method call. So left of the period you have the receiver, and right of it the message (method name). Now _
is a special symbol in Scala. There are several posts about it, for example this blog entry all use cases. Here it is an anonymous function short cut, that is it a shortcut for a function that takes one argument and invokes the method _
on it. Now _
is not a valid method, so most certainly you were seeing _._1
or something similar, that is, invoking method _._1
on the function argument. _1
to _22
are the methods of tuples which extract a particular element of a tuple. Example:
val tup = ("Hallo", 33)
tup._1 // extracts "Hallo"
tup._2 // extracts 33
Now lets assume a use case for the function application shortcut. Given a map which maps integers to strings:
val coll = Map(1 -> "Eins", 2 -> "Zwei", 3 -> "Drei")
Wooop, there is already another occurrence of a strange punctuation. The hyphen and greater-than characters, which resemble a right-hand arrow, is an operator which produces a Tuple2
. So there is no difference in the outcome of writing either (1, "Eins")
or 1 -> "Eins"
, only that the latter is easier to read, especially in a list of tuples like the map example. The ->
is no magic, it is, like a few other operators, available because you have all implicit conversions in object scala.Predef
in scope. The conversion which takes place here is
implicit def any2ArrowAssoc [A] (x: A): ArrowAssoc[A]
Where ArrowAssoc
has the ->
method which creates the Tuple2
. Thus 1 -> "Eins"
is actual the call Predef.any2ArrowAssoc(1).->("Eins")
. Ok. Now back to the original question with the underscore character:
// lets create a sequence from the map by returning the
// values in reverse.
coll.map(_._2.reverse) // yields List(sniE, iewZ, ierD)
The underscore here shortens the following equivalent code:
coll.map(tup => tup._2.reverse)
Note that the map
method of a Map passes in the tuple of key and value to the function argument. Since we are only interested in the values (the strings), we extract them with the _2
method on the tuple.
Use @@ROWCOUNT:
SELECT * FROM service s WHERE s.service_id = ?;
IF @@ROWCOUNT > 0
-- do stuff here.....
According to SQL Server Books Online:
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
I had issues with rowcount always returning -1 no matter what solution I tried.
I found the following a good replacement to check for a null result.
c.execute("SELECT * FROM users WHERE id=?", (id_num,))
row = c.fetchone()
if row == None:
print("There are no results for this query")
Well first of all there's no such thing as "arrays" in Python, Python uses lists and that does make a difference, I suggest you use NumPy which is a pretty good library for Python and it adds a lot of Matlab-like functionality.You can get started here Numpy for Matlab users
EG : COMPARE TO VILLAGE NAME
ALTER PROCEDURE POSMAST
(@COLUMN_NAME VARCHAR(50))
AS
SELECT * FROM TABLE_NAME
WHERE
village_name LIKE + @VILLAGE_NAME + '%';
Check that the directory the keytool executable is in is on your %PATH%
environment variable.
For example, on my Windows 7 machine, it is in
C:\Program Files (x86)\Java\jre6\bin
, and my %PATH%
variable looks like C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Java\jre6\bin;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
(and many other entries)
Version 1.3.0 has flaw IMO.
Downgrade to version 1.2.3 fixes my problem.
I'm on
I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...
There is a line of code to uncommment in order to have it return JSON.
I see timeouts used for this a lot, but in the context of an event, can't you look at coordinates, like this?:
function areXYInside(e){
var w=e.target.offsetWidth;
var h=e.target.offsetHeight;
var x=e.offsetX;
var y=e.offsetY;
return !(x<0 || x>=w || y<0 || y>=h);
}
Depending on context, you may need to make sure (this==e.target) before calling areXYInside(e).
fyi- I'm looking at using this approach inside a dragLeave handler, in order to confirm that the dragLeave event wasn't triggered by going into a child element. If you don't somehow check that you're still inside the parent element, you might mistakenly take action that's meant only for when you truly leave the parent.
EDIT: this is a nice idea, but does not work consistently enough. Perhaps with some small tweaks.
There are couple of ways to establish HHTP connection and fetch data from a RESTFULL web service. The most recent one is GSON. But before you proceed to GSON you must have some idea of the most traditional way of creating an HTTP Client and perform data communication with a remote server. I have mentioned both the methods to send POST & GET requests using HTTPClient.
/**
* This method is used to process GET requests to the server.
*
* @param url
* @return String
* @throws IOException
*/
public static String connect(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//instream.close();
}
}
catch (ClientProtocolException e) {
Utilities.showDLog("connect","ClientProtocolException:-"+e);
} catch (IOException e) {
Utilities.showDLog("connect","IOException:-"+e);
}
return result;
}
/**
* This method is used to send POST requests to the server.
*
* @param URL
* @param paramenter
* @return result of server response
*/
static public String postHTPPRequest(String URL, String paramenter) {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60*1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60*1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(URL);
httppost.setHeader("Content-Type", "application/json");
try {
if (paramenter != null) {
StringEntity tmp = null;
tmp = new StringEntity(paramenter, "UTF-8");
httppost.setEntity(tmp);
}
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httppost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream input = null;
input = entity.getContent();
String res = convertStreamToString(input);
return res;
}
}
catch (Exception e) {
System.out.print(e.toString());
}
return null;
}
Build Solution - Builds any assemblies which have changed files. If an assembly has no changes, it won't be re-built. Also will not delete any intermediate files.
Used most commonly.
Rebuild Solution - Rebuilds all assemblies regardless of changes but leaves intermediate files.
Used when you notice that Visual Studio didn't incorporate your changes in the latest assembly. Sometimes Visual Studio does make mistakes.
Clean Solution - Delete all intermediate files.
Used when all else fails and you need to clean everything up and start fresh.
what about
$(parentSelect).nextAll().fadeOut(200, function() {
$(this).remove();
}).one(function(){
myfunction();
});
The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.
As per the DOM structure you can use below code:
var x = document.getElementById('mySelect');
var txt = "";
var val = "";
for (var i = 0; i < x.length; i++) {
txt +=x[i].text + ",";
val +=x[i].value + ",";
}
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
That's aLL
You can use the following:
type
keyword, aliasing a function literal)Here is an example of how to use them:
type myCallbackType = (arg1: string, arg2: boolean) => number;
interface myCallbackInterface { (arg1: string, arg2: boolean): number };
class CallbackTest
{
// ...
public myCallback2: myCallbackType;
public myCallback3: myCallbackInterface;
public myCallback1: (arg1: string, arg2: boolean) => number;
// ...
}
you could also do show columns in $table
or see Hive, how do I retrieve all the database's tables columns for access to hive metadata
The column of the first matrix and the row of the second matrix should be equal and the order should be like this only
column of first matrix = row of second matrix
and do not follow the below step
row of first matrix = column of second matrix
it will throw an error
I will never understand why you need up to 50 reputation to leave a comment but I just had to say that @Curt answer is exactly what I was looking and hopefully someone else.
In my example, I have an ActionFilterAttribute that I was using to update the values of a json patch document. I didn't what the T model was for the patch document to I had to serialize & deserialize it to a plain JsonPatchDocument, modify it, then because I had the type, serialize & deserialize it back to the type again.
Type originalType = //someType that gets passed in to my constructor.
var objectAsString = JsonConvert.SerializeObject(myObjectWithAGenericType);
var plainPatchDocument = JsonConvert.DeserializeObject<JsonPatchDocument>(objectAsString);
var plainPatchDocumentAsString= JsonConvert.SerializeObject(plainPatchDocument);
var modifiedObjectWithGenericType = JsonConvert.DeserializeObject(plainPatchDocumentAsString, originalType );
I solved a similar issue by just deleting the .git
folder from my project and reintegrating with version control through IntelliJ.
Note: The .git
folder is hidden. You can view it in the terminal with ls -a
, and then remove it using rm -rf .git
.
In:
for i in range(c/10):
You're creating a float as a result - to fix this use the int division operator:
for i in range(c // 10):
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.
some_key
columngrouped = df.groupby('some_key')
sampled_df_i = random.sample(grouped.indices, N)
df_list = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)
sampled_df = pd.concat(df_list, axis=0, join='outer')
I believe I have found a solution to this, the key is the DATE() function in mysql, which converts a DateTime into just Date:
DB::table('page_views')
->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
->groupBy('date')
->get();
However, this is not really an Laravel Eloquent solution, since this is a raw query.The following is what I came up with in Eloquent-ish syntax. The first where clause uses carbon dates to compare.
$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
->groupBy('date')
->orderBy('date', 'DESC')
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "views"')
));
if (c is UserControl) c.Enabled = enable;
Full disclosure - I'm the author of the previously mentioned talk in TLV DroidCon.
I had a chance to examine this issue across many Android applications, and discuss it with other developers who encountered it - and we all got to the same point: this issue cannot be avoided, only minimized.
I took a closer look at the default implementation of the Android Garbage collector code, to understand better why this exception is thrown and on what could be the possible causes. I even found a possible root cause during experimentation.
The root of the problem is at the point a device "Goes to Sleep" for a while - this means that the OS has decided to lower the battery consumption by stopping most User Land processes for a while, and turning Screen off, reducing CPU cycles, etc. The way this is done - is on a Linux system level where the processes are Paused mid run. This can happen at any time during normal Application execution, but it will stop at a Native system call, as the context switching is done on the kernel level. So - this is where the Dalvik GC joins the story.
The Dalvik GC code (as implemented in the Dalvik project in the AOSP site) is not a complicated piece of code. The basic way it work is covered in my DroidCon slides. What I did not cover is the basic GC loop - at the point where the collector has a list of Objects to finalize (and destroy). The loop logic at the base can be simplified like this:
starting_timestamp
,finalize()
and call native destroy()
if required,end_timestamp
,end_timestamp - starting_timestamp
) and compare against a hard coded timeout value of 10 seconds,java.util.concurrent.TimeoutException
and kill the process.Application runs along doing its thing.
This is not a user facing application, it runs in the background.
During this background operation, objects are created, used and need to be collected to release memory.
Application does not bother with a WakeLock - as this will affect the battery adversely, and seems unnecessary.
This means the Application will invoke the GC from time to time.
Normally the GC runs is completed without a hitch.
Sometimes (very rarely) the system will decide to sleep in the middle of the GC run.
This will happen if you run your application long enough, and monitor the Dalvik memory logs closely.
Now - consider the timestamp logic of the basic GC loop - it is possible for the device to start the run, take a start_stamp
, and go to sleep at the destroy()
native call on a system object.
When it wakes up and resumes the run, the destroy()
will finish, and the next end_stamp
will be the time it took the destroy()
call + the sleep time.
If the sleep time was long (more than 10 seconds), the java.util.concurrent.TimeoutException
will be thrown.
I have seen this in the graphs generated from the analysis python script - for Android System Applications, not just my own monitored apps.
Collect enough logs and you will eventually see it.
The issue cannot be avoided - you will encounter it if your app runs in the background.
You can mitigate by taking a WakeLock, and prevent the device from sleeping, but that is a different story altogether, and a new headache, and maybe another talk in another con.
You can minimize the problem by reducing GC calls - making the scenario less likely (tips are in the slides).
I have not yet had the chance to go over the Dalvik 2 (a.k.a ART) GC code - which boasts a new Generational Compacting feature, or performed any experiments on an Android Lollipop.
Added 7/5/2015:
After reviewing the Crash reports aggregation for this crash type, it looks like these crashes from version 5.0+ of Android OS (Lollipop with ART) only account for 0.5% of this crash type. This means that the ART GC changes has reduced the frequency of these crashes.
Added 6/1/2016:
Looks like the Android project has added a lot of info on how the GC works in Dalvik 2.0 (a.k.a ART).
You can read about it here - Debugging ART Garbage Collection.
It also discusses some tools to get information on the GC behavior for your app.
Sending a SIGQUIT to your app process will essentially cause an ANR, and dump the application state to a log file for analysis.
As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:
You can apply conditional formatting, the visual styling of a
DataFrame
depending on the data within, by using theDataFrame.style
property. This is a property that returns apandas.Styler
object, which has useful methods for formatting and displayingDataFrames
.
For your example, that would be (the usual table will show up in Jupyter):
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
simply execute -
git stash
it will remove all your local changes. and you can also use it later by executing -
git stash apply
This problem can also occur after Ubuntu upgrades that require a reboot.
If the file /var/run/reboot-required
exists, do or schedule a restart.
I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:
b = snip(a,'0')
you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices
It also works with all other 'x', nan or whatever elements.
See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
To summarize: the way a directive accesses its parent ($parent
) scope depends on the type of scope the directive creates:
default (scope: false
) - the directive does not create a new scope, so there is no inheritance here. The directive's scope is the same scope as the parent/container. In the link function, use the first parameter (typically scope
).
scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. Properties that are defined on the parent scope are available to the directive scope
(because of prototypal inheritance). Just beware of writing to a primitive scope property -- that will create a new property on the directive scope (that hides/shadows the parent scope property of the same name).
scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent
, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =
, @
, and &
notation.
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. If the directive also creates an isolate scope, the transcluded and the isolate scopes are siblings. The $parent
property of each scope references the same parent scope.
Angular v1.3 update: If the directive also creates an isolate scope, the transcluded scope is now a child of the isolate scope. The transcluded and isolate scopes are no longer siblings. The $parent
property of the transcluded scope now references the isolate scope.
The above link has examples and pictures of all 4 types.
You cannot access the scope in the directive's compile function (as mentioned here: https://github.com/angular/angular.js/wiki/Dev-Guide:-Understanding-Directives). You can access the directive's scope in the link function.
Watching:
For 1. and 2. above: normally you specify which parent property the directive needs via an attribute, then $watch it:
<div my-dir attr1="prop1"></div>
scope.$watch(attrs.attr1, function() { ... });
If you are watching an object property, you'll need to use $parse:
<div my-dir attr2="obj.prop2"></div>
var model = $parse(attrs.attr2);
scope.$watch(model, function() { ... });
For 3. above (isolate scope), watch the name you give the directive property using the @
or =
notation:
<div my-dir attr3="{{prop3}}" attr4="obj.prop4"></div>
scope: {
localName3: '@attr3',
attr4: '=' // here, using the same name as the attribute
},
link: function(scope, element, attrs) {
scope.$watch('localName3', function() { ... });
scope.$watch('attr4', function() { ... });
The best solution is to acknowledge the asynchronous nature of the download and design for it.
In other words, decide what your application should look like while the data is downloading. Have the page constructor set up that view, and start the download. When the download completes update the page to display the data.
I have a blog post on asynchronous constructors that you may find useful. Also, some MSDN articles; one on asynchronous data-binding (if you're using MVVM) and another on asynchronous best practices (i.e., you should avoid async void
).
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
Use the Unicode Character 'BLACK CIRCLE' (U+25CF) http://www.fileformat.info/info/unicode/char/25CF/index.htm
To copy and paste: ?
Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises
HTML
<select
ng-model="cboPais"
ng-options="item.strPais for item in geoPaises"
></select>
JavaScript
$http.get(strUrl2).success(function (response) {
if (response.length > 0) {
$scope.geoPaises = response; //Data source
nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
if (nIndex >= 0) {
$scope.cboPais = response[nIndex]; //if index of array was found
} else {
$scope.cboPais = response[0]; //select the first element of array
}
$scope.geo_getDepartamentos();
}
}
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
Use ==
.
Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is
(in CPython implementations for instance). But don't rely on this or use it in real programs.
You can get accurate Carousel effect using iCarousel SDK.
You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from https://github.com/nicklockwood/iCarousel and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).
If you haven't added Objective-C code to a Swift project before, follow these steps:
Swift 3 Sample Code:
override func viewDidLoad() {
super.viewDidLoad()
let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
carousel.dataSource = self
carousel.type = .coverFlow
view.addSubview(carousel)
}
func numberOfItems(in carousel: iCarousel) -> Int {
return 10
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let imageView: UIImageView
if view != nil {
imageView = view as! UIImageView
} else {
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
}
imageView.image = UIImage(named: "example")
return imageView
}
by this you can load html file which is in your project Assets(bundle) to webView.
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
may be this is useful to you.
There's a caveat with the general 39 character IPv6 structure. For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this:
IPv6 (39 characters) :
ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD
IPv4-mapped IPv6 (45 characters) :
ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190
Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the .
character), so the maximum is DDD.DDD.DDD.DDD
).
The correct maximum IPv6 string length, therefore, is 45.
This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)
Why is a code solution that works getting voted down? Sure, it's ugly ...
Perhaps because as well as being ugly it isn't educational and doesn't work. Also, I suspect that like me, most people don't have the power to edit at present (and judging by the rank needed - never will).
The use of an array can be good for efficiency, but that's not mentioned in this code. It also takes no account of upper and lower case so it does not work for the example supplied in the question. FFFFFFFE
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
I had the same problem, but I noticed that my datagrid lost the rows's header after the datagrid.visible
property changed.
Try to update the rows's headers with the Datagrid.visiblechanged
event.
If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931
>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)
This is a very common question seen on Stackoverflow.
The important part here is not the command displayed in the error, but what the actual error tells you instead.
a Quick breakdown on why this error is received.
cmd.exe
Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.
How do I fix this:
When Actual Command/executable fails
First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.
If you have any executable which you are attempting to run from cmd.exe
then you need to tell cmd.exe
where this file is located. There are 2 ways of doing this.
specify the full path to the file.
"C:\My_Files\mycommand.exe"
Add the location of the file to your environment Variables.
Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables
In the System Variables
Window, locate path
and select edit
Now simply add your path to the end of the string, seperated by a semicolon ;
as:
;C:\My_Files\
Save the changes and exit. You need to make sure that ANY cmd.exe
windows you had open are then closed and re-opened to allow it to re-import the environment variables.
Now you should be able to run mycommand.exe from any path, within cmd.exe
as the environment is aware of the path to it.
When C:\Program
or Similar fails
This is a very simple error. Each string after a white space is seen as a different command in cmd.exe
terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe
to see it as a single string, and not separate commands.
So to execute C:\Program Files\My-App\Mobile.exe
simply run as:
"C:\Program Files\My-App\Mobile.exe"
I tried the first answer: git stash
with the highest score but the error message still popped up, and then I found this article to commit the changes instead of stash 'Reluctant Commit'
and the error message disappeared finally:
1: git add .
2: git commit -m "this is an additional commit"
3: git checkout the-other-file-name
then it worked. hope this answer helps.:)
Google treat Gmail accounts differently depending on the available user information, probably to curb spammers.
I couldn't use SMTP until I did the phone verification. Made another account to double check and I was able to confirm it.
NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.
You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)
Update
One can install the commands from the Visual Studio menu bar using Tools
->Extensions and Updates
selecting Online
and searching for vscommands
where then one selects VSCommands for Visual Studio 20XX
depending on whether using 2012 or 2013 (or greater going forward) and download and install.
Can this not be done with a user-defined function to replicate whatever your stored procedure is doing?
SELECT udfMyFunction(user_id), someOtherField, etc FROM MyTable WHERE WhateverCondition
where udfMyFunction is a function you make that takes in the user ID and does whatever you need to do with it.
See http://www.sqlteam.com/article/user-defined-functions for a bit more background
I agree that cursors really ought to be avoided where possible. And it usually is possible!
(of course, my answer presupposes that you're only interested in getting the output from the SP and that you're not changing the actual data. I find "alters user data in a certain way" a little ambiguous from the original question, so thought I'd offer this as a possible solution. Utterly depends on what you're doing!)
You can use the @RequestHeader
annotation with HttpHeaders
method parameter to gain access to all request headers:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
I'll add to the excellent answers given above, and talk about boxing and unboxing, and how this applies to Java (although C# has it too). I'll use just Java terminology because I am more au fait with that.
As the answers mentioned, int
is just a number (called the unboxed type), whereas Integer
is an object (which contains the number, hence a boxed type). In Java terms, that means (apart from not being able to call methods on int
), you cannot store int
or other non-object types in collections (List
, Map
, etc.). In order to store them, you must first box them up in its corresponding boxed type.
Java 5 onwards have something called auto-boxing and auto-unboxing which allow the boxing/unboxing to be done behind the scenes. Compare and contrast: Java 5 version:
Deque<Integer> queue;
void add(int n) {
queue.add(n);
}
int remove() {
return queue.remove();
}
Java 1.4 or earlier (no generics either):
Deque queue;
void add(int n) {
queue.add(Integer.valueOf(n));
}
int remove() {
return ((Integer) queue.remove()).intValue();
}
It must be noted that despite the brevity in the Java 5 version, both versions generate identical bytecode. Thus, although auto-boxing and auto-unboxing are very convenient because you write less code, these operations do happens behind the scenes, with the same runtime costs, so you still have to be aware of their existence.
Hope this helps!
For me I had to run Android Studio in Admin mode.
Windows 10 x64
Lets say we're looking for function named foo
:
foo\s*=\s*function
(searches for foo = function
with any number of spaces between those three tokens),Another variant for function definition is function\s*foo\s*\(
for function foo(
with any number of spaces between those three tokens.
To gist or not to gist. That is the $64 question ...
GitHub Gists are Single ( or, multiple ) Simple Markdown Files
with repo-like qualities that can be forked or cloned ( if public ).
Otherwise, not if private.
Kinda like a fancy scratch pad that can be shared.
Similar to this comment scratch pad that I am typing on now, but a bit more elaborate.
Whereas, an official, full GitHub repo is a full blown repository of source code src
, supporting documents ( markdown or html, or both ) docs
or root
, images png
, ico
, svg
, and a config.sys
file for running Yaml variables hosted on a Jekyll server.
Does a simple Gist file support Yaml front matter?
Me thinks not.
From the official GitHub Gist documentation ...
The gist editor is powered by CodeMirror.
However, you can copy a public Gist ( or, a private Gist if the owner has granted you access via a link to the private Gist ) ...
And, you can then embed that public Gist into an "official" repo page.md
using Visual Studio Code, as follows:
"You can embed a gist in any text field that supports Javascript, such as a blog post."
"To get the embed
code, click the clipboard icon next to the Embed URL
button of a gist."
Now, that's a cool feature.
Makes me want to search ( discover ) other peoples' gists, or OPG and incorporate their "public" work into my full-blown working repos.
"You can discover the PUBLIC gists others have created by going to the gist home page and clicking on the link ...
All Gists{:title='Click to Review the Discover Feature at GitHub Gists'}{:target='_blank'}."
Caveat. No support for Liquid tags at GitHub Gist.
I suppose if I do find something beneficial, I can always ping-back, or cite that source if I do use the work in my full-blown working repos.
Where is the implicit license posted for all gists made public by their authors?
Robert
P.S. This is a good comment. I think I will turn this into a gist
and make it publically searchable over at GitHub Gists.
Note. When embedding the <script></script>
html tag within the body of a Markdown (.md) file, you may get a warning "MD033" from your linter.
This should not, however, affect the rendering of the data ( src ) called from within the script
tag.
To change the default warning flag to accommodate the called contents of a script
tag from within Visual Studio Code, add an entry to the Markdownlint Configuration Object within the User Settings
Json file, as follows:
// Begin Markdownlint Configuration Object
"markdownlint.config": {
"MD013": false,
"MD033": {"allowed_elements": ["script"]}
}// End Markdownlint Configuration Object
Note. Solution derived from GitHub Commit by David Anson
In Java 8 we can solve it as:
String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
The method chars() returns an IntStream
as mentioned in doc:
Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.
forEachOrdered
and not forEach
?The behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept. Also check this question for more.
We could also use codePoints()
to print, see this answer for more details.
There's a set_ticks()
function for axis objects.
An API incompatibility I found, with Python 2.7 vs simplejson 3.3.1 is in whether output produces str or unicode objects. e.g.
>>> from json import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{u'a': u'b'}
vs
>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode("""{ "a":"b" }""")
{'a': 'b'}
If the preference is to use simplejson, then this can be addressed by coercing the argument string to unicode, as in:
>>> from simplejson import JSONDecoder
>>> jd = JSONDecoder()
>>> jd.decode(unicode("""{ "a":"b" }""", "utf-8"))
{u'a': u'b'}
The coercion does require knowing the original charset, for example:
>>> jd.decode(unicode("""{ "a": "?????ßß?f?e?" }"""))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 8: ordinal not in range(128)
This is the won't fix issue 40
According to the documentation on here http://angularjs.blogspot.co.uk/2017/03/angular-400-now-available.html you 'should' just be able to run...
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save
I tried it and got a couple of errors due to my zone.js and ngrx/store libraries being older versions.
Updating those to the latest versions npm install zone.js@latest --save
and npm install @ngrx/store@latest -save
, then running the angular install again worked for me.
It could be not supported file encoding. Change it to UTF-8 for example.
I've done this using Sublime
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
You can try using USING
:
The optional
USING
clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. AUSING
clause must be provided if there is no implicit or assignment cast from old to new type.
So this might work (depending on your data):
alter table presales alter column code type numeric(10,0) using code::numeric;
-- Or if you prefer standard casting...
alter table presales alter column code type numeric(10,0) using cast(code as numeric);
This will fail if you have anything in code
that cannot be cast to numeric; if the USING fails, you'll have to clean up the non-numeric data by hand before changing the column type.
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
REST is almost always going to be faster. The main advantage of SOAP is that it provides a mechanism for services to describe themselves to clients, and to advertise their existence.
REST is much more lightweight and can be implemented using almost any tool, leading to lower bandwidth and shorter learning curve. However, the clients have to know what to send and what to expect.
In general, When you're publishing an API to the outside world that is either complex or likely to change, SOAP will be more useful. Other than that, REST is usually the better option.
Follow the below steps:
Select body > form-data and do same as shown in the image.
Now in your Django view.py
def post(self, request, *args, **kwargs): image = request.FILES["image"] data = json.loads(request.data['data']) ... return Response(...)
My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2)
or decimal(10,2)
or whatever.
You can test this by commenting out the insert #temp
and see what numbers the select statement is giving you and see if they are bigger than your column can handle.
In version +2.0 you specify the namespace/room/node you are querying against.
As with broadcasting, the default is all clients from the default namespace ('/'):
const io = require('socket.io')();
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
Gets a list of client IDs connected to specific namespace (across all nodes if applicable).
const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
An example to get all clients in namespace's room:
const io = require('socket.io')();
io.of('/chat').in('general').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
This is from the official documentation: Socket.IO Server-API
what worked for me was and is superfast is
import pandas as pd
import dask.dataframe as dd
import time
t=time.clock()
df_train = dd.read_csv('../data/train.csv', usecols=[col1, col2])
df_train=df_train.compute()
print("load train: " , time.clock()-t)
Another working solution is:
import pandas as pd
from tqdm import tqdm
PATH = '../data/train.csv'
chunksize = 500000
traintypes = {
'col1':'category',
'col2':'str'}
cols = list(traintypes.keys())
df_list = [] # list to hold the batch dataframe
for df_chunk in tqdm(pd.read_csv(PATH, usecols=cols, dtype=traintypes, chunksize=chunksize)):
# Can process each chunk of dataframe here
# clean_data(), feature_engineer(),fit()
# Alternatively, append the chunk to list and merge all
df_list.append(df_chunk)
# Merge all dataframes into one dataframe
X = pd.concat(df_list)
# Delete the dataframe list to release memory
del df_list
del df_chunk
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
@PsychoWoods' answer is good. I would like to offer my own solution. This Javascript function takes an image data URL and a width, scales it to the new width, and returns a new data URL.
// Take an image URL, downscale it to the given width, and return a new image URL.
function downscaleImage(dataUrl, newWidth, imageType, imageArguments) {
"use strict";
var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
// Provide default values
imageType = imageType || "image/jpeg";
imageArguments = imageArguments || 0.7;
// Create a temporary image so that we can compute the height of the downscaled image.
image = new Image();
image.src = dataUrl;
oldWidth = image.width;
oldHeight = image.height;
newHeight = Math.floor(oldHeight / oldWidth * newWidth)
// Create a temporary canvas to draw the downscaled image on.
canvas = document.createElement("canvas");
canvas.width = newWidth;
canvas.height = newHeight;
// Draw the downscaled image on the canvas and return the new data URL.
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, newWidth, newHeight);
newDataUrl = canvas.toDataURL(imageType, imageArguments);
return newDataUrl;
}
This code can be used anywhere you have a data URL and want a data URL for a downscaled image.
Emil's answer is correct, but it's my understanding that inet_ntoa
is deprecated and that instead you should use inet_ntop
. If you are using IPv4, cast your struct sockaddr
to sockaddr_in
. Your code will look something like this:
struct addrinfo *res; // populated elsewhere in your code
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
char ipAddress[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ipv4->sin_addr), ipAddress, INET_ADDRSTRLEN);
printf("The IP address is: %s\n", ipAddress);
Take a look at this great resource for more explanation, including how to do this for IPv6 addresses.
Arrays are normally accessed via numeric indexes, so in your example arr[0] == {name:"k1", value:"abc"}
. If you know that the name
property of each object will be unique you can store them in an object instead of an array, as follows:
var obj = {};
obj["k1"] = "abc";
obj["k2"] = "hi";
obj["k3"] = "oa";
alert(obj["k2"]); // displays "hi"
If you actually want an array of objects like in your post you can loop through the array and return when you find an element with an object having the property you want:
function findElement(arr, propName, propValue) {
for (var i=0; i < arr.length; i++)
if (arr[i][propName] == propValue)
return arr[i];
// will return undefined if not found; you could return a default instead
}
// Using the array from the question
var x = findElement(arr, "name", "k2"); // x is {"name":"k2", "value":"hi"}
alert(x["value"]); // displays "hi"
var y = findElement(arr, "name", "k9"); // y is undefined
alert(y["value"]); // error because y is undefined
alert(findElement(arr, "name", "k2")["value"]); // displays "hi";
alert(findElement(arr, "name", "zzz")["value"]); // gives an error because the function returned undefined which won't have a "value" property
Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.
Other than sharing same unicode number for given character, each one is their own format.
UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...
UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.
Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.
Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.
Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )
So, people use UTF-8 where ever possible.
In the end a stored procedure was the solution for my problem. Here´s what helped:
DELIMITER //
CREATE PROCEDURE test ()
BEGIN
DECLARE myvar DOUBLE;
SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
SELECT myvar;
END
//
DELIMITER ;
call test ();
Use something like this "parseFloat(parseFloat(value).toFixed(2))"
parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78
parseFloat(parseFloat("10").toFixed(2))-->10
parseFloat(parseFloat("9.1").toFixed(2))-->9.1
if you have a char/varchar value formatted as the standard GUID, you can simply store it as BINARY(16) using the simple CAST(MyString AS BINARY16), without all those mind-boggling sequences of CONCAT + SUBSTR.
BINARY(16) fields are compared/sorted/indexed much faster than strings, and also take two times less space in the database
Here is sample code that might help you coping Column A to Column B:
UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
Just modify your WebAPIConfig.cs as bellow
Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional });
Then implement your API as bellow
// GET: api/Controller_Name/Show/1
[ActionName("Show")]
[HttpGet]
public EventPlanner Id(int id){}
You must put your mathematical expressions inside $(( )).
One-liner:
for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;
Multiple lines:
for i in {1..600}; do
wget http://example.com/search/link$(($i % 5))
done
Just fix your replaceAt
:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
mystring.replaceAt(4, 1);
I'd call it removeAt
instead. :)
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
This is a weird approach but it worked for me(MacOs HighSierra 10.13.3). Install CLion. It comes with gdb. Once run the gdb using Terminal. Copy the gdb program to your usr/local/bin/. No problem of signin, sudo etc.
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404
importing by from django.shortcuts import get_object_or_404
.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)
Implemented in a category as below:
UIButton+Border.h:
@interface UIButton (Border)
- (void)addBottomBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addLeftBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addRightBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
- (void)addTopBorderWithColor: (UIColor *) color andWidth:(CGFloat) borderWidth;
@end
UIButton+Border.m:
@implementation UIButton (Border)
- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
}
- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
[self.layer addSublayer:border];
}
- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
}
- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
[self.layer addSublayer:border];
}
@end
this.myService.getConfig().subscribe(
(res) => console.log(res),
(err) => console.log(err),
() => console.log('done!')
);
Add HttpClientModule
in your app.module.ts
and try, it will work so sure.
for example
import { HttpModule } from '@angular/http
TL;DR
headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
headroom_by_DOM = $('#id')[0].getBoundingClientRect().top; // if no iframe
.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.
I need to do 2 things to connect with instance name
1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)
Restart sql and done
You can achieve this $(identifier).data('id')
using jquery,
<script type="text/javascript">
function goDoSomething(identifier){
alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
javascript : You can use getAttribute("attributename")
if want to use javascript tag,
<script type="text/javascript">
function goDoSomething(d){
alert(d.getAttribute("data-id"));
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this);">
Click to do something
</a>
Or:
<script type="text/javascript">
function goDoSomething(data_id, data_option){
alert("data-id:"+data_id+", data-option:"+data_option);
}
</script>
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
Click to do something
</a>
It's worth to mention that using concerns is considered bad idea by many.
Some reasons:
include
method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.Concerns are easy way to shoot yourself in the leg, be careful with them.
Most answers are fairly old, so it might have not been possible back then, but there actually is a solution that satisfies all the possible use-cases.
So right know the answers are:
@Value
you have to have the value in a configuration file somewhere)The solution to solve those issues is to create the object manually using the ApplicationContext
:
@Component
public class MyConstructorClass
{
String var;
public MyConstructorClass() {}
public MyConstructorClass(String constrArg) {
this.var = var;
}
}
@Service
public class MyBeanService implements ApplicationContextAware
{
private static ApplicationContext applicationContext;
MyConstructorClass myConstructorClass;
public MyBeanService()
{
// Creating the object manually
MyConstructorClass myObject = new MyConstructorClass("hello world");
// Initializing the object as a Spring component
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(myObject);
factory.initializeBean(myObject, myObject.getClass().getSimpleName());
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
}
This is a cool solution because:
@Autowired
obviously, but also @Async
for example),The only thing to keep in mind is that you have to have a constructor that takes no arguments (and that can be empty) in the class you want to instantiate (or an @Autowired
constructor if you need it).
I got this error until I realized that I hadn't intialized a Git repository in that folder, on a mounted vagrant machine.
So I typed git init
and then git worked.
There is a pretty significant difference between the two. The empty string ""
is "the string that has no characters in it." It's an actual string that has a well-defined length. All of the standard string operations are well-defined on the empty string - you can convert it to lower case, look up the index of some character in it, etc. The null string null
is "no string at all." It doesn't have a length because it's not a string at all. Trying to apply any standard string operation to the null string will cause a NullPointerException
at runtime.
I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?
Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...
Add permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Import:
import android.telephony.TelephonyManager;
Use the below code:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
imei = tm.getDeviceId();
// get SimSerialNumber
simSerialNumber = tm.getSimSerialNumber();
The easy way to handle this (and best HTML solution to boot) is to set up classes that have the styles you want to use. Then it's a simple matter of using addClass() and removeClass(), or even toggleClass().
$('#voltaic_holder').addClass('shiny').removeClass('dull');
or even
$('#voltaic_holder').toggleClass('shiny dull');
Open vscode.
Press ctrl,.
The setting is "editor.fontFamily"
.
On Linux to get a list of fonts (and their names which you have to use) run this in another shell:
fc-list | awk '{$1=""}1' | cut -d: -f1 | sort| uniq
You can specify a list of fonts, to have fallback values in case a font is missing.
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
You are creating an array of three elements and assigning all three to the same thing, which is itself an array of three elements (three Doubles).
When you do the modifications you are modifying the floats in the internal array.
I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)
$Date3 = date('y-m-d');
$Date2 = date('y-m-d', strtotime("-7 days"));
SELECT * FROM disaster WHERE date BETWEEN '".$Date2."' AND '".$Date3."'
You have an array, convert it to an object, something like:
data: [{"id": 3636, "is_default": true, "name": "Unit", "quantity": 1, "stock": "100000.00", "unit_cost": "0"}, {"id": 4592, "is_default": false, "name": "Bundle", "quantity": 5, "stock": "100000.00", "unit_cost": "0"}]
The solution from @user1437663 is great.
Who really understands the solution is being prepared to understand complex regular expressions.
A small improvement to make it more readable:
function numberWithCommas(x) {
var parts = x.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?=$))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
The pattern starts with \B to avoid use comma at the beginning of a word. Interestingly, the pattern is returned empty because \B does not advance the "cursor" (the same applies to $).
O \B is followed by a less known resources but is a powerful feature from Perl's regular expressions.
Pattern1 (? = (Pattern2) ).
The magic is that what is in parentheses (Pattern2) is a pattern that follows the previous pattern (Pattern1) but without advancing the cursor and also is not part of the pattern returned. It is a kind of future pattern. This is similar when someone looks forward but really doesn't walk!
In this case pattern2 is
\d{3})+(?=$)
It means 3 digits (one or more times) followed by the end of the string ($)
Finally, Replace method changes all occurrences of the pattern found (empty string) for comma. This only happens in cases where the remaining piece is a multiple of 3 digits (such cases where future cursor reach the end of the origin).
I wrote this purely SQLPlus script to dump tables to CSV in 1994.
As noted in the script comments, someone at Oracle put my script in an Oracle Support note, but without attribution.
https://github.com/jkstill/oracle-script-lib/blob/master/sql/dump.sql
The script also also builds a control file and a parameter file for SQL*LOADER
As for the first part:
>>> N = 5
>>> count_list = [i+1 for i in xrange(N)]
>>> count_list
[1, 2, 3, 4, 5]
>>>
As for the second, read 9.6. random — Generate pseudo-random numbers.
>>> from random import choice
>>> a = choice(count_list)
>>> a
1
>>> count_list.remove(a)
>>> count_list
[2, 3, 4, 5]
That's the general idea.
By the way, you may also be interested in reading Random selection of elements in a list, with no repeats (Python recipe).
There are a few implementations of fast random selection.
The existence of that piece of metadata is entirely dependent on the application that wrote the file. It's very common to load up JPG files with metadata (EXIF tags) about the file, such as a timestamp or camera information or geolocation. ID3 tags in MP3 files are also very common. But it's a lot less common to see this kind of metadata in video files.
If you just need a tool to read this data from files manually, GSpot might do the trick: http://www.videohelp.com/tools/Gspot
If you want to read this in code then I imagine each container format is going to have its own standards and each one will take a bit of research and implementation to support.
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
Building on @Pvl's answer, you can include type safety on your returned value as well if you use overrides:
function dig<
T,
K1 extends keyof T
>(obj: T, key1: K1): T[K1];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1]
>(obj: T, key1: K1, key2: K2): T[K1][K2];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2]
>(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3]
>(obj: T, key1: K1, key2: K2, key3: K3, key4: K4): T[K1][K2][K3][K4];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3],
K5 extends keyof T[K1][K2][K3][K4]
>(obj: T, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): T[K1][K2][K3][K4][K5];
function dig<
T,
K1 extends keyof T,
K2 extends keyof T[K1],
K3 extends keyof T[K1][K2],
K4 extends keyof T[K1][K2][K3],
K5 extends keyof T[K1][K2][K3][K4]
>(obj: T, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5):
T[K1] |
T[K1][K2] |
T[K1][K2][K3] |
T[K1][K2][K3][K4] |
T[K1][K2][K3][K4][K5] {
let value: any = obj && obj[key1];
if (key2) {
value = value && value[key2];
}
if (key3) {
value = value && value[key3];
}
if (key4) {
value = value && value[key4];
}
if (key5) {
value = value && value[key5];
}
return value;
}
Example on playground.
There are basically two ways
store the previous value of window.onload
so your code can call a previous handler if present before or after your code executes
using the addEventListener
approach (that of course Microsoft doesn't like and requires you to use another different name).
The second method will give you a bit more safety if another script wants to use window.onload
and does it without thinking to cooperation but the main assumption for Javascript is that all the scripts will cooperate like you are trying to do.
Note that a bad script that is not designed to work with other unknown scripts will be always able to break a page for example by messing with prototypes, by contaminating the global namespace or by damaging the dom.
or use the blazing fast GNU Parallel:
grep -rl oldtext . | parallel sed -i 's/oldtext/newtext/g' {}
You can do something like this:
div {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
a:hover + div {_x000D_
display: block;_x000D_
}
_x000D_
<a>Hover over me!</a>_x000D_
<div>Stuff shown on hover</div>
_x000D_
This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.
HTML5 allows anchor elements to wrap almost anything, so in that case the div
element can be made a child of the anchor. Otherwise the principle is the same - use the :hover
pseudo-class to change the display
property of another element.
You can try this:
Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
allMatches.add(m.group());
}
The result (allMatches) will be:
["123", "abc", "345", "def"]
A more powerful and flexible example can be found here: C# File Upload with form fields, cookies and headers
Its all about Method Overloading.
There are individual methods for each data type in println() method
If you pass object :
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
If you pass Primitive type:
corresponding primitive type method calls
if you pass String :
corresponding println(String x) method calls
git reset filename.txt
Will remove a file named filename.txt from the current index, the "about to be committed" area, without changing anything else.
Been looking into this for a while and not got any satisfactory answers, however...
1) ANSI escape sequences do work in a terminal on Linux
2) if you can tolerate a limited set of colo(u)rs try this:
print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")
In idle "hello" and "goodbye" are in blue and "error" is in red.
Not fantastic, but good enough for now, and easy!
I found a reference to this in condas issues. The following should now work.
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- git+https://github.com/pythonforfacebook/facebook-sdk.git
All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:
Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.
The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory
Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences
CMake 3.13 on Ubuntu 16.04
This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:
$ cat CMakeLists.txt
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE )
message("MY_VARIABLE evaluates to True")
endif()
$ mkdir build && cd build
$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
Even better are f-strings in python 3!
f = open(f'{name}.csv', 'wb')
I think df.replace()
does the job, since pandas 0.13:
df = pd.DataFrame([
[-0.532681, 'foo', 0],
[1.490752, 'bar', 1],
[-1.387326, 'foo', 2],
[0.814772, 'baz', ' '],
[-0.222552, ' ', 4],
[-1.176781, 'qux', ' '],
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))
# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))
Produces:
A B C
2000-01-01 -0.532681 foo 0
2000-01-02 1.490752 bar 1
2000-01-03 -1.387326 foo 2
2000-01-04 0.814772 baz NaN
2000-01-05 -0.222552 NaN 4
2000-01-06 -1.176781 qux NaN
As Temak pointed it out, use df.replace(r'^\s+$', np.nan, regex=True)
in case your valid data contains white spaces.
It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.
Here a small change that you can do:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine());
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
because u have to have jquery set-up to enable the toggling functionality of the toggler button. So, all u have to do is to add bootstrap.bundle.js before bootstrap.css:
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
^\d{0,2}\.?\d{1,2}$
Maybe the uuid module?
I think this is the easiest way
input {_x000D_
position: relative;_x000D_
top: 1px;_x000D_
}
_x000D_
<form>_x000D_
<div>_x000D_
<label><input type="checkbox" /> Label text</label>_x000D_
</div>_x000D_
<form>
_x000D_
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
firstly shouldn't
data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
be
data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
and secondly you can use
url: this.action + '?NonFormValue=' + NonFormValue,
or if the action already contains any parameters
url: this.action + '&NonFormValue=' + NonFormValue,
The bottom line is not all browsers will actually look for your favicon.ico file. Some browsers allow users to choose whether or not it should automatically look. Therefore, in order to ensure that it will always appear and get looked at, you do have to define it.
Basically, when your FROM clause lists tables like so:
SELECT * FROM
tableA, tableB, tableC
the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id
which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id
and you should then get only those rows you are really interested in.
DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like
tableA.id = tableB.a_id
AND tableB.id = tableC.b_id
which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.
Try this in your CSS:
input {
text-align: right;
}
To align the text in the center:
input {
text-align: center;
}
But, it should be left-aligned, as that is the default - and appears to be the most user friendly.
First create table without auto_increment,
CREATE TABLE `members`(
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL
PRIMARY KEY (memberid)
) ENGINE = MYISAM;
after set id as index,
ALTER TABLE `members` ADD INDEX(`id`);
after set id as auto_increment,
ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
Or
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL,
PRIMARY KEY (`memberid`),
KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
As pointed out, "&" in python performs a bitwise and operation, just as it does in C#. and
is the appropriate equivalent to the &&
operator.
Since we're dealing with booleans (i == 5
is True
and ii == 10
is also True
), you may wonder why this didn't either work anyway (True being treated as an integer quantity should still mean True & True is a True value), or throw an exception (eg. by forbidding bitwise operations on boolean types)
The reason is operator precedence. The "and
" operator binds more loosely than ==
, so the expression: "i==5 and ii==10
" is equivalent to: "(i==5) and (ii==10)
"
However, bitwise &
has a higher precedence than "==
" (since you wouldn't want expressions like "a & 0xff == ch
" to mean "a & (0xff == ch)
"), so the expression would actually be interpreted as:
if i == (5 & ii) == 10:
Which is using python's operator chaining to mean: does the valuee of ii anded with 5 equal both i and 10. Obviously this will never be true.
You would actually get (seemingly) the right answer if you had included brackets to force the precedence, so:
if (i==5) & (ii=10)
would cause the statement to be printed. It's the wrong thing to do, however - "&
" has many different semantics to "and
" - (precedence, short-cirtuiting, behaviour with integer arguments etc), so it's fortunate that you caught this here rather than being fooled till it produced less obvious bugs.
Since it's a long time and people keep suggesting to use Scanner#nextLine()
, there's another chance that Scanner
can take spaces included in input.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter()
to change the delimiter of Scanner
to another pattern such as a line feed
or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
If yours is a gradle project replace:
xmlns:android="http://schemas.android.com/apk/res/android"
with:
xmlns:app="http://schemas.android.com/apk/res-auto"
As a fallback solution, you could wrap your classes in a parent element like this:
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<div>
<!-- first-child / first-of-type starts from here -->
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
</div>
Here is a slightly modified version that uses an Object to store the hashes can handle numbers as well as strings in arrays.
function arrDiff(a, b) {
const hash = {};
a.forEach(n => { hash[n] = n; });
b.forEach(n => {
if (hash[n]) {
delete hash[n];
} else {
hash[n] = n;
}
});
return Object.values(hash);
}
Update Oct. 2016: issue 871 did mention "Signing stopped working in Git 2.9.3"
Git for Windows 2.10.1 released two days ago (Oct. 4th, 2016) has fixed Interactive GPG signing of commits and tag.
the recent gpg-sign change in git (which introduces no problem on Linux) exposes a problem in the way in which, on Windows, non-MSYS2-git interacts with MSYS2-gpg.
Original answer:
Reading "7.4 Git Tools - Signing Your Work", I assume you have your "user.signingkey
" configuration set.
The last big refactoring (before Git 2.10) around gpg was in commit 2f47eae2a, here that error message was moved to gpg-interface.c
A log on that file reveals the recent change in commit af2b21e (Git 2.10)
gpg2 already uses the long format by default, but most distributions seem to still have "gpg" be the older 1.x version due to compatibility reasons. And older versions of gpg only show the 32-bit short ID, which is quite insecure.
This doesn't actually matter for the verification itself: if the verification passes, the pgp signature is good.
But if you don't actually have the key yet, and want to fetch it, or you want to check exactly which key was used for verification and want to check it, we should specify the key with more precision.
So check how you specified your user.signingkey
configuration, and the version of gpg you are using (gpg1 or gpg2), to see if those have any effect on the error message.
There is also commit 0581b54 which changes the condition for the gpg failed to sign the data
error message (in complement to commit 0d2b664):
We don't read from stderr at all currently. However, we will want to in a future patch, so this also prepares us there (and in that case gpg does write before reading all of the input, though again, it is unlikely that a key uid will fill up a pipe buffer).
Commit 4322353 shows gpg now uses a temporary file, so there could be right issues around that.
Let's convert to using a tempfile object, which handles the hard cases for us, and add the missing cleanup call.
Taking DWins example.
What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".
E.g.
clab = 1.5
cmain = 2
caxis = 1.2
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=clab,
col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis)
You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:
which you then call with setwd("") source("plotcolours.r")
in a file say called plotcolours.r you then store all the e.g. colour or size variables
clab = 1.5
cmain = 2
caxis = 1.2
for colours could use
darkred<-rgb(113,28,47,maxColorValue=255)
as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.
plot(1,1,col=darkred)
after a lot of tries, I've read in other topics which someone said "delete all your apps and create it again". I did that but, as you can imagine, a new App will create a new Application ID on Facebook's page.
So, even after all the "set public things" it didn't work because the application ID was wrong in my code due to the creation of a new App on Facebook developer page.
So, as AndrewSmiley said above, you should remeber to update that in your app @strings
The other answers are great and contain more detail if you want/need them.
In addition to those, I would like to add a TL;DR:
@RunWith(MockitoJUnitRunner.class)
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Before public void initMocks() {
MockitoAnnotations.initMocks(this);
}
X x = mock(X.class)
(1) and (2) and (3) are mutually exclusive.
(4) can be used in combination with the others.
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);
subinacl.exe command-line tool is probably the only viable and very easy to use from anything in this post. You cant use a GPO with non-system services and the other option is just way way way too complicated.
Here is my solution. The code should be easy enough to follow but here is the idea:
The code:
function focusFirst(parent) {
$(parent).find('input, textarea, select')
.not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
.filter(':enabled:visible:first')
.focus();
}
Then simply call focusFirst with your parent element or selector.
Selector:
focusFirst('form#aspnetForm');
Element:
var el = $('form#aspnetForm');
focusFirst(el);
Both the options can be correct depending on your situation.
A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.
It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
To calculate tax, you could use round
(after all, that's what the restaurant does):
def calc_tax(mealPrice):
tax = round(mealPrice*.06,2)
return tax
To display the data, you could use a multi-line string, and the string format method:
def display_data(mealPrice, tax):
total=round(mealPrice+tax,2)
print('''\
Your Meal Price is {m:=5.2f}
Tax {x:=5.2f}
Total {t:=5.2f}
'''.format(m=mealPrice,x=tax,t=total))
Note the format method was introduced in Python 2.6, for earlier versions you'll need to use old-style string interpolation %
:
print('''\
Your Meal Price is %5.2f
Tax %5.2f
Total %5.2f
'''%(mealPrice,tax,total))
Then
mealPrice=input_meal()
tax=calc_tax(mealPrice)
display_data(mealPrice,tax)
yields:
# Enter the meal subtotal: $43.45
# Your Meal Price is 43.45
# Tax 2.61
# Total 46.06
I'd recommend using the Buffer
class:
var someEncodedString = Buffer.from('someString', 'utf-8');
This avoids any unnecessary dependencies that other answers require, since Buffer
is included with node.js
, and is already defined in the global scope.
When the rails server does not start it means that it is already running then you can start by using new port eg.
rails s -p 3001
or it starts and stops in that case you want to delete temp folder in rails directory structure it starts the rails server.
I'm not familiar with DB2, but have you tried COALESCE?
ie:
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
Now there is a very useful npm package for this: buffer
https://github.com/feross/buffer
It tries to provide an API that is 100% identical to node's Buffer API and allow:
and few more.
It seems that the only way to do this is to prevent Location Spoofing preventing MockLocations. The down side is there are some users who use Bluetooth GPS devices to get a better signal, they won't be able to use the app as they are required to use the mock locations.
To do this, I did the following :
// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
return false;
else return true;
I decided to share my solution, because although many answers provided here were helpful, I still had this problem. In my case, I am using JSF 2.3, jdk10, jee8, cdi 2.0 for my new project and I did run my app on wildfly 12, starting server with parameter standalone.sh -Dee8.preview.mode=true as recommended on wildfly website. The problem with "bean resolved to null” disappeared after downloading wildfly 13. Uploading exactly the same war to wildfly 13 made it all work.
You can try with textContent.
var productId = val[key].textContent;
I believe most of people landed here are using ZSH thorugh iterm or whatever, and that brings you to this answer.
You have to add/modify your commands in ~/.zshrc
instead.
This is my simple solution:
String secToTime(int sec) {
int seconds = sec % 60;
int minutes = sec / 60;
if (minutes >= 60) {
int hours = minutes / 60;
minutes %= 60;
if( hours >= 24) {
int days = hours / 24;
return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
}
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
return String.format("00:%02d:%02d", minutes, seconds);
}
Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745
Release notes iOS 3.2 (External Display Support) and iOS 4.0 (Inherited Improvements) mentions that it should be possible to connect external displays to iOS 4.0 devices.
But you still have to jailbreak if you would mirror your iPhone screen...
Related SO Question with updates
In javascript, there is no way, to make the code wait. I've had this problem and the way I did it was do a synchronous SJAX call to the server, and the server actually executes sleep or does some activity before returning and the whole time, the js waits.
Eg of Sync AJAX: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX
Here is a solution with sqldf
library("sqldf")
myvec <- read.table(header=TRUE, text=
" name order_no
1 Amy 12
2 Jack 14
3 Jack 16
4 Dave 11
5 Amy 12
6 Jack 16
7 Tom 19
8 Larry 22
9 Tom 19
10 Dave 11
11 Jack 17
12 Tom 20
13 Amy 23
14 Jack 16")
sqldf("SELECT name,COUNT(distinct(order_no)) as number_of_distinct_orders FROM myvec GROUP BY name")
# > sqldf("SELECT name,COUNT(distinct(order_no)) as number_of_distinct_orders FROM myvec GROUP BY name")
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
Also the visual studio add-in ghost doc will attempt to create and fill-in the header comments from your function name.
typeid provides the type of the data at runtime, when asked for. Typedef is a compile time construct that defines a new type as stated after that. There is no typeof in C++ Output appears as (shown as inscribed comments):
std::cout << typeid(t).name() << std::endl; // i
std::cout << typeid(person).name() << std::endl; // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl; // P6Person
std::cout << typeid(*ptr).name() << std::endl; //8Employee
Of course, I was misunderstanding the problem. As AWS themselves put it:
For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling
context.done()
in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.
I was calling context.done
way before any callbacks for the request fired, causing the termination of my function ahead of time.
The working code is this:
var http = require('http');
exports.handler = function(event, context) {
console.log('start request to ' + event.url)
http.get(event.url, function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
console.log('end request to ' + event.url);
}
Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.
function(event, context, callback)
Although you will still find the succeed
, done
and fail
on the context parameter, AWS suggest to use the callback
function instead or null
is returned by default.
callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok
Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.
A previous reply to this question has given a great explanation of what the various types are.
You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.
http://www.softwareverify.com/cpp/memory/index.html
Disclaimer: I designed Memory Validator.