I had the same problem running windows 7-64 with VB6. I tried the unregister and re-register solutions above but it did not solve the problem. Then I noticed that in my VB6 Components I had references to both the Microsoft Windows Common Controls -2 6.0(SP6) and Microsoft Windows Common Controls -3 6.0(SP5). I removed the SP5 reference and all now works OK. It seems that -2 6.0 SP6 supersedes -3 6.0 (SP5) and when both are present there are two references to the same control. Hope this helps. Steve
For Windows I just had to add an env variable pointing to the SDK folder. Done! (The accepted answer didn´t work for me)
Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)
I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.
Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.
Use Random.nextInt(int).
In your case it would look something like this:
a[i][j] = r.nextInt(101);
.class {_x000D_
display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
.class {_x000D_
display: block; /* just an example display property */_x000D_
}_x000D_
}
_x000D_
I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.
Here is the method which works for me (when installing version 1.7.8):
yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
tar -xzvf ./git-1.7.8.tar.gz
cd ./git-1.7.8
./configure
make
make install
You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list
If you extend the Application
class and maintain a static 'global' Context object, as follows, then you can use that instead of the activity to load a String resource.
public class MyApplication extends Application {
public static Context GLOBAL_APP_CONTEXT;
@Override
public void onCreate() {
super.onCreate();
GLOBAL_APP_CONTEXT = this;
}
}
If you use this, you can get away with Toast
and resource loading without worrying about lifecycles.
To check on elasticsearch cluster health you need to use
curl localhost:9200/_cat/health
More on the cat APIs here.
I usually use elasticsearch-head plugin to visualize that.
You can find it's github project here.
It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head
and then you can open localhost:9200/_plugin/head/
in your web brower.
You should have something that looks like this :
In your php.ini file check for display_errors. If it is off, then make it on as below:
display_errors = On
It should display warnings/notices/errors .
Please read this
http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
No need to complicate stuff - this should work:
#/bin/bash
echo "
verbose
open ftp.mydomain.net
user myusername mypassword
ascii
put textfile1
put textfile2
bin
put binaryfile1
put binaryfile2
bye
" | ftp -n > ftp_$$.log
or you can use mput if you have many files ...
This has proved to be elusive for me (WebSite Project) until I figured out the following procedure, which combines the solution provided by @Jimmy, with the added step of checking out the solution from Source Control
Steps: (if using VS2013+ with website project and SourceControl)
VWDPort = ......
and change to desired port: (example: "60000" - depends on your IISExpress Settings)As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
From here
Thus, only alphanumerics, the special characters
$-_.+!*'(),
and reserved characters used for their reserved purposes may be used unencoded within a URL.
It's one end of a communication channel, so often this would be represented as the URL of a server or service.
you can create batch file and insert into it the bellow line:
cmd /k start chrome "http://yourWebSite.com
after that you do just double click on this batch file.
In iPhone iOS6 and from Android ICS onwards, HTML5 has the following tag which allows you to take pictures from your device:
<input type="file" accept="image/*" capture="camera">
Capture
can take values like camera, camcorder and audio.
I think this tag will definitely not work in iOS5, not sure about it.
I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:
$int = (($int > 0) ? -$int : $int);
EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:
/* I am not proposing you actually use functions called
"makeNegative" and "makePositive"; I am just presenting
the most direct solution in the form of two clearly named
functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }
I found an easier way to get UTC in Swift4. Put this code in playground
let date = Date()
*//"Mar 15, 2018 at 4:01 PM"*
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let newDate = dateFormatter.string(from: date)
*//"2018-03-15 21:05:04 +0000"*
If you use Anaconda 2.7 64 bit, try
conda upgrade scikit-learn
and restart the python shell, that works for me.
Second edit when I faced the same problem and solved it:
conda upgrade scikit-learn
also works for me
void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
});
});
And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.
During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.
var updateStatementString : String! = ""
for item in cardids {
let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
updateStatementString.append(newstring)
}
print(updateStatementString)
let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)
return Int64(results)
<div style="display: inline">Is this what you meant?</div>
This has to do with the fact that mutating a prop locally is considered an anti-pattern in Vue 2
What you should do now, in case you want to mutate a prop locally, is to declare a field in your data
that uses the props
value as its initial value and then mutate the copy:
Vue.component('task', {
template: '#task-template',
props: ['list'],
data: function () {
return {
mutableList: JSON.parse(this.list);
}
}
});
You can read more about this on Vue.js official guide
Note 1: Please note that you should not use the same name for your prop
and data
, i.e.:
data: function () { return { list: JSON.parse(this.list) } // WRONG!!
Note 2: Since I feel there is some confusion regarding props
and reactivity, I suggest you to have a look on this thread
One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.
For example, have a pool of files called:
Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile
".
If it's on a separate filesystem, you will have to use a symbolic link.
The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.
The link operation is about as fast as you can get.
Add an auto incrementing Primary Key to each record, for example, UserStatusId.
Then your query could look like this:
select * from UserStatus where UserStatusId in
(
select max(UserStatusId) from UserStatus group by User
)
Date User Status Notes
This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.
Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]
However, the below links is perfect, it works for me.
http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0
Regards, Bilal
Is there any command in Linux through which i can know if the process is in hang state.
There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):
ps
to find list of PIDs of the watched processes (along with exec time, etc)gdb
attaching to the process using its PID, dumping stack trace from it using thread apply all where
, detaching from the processBut that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.
Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.
The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".
Use whatever service manager your system offers - for example under Ubuntu use upstart. This will handle all the details for you such as start on boot, restart on crash, etc.
POSIX sh doesn't understand ==
for string equality, as that is a bash-ism. Use =
instead.
The other people saying that brackets aren't supported by sh are wrong, btw.
There are many ways of doing.
1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:
def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
what match {
case 'row => replaceRow(where, newValue)
case 'col | 'column => replaceCol(where, newValue)
case _ => throw new IllegalArgumentException
}
// At REPL:
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /
scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /
scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /
2) Using class Enumeration
:
object Dimension extends Enumeration {
type Dimension = Value
val Row, Column = Value
}
or, if you need to serialize or display it:
object Dimension extends Enumeration("Row", "Column") {
type Dimension = Value
val Row, Column = Value
}
This can be used like this:
def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
what match {
case Row => replaceRow(where, newValue)
case Column => replaceCol(where, newValue)
}
// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
a(Row, 2) = a.row(1)
^
scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /
scala> import Dimension._
import Dimension._
scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /
Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.
3) Case objects:
sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension
Now, if I leave out a case on a match
, the compiler will warn me:
MatrixInt.scala:70: warning: match is not exhaustive!
missing combination Column
what match {
^
one warning found
It's used pretty much the same way, and doesn't even need an import
:
scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /
scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /
You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.
This answer is essentially a selected parts from this article in my blog.
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
DO NOT USE THIS ANSWER. The URL is pointing at jQuery 1.11 (and always will).
Credits to Basic for above snippet
http://code.jquery.com/jquery-latest.min.js is the minified version, always up-to-date.
You can use parseFloat()
and toFixed()
if you want to bypass this issue for a small operation:
a = 0.1;
b = 0.2;
a + b = 0.30000000000000004;
c = parseFloat((a+b).toFixed(2));
c = 0.3;
a = 0.3;
b = 0.2;
a - b = 0.09999999999999998;
c = parseFloat((a-b).toFixed(2));
c = 0.1;
For [1], you can't: these operators are made to return a value, not perform operations.
The expression
a ? b : c
evaluates to b
if a
is true and evaluates to c
if a
is false.
The expression
b ?? c
evaluates to b
if b
is not null and evaluates to c
if b
is null.
If you write
return a ? b : c;
or
return b ?? c;
they will always return something.
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
It handle all possible stuff and even reference itself in structure of object. You can see the example at the end of code.
var deepCompare = (function() {
function internalDeepCompare (obj1, obj2, objects) {
var i, objPair;
if (obj1 === obj2) {
return true;
}
i = objects.length;
while (i--) {
objPair = objects[i];
if ( (objPair.obj1 === obj1 && objPair.obj2 === obj2) ||
(objPair.obj1 === obj2 && objPair.obj2 === obj1) ) {
return true;
}
}
objects.push({obj1: obj1, obj2: obj2});
if (obj1 instanceof Array) {
if (!(obj2 instanceof Array)) {
return false;
}
i = obj1.length;
if (i !== obj2.length) {
return false;
}
while (i--) {
if (!internalDeepCompare(obj1[i], obj2[i], objects)) {
return false;
}
}
}
else {
switch (typeof obj1) {
case "object":
// deal with null
if (!(obj2 && obj1.constructor === obj2.constructor)) {
return false;
}
if (obj1 instanceof RegExp) {
if (!(obj2 instanceof RegExp && obj1.source === obj2.source)) {
return false;
}
}
else if (obj1 instanceof Date) {
if (!(obj2 instanceof Date && obj1.getTime() === obj2.getTime())) {
return false;
}
}
else {
for (i in obj1) {
if (obj1.hasOwnProperty(i)) {
if (!(obj2.hasOwnProperty(i) && internalDeepCompare(obj1[i], obj2[i], objects))) {
return false;
}
}
}
}
break;
case "function":
if (!(typeof obj2 === "function" && obj1+"" === obj2+"")) {
return false;
}
break;
default: //deal with NaN
if (obj1 !== obj2 && obj1 === obj1 && obj2 === obj2) {
return false;
}
}
}
return true;
}
return function (obj1, obj2) {
return internalDeepCompare(obj1, obj2, []);
};
}());
/*
var a = [a, undefined, new Date(10), /.+/, {a:2}, function(){}, Infinity, -Infinity, NaN, 0, -0, 1, [4,5], "1", "-1", "a", null],
b = [b, undefined, new Date(10), /.+/, {a:2}, function(){}, Infinity, -Infinity, NaN, 0, -0, 1, [4,5], "1", "-1", "a", null];
deepCompare(a, b);
*/
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.
But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.
Here is working code:
=QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")
In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.
The below works for Normal mode: I agree with Dan Olson's answer that you should probably be in normal mode for most deletions. More details below.
If the cursor is inside the word:
diw
to delete in the word (doesn't include spaces)
daw
to delete around the word (includes spaces before the next word).
If the cursor is at the start of the word, just press dw
.
This can be multiplied by adding the usual numbers for movement, e.g. 2w to move forward 2 words, so d2w deletes two words.
Insert Mode ^w
The idea of using hjkl for movement in Vim is that it's more productive to keep your hands on the home row. At the end of a word ^w works great to quickly delete the word. If you've gone into insert mode, entered some text and used the arrow keys to end up in the middle of the word you've gone against the home-row philosophy.
If you're in normal mode and want to change the word you can simply use the c
(change) rather than d
(delete) if you'd like to completely change the word, and re-enter insert mode without having to press i
to get back to typing.
HI you can try this...
Try..
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation
Or
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer
Hope it works for you.
SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).
A SQL 2012 example on this data
/* Prepare */
select * into #tmp
from
(
select 2 as rowint, 23 as Value
union select 3, 45
union select 17, 10
union select 9, 0
) x
/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value
from #tmp
LEAD(value) will return the value of the next row in respect to the given order in "over" clause.
Alternative solution to the updated question using Java 8:
Bar[] result = foos.stream()
.map(x -> new Bar(x))
.toArray(size -> new Bar[size]);
In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.
Thanks & Regards Vengat Maran
As far as I know, Angular doesn't provide such a function. You may want to use underscore's find()
function for this (it's basically a forEach which breaks out of the loop once the function returns true).
Just In Time Compiler (JIT) :
It compiles the java bytecodes into machine instructions of that specific CPU.
For example, if we have a loop statement in our java code :
while(i<10){
// ...
a=a+i;
// ...
}
The above loop code runs for 10 times if the value of i is 0.
It is not necessary to compile the bytecode for 10 times again and again as the same instruction is going to execute for 10 times. In that case, it is necessary to compile that code only once and the value can be changed for the required number of times. So, Just In Time (JIT) Compiler keeps track of such statements and methods (as said above before) and compiles such pieces of byte code into machine code for better performance.
Another similar example , is that a search for a pattern using "Regular Expression" in a list of strings/sentences.
JIT Compiler doesn't compile all the code to machine code. It compiles code that have a similar pattern at run time.
See this Oracle documentation on Understand JIT to read more.
Simple Javascript code to make mobile browser display either in portrait or landscape..
(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Mobile Device</title>
<script type="text/javascript">
// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
if(window.orientation==0)
{
document.getElementById('portrait').style.display = '';
document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
document.getElementById('portrait').style.display = 'none';
document.getElementById('landscape').style.display = '';
}
}, false);
</script>
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body>
<div id="portrait" style="width:100%;height:100%;font-size:20px;">Portrait</div>
<div id="landscape" style="width:100%;height:100%;font-size:20px;">Landscape</div>
<script type="text/javascript">
if(window.orientation==0)
{
document.getElementById('portrait').style.display = '';
document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
document.getElementById('portrait').style.display = 'none';
document.getElementById('landscape').style.display = '';
}
</script>
</body>
</html>
Tested and works on Android HTC Sense and Apple iPad.
You should use DrawEllipse
:
//
// Summary:
// Draws an ellipse defined by a bounding rectangle specified by coordinates
// for the upper-left corner of the rectangle, a height, and a width.
//
// Parameters:
// pen:
// System.Drawing.Pen that determines the color, width,
// and style of the ellipse.
//
// x:
// The x-coordinate of the upper-left corner of the bounding rectangle that
// defines the ellipse.
//
// y:
// The y-coordinate of the upper-left corner of the bounding rectangle that
// defines the ellipse.
//
// width:
// Width of the bounding rectangle that defines the ellipse.
//
// height:
// Height of the bounding rectangle that defines the ellipse.
//
// Exceptions:
// System.ArgumentNullException:
// pen is null.
public void DrawEllipse(Pen pen, int x, int y, int width, int height);
Remove the last characters from a string
TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)
.Text.Remove(10)
// used to remove text starting from index 10 to end
from ..gen_py.lib import MyService
or
from main.gen_py.lib import MyService
Make sure you have a (at least empty) __init__.py
file on each directory.
for ind in df.index:
print df['c1'][ind], df['c2'][ind]
I found a solution by myself after doing some research:
Now everything works fine.
@GetMapping
is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)
.
@GetMapping
is the newer annotaion.
It supports consumes
Consume options are :
consumes = "text/plain"
consumes = {"text/plain", "application/*"}
For Further details see: GetMapping Annotation
or read: request mapping variants
RequestMapping supports consumes as well
GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level
For Swift-3 and above:
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: .main, completionHandler: { (response, data, error) in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData as Data)
}
})
}
}
}
For me, on Windows 7, killing the ADB server and restarting it via command line did not help. It would not start up successfully.
>adb kill-server
>adb start-server
* daemon not running. starting it now on port 5037 *
ADB server didn't ACK
* failed to start daemon *
So killing the adb.exe process via Task Manager was actually the easiest solution that case.
Redis has configuration parameter pidfile
(e.g. /etc/redis.conf - check redis source code), for example:
# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
pidfile /var/run/redis.pid
If it is set or could be set, instead of searching for process id (pid) by using ps + grep
something like this could be used:
kill $(cat /var/run/redis.pid)
If required one can make redis stop script like this (adapted default redis 5.0 init.d script in redis source code):
PIDFILE=/var/run/redis.pid
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping ..."
kill $PID
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
There are below things to do.
git
command can be run successfully in CMDThat means you need to add git
to path when install git or add it to system environment later.
profile.json
Open Settings
, add following snippet inside the word profiles
:
{
"tabTitle": "Git Bash",
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "C:/Program Files/Git/bin/bash.exe --login",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 12,
"guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}",
"historySize" : 9001,
"icon": "ms-appdata:///roaming/git-bash_32px.ico",
"name" : "Git Bash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"useAcrylic" : true
}
The icon can be obtained here: git-bash_32px.ico
You can add icons for Tab to this location:
%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState
Put 32x32 PNG/icons in this folder, and then in profile.json
you can reference the image resource with the path starting with ms-appdata:// .
Note that, please make sure the Guid
is correct and it matches the corresponding correct configs.
Windows Terminal
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
I had this error when trying to use the dreadful Business Objects 4 for .Net SDK.
They ship five BusinessObjects*.dll files, but all of them are 64-bit.
To get my webpage to load, I needed to click on Tools\Options, then change this setting in VS2013:
There are some code differences to be aware of.
A negative first parameter to subtr is not supported, e.g. in Javascript: "string".substr(-1)
returns "g", whereas in JScript: "string".substr(-1)
returns "string"
It's possible to do "string"[0]
to get "s" in Javascript, but JScript doesn't support such a construct. (Actually, only modern browsers appear to support the "string"[0]
construct.
JavaScript
$scope.get_pre = function(x) {
return $sce.trustAsHtml(x);
};
HTML
<pre ng-bind-html="get_pre(html)"></pre>
This version of JavaC.sublime-build which is edited from vijay's answer works for me on both Windows 7 and Mac for Sublime Text 3.
I edited it so Ctrl+b or command+b is sufficient for both build + run.
{
"shell_cmd": "javac -Xlint $file && java $file_base_name",
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"shell": true
}
'&&' ensures that the second part runs only when first part succeeds ie only when the class file is generated. You can find more related info here: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true
-- Access:
SELECT CHR(13) & CHR(10)
-- SQL Server:
SELECT CHAR(13) + CHAR(10)
Use FormData
object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
The website you linked doesn't changes the image's width but it actually cuts it off. For that it needs to be set as a background-image.
For more info about background-image
look it at http://www.w3schools.com/cssref/pr_background-image.asp
Usage:
#divID {
background-image:url(image_url);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
You could create a helper function:
def re_match_group(pattern, str, out_groups):
del out_groups[:]
result = re.match(pattern, str)
if result:
out_groups[:len(result.groups())] = result.groups()
return result
And then use it like this:
groups = []
if re_match_group("I love (\w+)", statement, groups):
print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
print "Il aime", groups[0]
It's a little clunky, but it gets the job done.
DO LIKE THIS
<LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">
<TextView
android:id="@+id/texts1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2"
android:text="@string/forgotpass"
android:padding="7dp"
android:gravity="bottom|center_horizontal"
android:paddingLeft="10dp"
android:layout_marginBottom="30dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:textSize="16sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
/>
</LinearLayout>
This is sort of an appendage @znq's answer...
There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.
You can do this with the following custom adapter:
private static class CustomCursorAdapter extends CursorAdapter {
protected ListView mListView;
protected static class RowViewHolder {
public TextView mTitle;
public TextView mText;
}
public CustomCursorAdapter(Activity activity) {
super();
mListView = activity.getListView();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// do what you need to do
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = View.inflate(context, R.layout.row_layout, null);
RowViewHolder holder = new RowViewHolder();
holder.mTitle = (TextView) view.findViewById(R.id.Title);
holder.mText = (TextView) view.findViewById(R.id.Text);
holder.mTitle.setOnClickListener(mOnTitleClickListener);
holder.mText.setOnClickListener(mOnTextClickListener);
view.setTag(holder);
return view;
}
private OnClickListener mOnTitleClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Title clicked, row %d", position);
}
};
private OnClickListener mOnTextClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Text clicked, row %d", position);
}
};
}
$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];
but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$text.split(';')[1].split(' ')
As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:
Object.keys
, Object.values
, Object.entries
for..in
loopsJSON.stringify
But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.
Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys
and Object.getOwnPropertyNames
), the previously-unspecified methods will also iterate in the following order:
This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.
Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"
The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.
Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.
There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:
Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.
Neither the object nor anything in its prototype chain has its prototype change during iteration.
Neither the object nor anything in its prototype chain has a property deleted during iteration.
Nothing in the object's prototype chain has a property added during iteration.
No property of the object or anything in its prototype chain has its enumerability change during iteration.
No non-enumerable property shadows an enumerable one.
Try it:
String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();
if the process is still alive, add:
p.destroyForcibly();
I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.
void Main()
{
var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};
//Will update egli
WontUpdate(Person);
Console.WriteLine("WontUpdate");
Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
UpdateImplicitly(Person);
Console.WriteLine("UpdateImplicitly");
Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
UpdateExplicitly(ref Person);
Console.WriteLine("UpdateExplicitly");
Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}
//Class to test
public class Person{
public string FirstName {get; set;}
public string LastName {get; set;}
public string printName(){
return $"First name: {FirstName} Last name:{LastName}";
}
}
public static void WontUpdate(Person p)
{
//New instance does jack...
var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
newP.FirstName = "Favio";
newP.LastName = "Becerra";
}
public static void UpdateImplicitly(Person p)
{
//Passing by reference implicitly
p.FirstName = "Favio";
p.LastName = "Becerra";
}
public static void UpdateExplicitly(ref Person p)
{
//Again passing by reference explicitly (reduntant)
p.FirstName = "Favio";
p.LastName = "Becerra";
}
And that should output
WontUpdate
First name: Egli, Last name: Becerra
UpdateImplicitly
First name: Favio, Last name: Becerra
UpdateExplicitly
First name: Favio, Last name: Becerra
This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using
JDialog(null, String, boolean, Graphicsconfiguration)
is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:
JDialog((Frame) null, String, boolean, GraphicsConfiguration)
In Swift 4:
Swift 4
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Your title"
}
I hope it helps, regards!
Cmake from Windows terminal:
mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe
Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.
Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.
I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
You cannot directly remote debug Chrome on iOS currently. It uses a uiWebView that may act subtly different than Mobile Safari.
You have a few options.
Option 1: Remote-debug Mobile Safari using Safari's inspector. If your issue reproduces in Mobile Safari, this is definitely the best way to go. In fact, going through the iOS simulator is even easier.
Option 2: Use Weinre for a slimmed down debugging experience. Weinre doesn't have much features but sometimes it's good enough.
Option 3: Remote debug a proper uiWebView that functions the same.
Here's the best way to do this. You'll need to install XCode.
urlString
to be the URL you want to test.There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.
Use the FormBorderStyle
property of your Form
:
this.FormBorderStyle = FormBorderStyle.FixedDialog;
Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.
I know the tag says Windows Forms
... but, if anyone is interested in a WPF
application method, System.Printing
works like a charm.
var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
Just remember to include System.Printing
reference, if it's not already included.
Now, this method does not play well with ASP.NET
or Windows Service
. It should not be used with Windows Forms
, as it has System.Drawing.Printing
. I don't have a single issue with my PDF printing using the above code.
I should mention, however, that if your printer does not support Direct Print for PDF file format, you're out of luck with this method.
We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).
We chose it for the following reasons:
I should mention, this is speaking from an ASP.NET development point of view
I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail
from what I can tell.
So we have a library which wraps log4net and within our code we just need stuff like this:
Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());
try {
var i = int.Parse("Hello World");
} catch(FormatException, ex) {
Logger.Instance.Error(ex);
}
Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:
Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
This will become:
if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);
(Save a bit of execusion time)
By default we log at two locations:
Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.
I find Notepad works just fine for reading logs.
For me it was enough to reinstall whitelist plugin:
cordova plugin remove cordova-plugin-whitelist
and then
cordova plugin add cordova-plugin-whitelist
It looks like updating from previous versions of Cordova was not succesful.
Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
This code works for me with IE8 and Firefox
<td>
<textarea style="width:100%" rows=3 name="abc">Modify width:% accordingly</textarea>
</td>
You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.
You can add to your button OnClientClick like so:
<asp:Button ID="" runat="Server" Text="" OnClick="btnNewEntry_Click" OnClientClick="target ='_blank';"/>
This will change the current form's target for all buttons to open in new tab. So to complete the fix you can then use 2 approaches:
function ResetTarget() {
window.document.forms[0].target = '';
}
I have used the following code in the past and it had worked with basic authentication enabled in TomCat:
URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
You can try the above code. The code above is for POST, and you can modify it for GET
Writing JSON Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject
and looping through each json item. Below i am creating an instance of JSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
One can iterate from a to z like this
int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}
This is probably what you need:
$text = str_replace(' ', '_', substr($text, 0, 10));
Here is an elegant, generic implementation in Scala, as described on 99 Scala Problems.
object P26 {
def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
ls match {
case Nil => Nil
case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
}
def combinations[A](n: Int, ls: List[A]): List[List[A]] =
if (n == 0) List(Nil)
else flatMapSublists(ls) { sl =>
combinations(n - 1, sl.tail) map {sl.head :: _}
}
}
The clearest answer. Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.
This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:
/**_x000D_
* Save a text as file using HTML <a> temporary element and Blob_x000D_
* @author Loreto Parisi_x000D_
*/_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
var downloadLink = document.createElement("a");_x000D_
downloadLink.download = fileName;_x000D_
if (window.webkitURL != null) {_x000D_
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
} else {_x000D_
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
downloadLink.onclick = document.body.removeChild(event.target);_x000D_
downloadLink.style.display = "none";_x000D_
document.body.appendChild(downloadLink);_x000D_
}_x000D_
downloadLink.click();_x000D_
} else { // Alternative 2: using Data_x000D_
var pp = document.createElement('a');_x000D_
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
encodeURIComponent(fileContents));_x000D_
pp.setAttribute('download', fileName);_x000D_
pp.onclick = document.body.removeChild(event.target);_x000D_
pp.click();_x000D_
}_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
The function is called like saveAsFile('out.json', jsonString);
. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL
.
In the else
, it is possible to see the same result obtained via the href
element plus the Data API, but this has several limitations that the Blob API has not.
I am going to post this because this is what I am currently using for my site and it works in both Google Chrome and IE 10 without receiving any popup messages:
<html>
<head>
</head>
<body onload="window.close();">
</body>
</html>
I have a function on my site that I want to run to save an on/off variable to session without directly going to a new page so I just open a tiny popup webpage. That webpage then closes itself immediately with the onload="window.close();"
function.
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
Assuming the type is CV_8UC3 you would do this:
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
Vec3b bgrPixel = foo.at<Vec3b>(i, j);
// do something with BGR values...
}
}
Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.
EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:
Here is how you might go about this:
uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R
// do something with BGR values...
}
}
Or alternatively:
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
uint8_t* rowPtr = foo.row(i);
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
bgrPixel.val[2] = rowPtr[j*cn + 2]; // R
// do something with BGR values...
}
}
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
Use the replace
function in js:
var emailAdd = $(this).text().replace(/ /g,'');
That will remove all the spaces
If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :
var emailAdd = $.trim($(this).text());
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
I changed 3 things and then it works:
Follow the following steps before executing the UPDATE command: In MySQL Workbench
Edit
--> Preferences
"SQL Editor"
tab and uncheck
"Safe Updates" check box
Query
--> Reconnect to Server
// logout and then loginp.s., No need to restart the MySQL daemon!
To make a single icon be usable by all your action bars you can do this in your Android Manifest.
<application
android:logo="@drawable/Image">
...
</application>
/* you can match the exact string with table value*/
if(md5("string to match") == $res["hashstring"])
echo "login correct";
In case you are using extending the dialog the use:
requestWindowFeature(Window.FEATURE_NO_TITLE);
Or you can try the same but without listeners. On your button XML definition:
android:onClick="ButtonOnClick"
And in your code define the method ButtonOnClick
:
public void ButtonOnClick(View v) {
switch (v.getId()) {
case R.id.button1:
doSomething1();
break;
case R.id.button2:
doSomething2();
break;
}
}
I am not an expert, but I got this debug message when I wanted to send data from my android application to a web server. Though I used AsyncTask class and did the data transfer in background, for getting the result data back from server I used get() method of the AsyncTask class which makes the UI synchronous which means that your UI will be waiting for too long. So my advice is to make your app do every network oriented tasks on a separate thread.
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
I had the same problem and it kept me up for days. At the end, I realised that my URL pointing to the app was wrong altogether. example:
URL: 'http://api.example.com/'
URL: 'https://api.example.com/'.
If it's http or https verify.
Check the redirecting URL and make sure it's the same thing you're passing along.
(SELECT table1.field1 FROM table1
UNION
SELECT table2.field1 FROM table2) ORDER BY field1
Work? Remember think sets. Get the set you want using a union and then perform your operations on it.
All you need to do is to put arp into diferrent group.
Default:
-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*
With command:
sudo chown root:www-data /usr/sbin/arp
you will get:
-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*
And because apache is a daemon running under the user www-data, it's now able to execute this command.
So if you now use a PHP script, e.g.:
<?php
$mac = system('arp -an');
echo $mac;
?>
you will get the output of linux arp -an
command.
I had the same problem and I created a new listener for it and used in my fragments.
1 - Your activity should have a listener interface and a list of listeners in it
2 - You should implement methods for adding and removing the listeners
3 - You should override the onBackPressed method to check that any of the listeners use the back press or not
public class MainActivity ... {
/**
* Back press listener list. Used for notifying fragments when onBackPressed called
*/
private Stack<BackPressListener> backPressListeners = new Stack<BackPressListener>();
...
/**
* Adding new listener to back press listener stack
* @param backPressListener
*/
public void addBackPressListener(BackPressListener backPressListener) {
backPressListeners.add(backPressListener);
}
/**
* Removing the listener from back press listener stack
* @param backPressListener
*/
public void removeBackPressListener(BackPressListener backPressListener) {
backPressListeners.remove(backPressListener);
}
// Overriding onBackPressed to check that is there any listener using this back press
@Override
public void onBackPressed() {
// checks if is there any back press listeners use this press
for(BackPressListener backPressListener : backPressListeners) {
if(backPressListener.onBackPressed()) return;
}
// if not returns in the loop, calls super onBackPressed
super.onBackPressed();
}
}
4 - Your fragment must implement the interface for back press
5 - You need to add the fragment as a listener for back press
6 - You should return true from onBackPressed if the fragment uses this back press
7 - IMPORTANT - You must remove the fragment from the list onDestroy
public class MyFragment extends Fragment implements MainActivity.BackPressListener {
...
@Override
public void onAttach(Activity activity) {
super.onCreate(savedInstanceState);
// adding the fragment to listener list
((MainActivity) activity).addBackPressListener(this);
}
...
@Override
public void onDestroy() {
super.onDestroy();
// removing the fragment from the listener list
((MainActivity) getActivity()).removeBackPressListener(this);
}
...
@Override
public boolean onBackPressed() {
// you should check that if this fragment is the currently used fragment or not
// if this fragment is not used at the moment you should return false
if(!isThisFragmentVisibleAtTheMoment) return false;
if (isThisFragmentUsingBackPress) {
// do what you need to do
return true;
}
return false;
}
}
There is a Stack used instead of the ArrayList to be able to start from the latest fragment. There may be a problem also while adding fragments to the back stack. So you need to check that the fragment is visible or not while using back press. Otherwise one of the fragments will use the event and latest fragment will not be closed on back press.
I hope this solves the problem for everyone.
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
Now that the ::marker
element is available in evergreen browsers, this is how you could use it, including using :hover
to change the marker. As you can see, now you can use any Unicode character you want as a list item marker and even use custom counters.
@charset "UTF-8";
@counter-style fancy {
system: fixed;
symbols: ;
suffix: " ";
}
p {
margin-left: 8em;
}
p.note {
display: list-item;
counter-increment: note-counter;
}
p.note::marker {
content: "Note " counter(note-counter) ":";
}
ol {
margin-left: 8em;
padding-left: 0;
}
ol li {
list-style-type: lower-roman;
}
ol li::marker {
color: blue;
font-weight: bold;
}
ul {
margin-left: 8em;
padding-left: 0;
}
ul.happy li::marker {
content: "";
}
ul.happy li:hover {
color: blue;
}
ul.happy li:hover::marker {
content: "";
}
ul.fancy {
list-style: fancy;
}
_x000D_
<p>This is the first paragraph in this document.</p>
<p class="note">This is a very short document.</p>
<ol>
<li>This is the first item.
<li>This is the second item.
<li>This is the third item.
</ol>
<p>This is the end.</p>
<ul class="happy">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ul class="fancy">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
_x000D_
I was hit with this issue also and was able to come up with a sufficient solution for my case. If your Eclipse project has a .classpath file in your project root (see it in Navigator view instead of Package Explorer view), be sure that your Maven classpathentry appears prior to your JRE Container classpathentry.
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>
If your project does not have a .classpath file, you can edit your project's Java Build Path to switch the Order and Export. If your project has the .classpath file and you only change your ordering in the Java Build Path, you will see that the ordering is not impacted and the issue will continue to occur.
And a project->clean never hurts things after you make the change.
For those who are looking for a button toggle:
Even using the sqlite3.Row class-- you still can't use string formatting in the form of:
print "%(id)i - %(name)s: %(value)s" % row
In order to get past this, I use a helper function that takes the row and converts to a dictionary. I only use this when the dictionary object is preferable to the Row object (e.g. for things like string formatting where the Row object doesn't natively support the dictionary API as well). But use the Row object all other times.
def dict_from_row(row):
return dict(zip(row.keys(), row))
EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.
Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.
You can always restrict you firebase project keys to domains / IP's.
https://console.cloud.google.com/apis/credentials/key
select your project Id and key and restrict it to Your Android/iOs/web App.
If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.
First way is floor rounding the float value:
float myFloat = 3.14f;
int myInteger = (int)myFloat;
The output of this code will be 3, even if the myFloat value is closer to 4.
The second way is ceil rounding the float value:
float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);
The output of this code will be 4, because the rounding mode is always looking for the highest value.
I already showed this elsewhere on SO (How to use a variable in the format specifier statement? , not an exact duplicate IMHO), but I think it is worthwhile to place it here. It is possible to use the techniques from other answers for this question to make a simple function
function itoa(i) result(res)
character(:),allocatable :: res
integer,intent(in) :: i
character(range(i)+2) :: tmp
write(tmp,'(i0)') i
res = trim(tmp)
end function
which you can use after without worrying about trimming and left-adjusting and without writing to a temporary variable:
OPEN(1, FILE = 'Output'//itoa(i)//'.TXT')
It requires Fortran 2003 because of the allocatable string.
I tried a few of the commands that people have mentioned above. None worked. Then I got hold of the simplest of them all.
Step 1: vi <filename>
Step 2: Right click on the title bar of the Putty window
Step 3: Select "Clear scrollback" (to avoid copying the rest of your SSH session)
Step 4: Right click again and select "Copy all to clipboard".
If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.
From Crockford
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
function usesThis(name) {
this.myName = name;
function returnMe() {
return this; //scope is lost because of the inner function
}
return {
returnMe : returnMe
}
}
function usesThat(name) {
var that = this;
this.myName = name;
function returnMe() {
return that; //scope is baked in with 'that' to the "class"
}
return {
returnMe : returnMe
}
}
var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
"UsesThis thinks it's called " + usesthis.returnMe().myName);
This alerts...
UsesThat thinks it's called Dave
UsesThis thinks it's called undefined
How about trying:
select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)
which will return all date ranges which do not overlap your date range at all.
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
quite new to Python and I encountered the same issue. I find this solution quite simple and for me it works fine (Python 3.6):
unaware=parser.parse("2020-05-01 0:00:00")
aware=unaware.replace(tzinfo=tz.tzlocal()).astimezone(tz.tzlocal())
Here is another way:
static void
unhandled_interrupt(struct trap_frame *frame, int irq, void *arg)
{
//this code intentionally left blank
}
static struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {
[0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},
};
See:
Designated inits
Then ask the question: When can one use C extensions?
The code sample above is in an embedded system and will never see the light from another compiler.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
pixels = np.array(pixels)
in this line you reassign pixels
. So, it may not a list anyhow. Though pixels
is not a list it has no attributes append
. Does it make sense?
I had this error aswell.
I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.
To render any json in tabular format:
<table>
<thead>
<tr>
<th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in vm.records">
<td ng-repeat="(key, value) in value">
{{value}}
</td>
</tr>
</tbody>
</table>
My answer shows how to check the version of CuDNN installed, which is usually something that you also want to verify. You first need to find the installed cudnn file and then parse this file. To find the file, you can use:
whereis cudnn.h
CUDNN_H_PATH=$(whereis cudnn.h)
If that doesn't work, see "Redhat distributions" below.
Once you find this location you can then do the following (replacing ${CUDNN_H_PATH}
with the path):
cat ${CUDNN_H_PATH} | grep CUDNN_MAJOR -A 2
The result should look something like this:
#define CUDNN_MAJOR 7
#define CUDNN_MINOR 5
#define CUDNN_PATCHLEVEL 0
--
#define CUDNN_VERSION (CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL)
Which means the version is 7.5.0.
This method of installation installs cuda in /usr/include and /usr/lib/cuda/lib64, hence the file you need to look at is in /usr/include/cudnn.h.
CUDNN_H_PATH=/usr/include/cudnn.h
cat ${CUDNN_H_PATH} | grep CUDNN_MAJOR -A 2
From CuDNN v5 onwards (at least when you install via sudo dpkg -i <library_name>.deb
packages), it looks like you might need to use the following:
cat /usr/include/x86_64-linux-gnu/cudnn_v*.h | grep CUDNN_MAJOR -A 2
For example:
$ cat /usr/include/x86_64-linux-gnu/cudnn_v*.h | grep CUDNN_MAJOR -A 2
#define CUDNN_MAJOR 6
#define CUDNN_MINOR 0
#define CUDNN_PATCHLEVEL 21
--
#define CUDNN_VERSION (CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL)
#include "driver_types.h"
indicates that CuDNN version 6.0.21 is installed.
On CentOS, I found the location of CUDA with:
$ whereis cuda
cuda: /usr/local/cuda
I then used the procedure about on the cudnn.h file that I found from this location:
$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2
You just have to right-click on the widget and choose "center" -> "horizontally" and do it again then choose ->"vertically" This worked for me...
in my case, I just had to do something like this :
date1.toString().equals(date2.toString())
And it worked!
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
I'm not sure about HQL, but in JPA you just call the query's setParameter
with the parameter and collection.
Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);
where names
is the collection of names you're searching for
Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");
There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)
html
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.
controller
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( ...all right!... ).error( ..damn!... );
};
The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.
Don't trim the []
and you should be fine. []
identify a JSON array which is exactly what you require to be able to iterate its elements.
JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.
You can use exec.java
.
Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.
<html lang="en">_x000D_
<head>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
<div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
<div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Thought this might be handy for others. Knowing regex is useful, kids. Stay in school.
Edit: Turned it into a handy dandy function!
let specificStatusCodeMappings = {
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
};
function getStatusCodeString(code) {
if (code >= 0 && code <= 999) {
return '(Unused)';
} else if (code >= 1016) {
if (code <= 1999) {
return '(For WebSocket standard)';
} else if (code <= 2999) {
return '(For WebSocket extensions)';
} else if (code <= 3999) {
return '(For libraries and frameworks)';
} else if (code <= 4999) {
return '(For applications)';
}
}
if (typeof(specificStatusCodeMappings[code]) !== 'undefined') {
return specificStatusCodeMappings[code];
}
return '(Unknown)';
}
Usage:
getStatusCodeString(1006); //'Abnormal Closure'
{
'0-999': '(Unused)',
'1016-1999': '(For WebSocket standard)',
'2000-2999': '(For WebSocket extensions)',
'3000-3999': '(For libraries and frameworks)',
'4000-4999': '(For applications)'
}
{
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
}
Source (with minor edits for terseness): https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
You can write the below code:-
create procedure spCreateTable
as
begin
create table testtb(Name varchar(20))
end
execute it as:-
exec spCreateTable
You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.
Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt
) such as /mnt/c/Users/yourusername/files
within WSL. These files stay synced between WSL and Windows.
For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/
I'm stumbling into the same issue. For me it seems to be caused by having 2 projects with the same name, one depending on the other.
For example, I have one project named Foo which produces Foo.lib. I then have another project that's also named Foo which produces Foo.exe and links in Foo.lib.
I watched the file activity w/ Process Monitor. What seems to be happening is Foo(lib) is built first--which is proper because Foo(exe) is marked as depending on Foo(lib). This is all fine and builds successfully, and is placed in the output directory--$(OutDir)$(TargetName)$(TargetExt). Then Foo(exe) is triggered to rebuild. Well, a rebuild is a clean followed by a build. It seems like the 'clean' stage of Foo.exe is deleting Foo.lib from the output directory. This also explains why a subsequent 'build' works--that doesn't delete output files.
A bug in VS I guess.
Unfortunately I don't have a solution to the problem as it involves Rebuild. A workaround is to manually issue Clean, and then Build.
Suppose we have a collection like below:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
We want to know if the bottle field is present or not?
Ans:
db.products.find({"things.bottle":{"$exists":true}})
An alternative to msturdy's solution is using the request helper method available to you.
This works in exactly the same way, without the need to import the Input
namespace use Illuminate\Support\Facades\Input
at the top of your controller.
For example:
class SearchController extends BaseController {
public function search()
{
$category = request('category', 'default');
$term = request('term'); // no default defined
...
}
}
There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.
DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"
DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
Scott Hanselman has a writeup on it on his blog
I have a short version for you. It works well for me!
var match = str.match(/[abc]/gi);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
And if you want a prototype version:
String.prototype.indexOfRegex = function(regex){
var match = this.match(regex);
return match ? this.indexOf(match[0]) : -1;
}
String.prototype.lastIndexOfRegex = function(regex){
var match = this.match(regex);
return match ? this.lastIndexOf(match[match.length-1]) : -1;
}
EDIT : if you want to add support for fromIndex
String.prototype.indexOfRegex = function(regex, fromIndex){
var str = fromIndex ? this.substring(fromIndex) : this;
var match = str.match(regex);
return match ? str.indexOf(match[0]) + fromIndex : -1;
}
String.prototype.lastIndexOfRegex = function(regex, fromIndex){
var str = fromIndex ? this.substring(0, fromIndex) : this;
var match = str.match(regex);
return match ? str.lastIndexOf(match[match.length-1]) : -1;
}
To use it, as simple as this:
var firstIndex = str.indexOfRegex(/[abc]/gi);
var lastIndex = str.lastIndexOfRegex(/[abc]/gi);
Math
has static method where you can call directly like Math.abs()
while Date
has static method like Date.now()
and also instance method where you need to create new instance first var time = new Date()
to call time.getHours()
.
// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);
// And for the static method
var keys = Object.getOwnPropertyNames(Date);
// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);
Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name
that aren't a function on the list.
But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__
. For saving your time you can use script below to get static method and deep method instance.
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
for(var i = 0; i < keys2.length; i++){_x000D_
if(clas[keys2[i]].constructor === Function)_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
if(clas.prototype === void 0)_x000D_
return;_x000D_
_x000D_
var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
if(keys2[i] !== 'constructor')_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
_x000D_
var deep = Object.getPrototypeOf(clas);_x000D_
if(deep.prototype !== void 0)_x000D_
getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
If you want to obtain methods from created instance, don't forget to pass the constructor
of it.
String value = someMethod();
switch(0) {
default:
if ("apple".equals(value)) {
method1();
break;
}
if ("carrot".equals(value)) {
method2();
break;
}
if ("mango".equals(value)) {
method3();
break;
}
if ("orance".equals(value)) {
method4();
break;
}
}
In many practical cases instead of using type
or isinstance
you can also use @functools.singledispatch
, which is used to define generic functions (function composed of multiple functions implementing the same operation for different types).
In other words, you would want to use it when you have a code like the following:
def do_something(arg):
if isinstance(arg, int):
... # some code specific to processing integers
if isinstance(arg, str):
... # some code specific to processing strings
if isinstance(arg, list):
... # some code specific to processing lists
... # etc
Here is a small example of how it works:
from functools import singledispatch
@singledispatch
def say_type(arg):
raise NotImplementedError(f"I don't work with {type(arg)}")
@say_type.register
def _(arg: int):
print(f"{arg} is an integer")
@say_type.register
def _(arg: bool):
print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>
Additionaly we can use abstract classes to cover several types at once:
from collections.abc import Sequence
@say_type.register
def _(arg: Sequence):
print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!
F5 to run the current query is an easy win, after that, the generic MS editor commands of CTRL + K + C to comment out the selected text and then CTRL + K + U to uncomment.
Mini tip:
I had the following scenario:
<a href="/page/">My link text
:after
</a>
I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.
I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.
Visibility: hidden: Didn't allow me to use :after.
text-indent: -9999px;: Also moved the :after element
That file will allow all crawlers access
User-agent: *
Allow: /
This basically allows all user agents (the *) to all parts of the site (the /).
Well, if you don't want to do the work yourself (object
elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/
To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow
instead of pcolormesh
because of the 1:1 aspect ratio imposed by imshow
.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.flat)
plt.show()
give id to submit button
<button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>
$('#btnSave').click(function() {
$('#StudentModal').modal('hide');
});
Also you forgot to close last div.
</div>
Hope this helps.
If you had use strict
turned on, you would have found out that $++foo
doesn't make any sense.
Here's how to do it:
use strict;
use warnings;
my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";
while( my $line = <$info>) {
print $line;
last if $. == 2;
}
close $info;
This takes advantage of the special variable $.
which keeps track of the line number in the current file. (See perlvar)
If you want to use a counter instead, use
my $count = 0;
while( my $line = <$info>) {
print $line;
last if ++$count == 2;
}
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
It's easier to use the timestamp for this things since Tweepy gets both
import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))
Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.
Nobody answered with regular for
loop? Sometimes I find it more readable and prefer for
over foreach
So here it is:
$array = array('key1' => 'value1', 'key2' => 'value2');
$keys = array_keys($array);
for($i=0; $i < count($keys); ++$i) {
echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}
/*
prints:
key1 value1
key2 value2
*/
I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:
At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection
Use vscode-solution-explorer
extension:
This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.
https://github.com/fernandoescolar/vscode-solution-explorer
Thanks @fernandoescolar
There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off
then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.
You can return the same value from several matches:
SELECT
CASE c.Number
WHEN '1121231' THEN 1
WHEN '31242323' THEN 1
WHEN '234523' THEN 2
WHEN '2342423' THEN 2
END AS Test
FROM tblClient c
This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.
Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.
If you just want to compare only one row with $lactureName then use following
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
if(mysql_num_rows($result) > 0)
{
mysql_close($con);
return "Assigned";
}
else
{
mysql_close($con);
return "Available";
}
}
You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.
Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.
I can think of two things:
First, try loading the image with:
string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));
Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".
Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx
As of .NET 4.6, you can use a DateTimeOffset
object to get the unix milliseconds. It has a constructor which takes a DateTime
object, so you can just pass in your object as demonstrated below.
DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();
As noted in other answers, make sure yourDateTime
has the correct Kind
specified, or use .ToUniversalTime()
to convert it to UTC time first.
Here you can learn more about DateTimeOffset
.
To check if a folder contains at least one file
>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder or any of its descendents contain at least one file
>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder contains at least one file or folder.
Note addition of /a
option to enable finding of hidden and system files/folders.
dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)
To check if a folder contains at least one folder
dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)
You can not use more than one Structural Directive
in Angular on the same element, it makes a bad confusion and structure, so you need to apply them in 2 separate nested elements(or you can use ng-container
), read this statement from Angular team:
One structural directive per host element
Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.
The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?
There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.
So you can use ng-container
(Angular4) as the wrapper (will be deleted from the dom) or a div or span if you have class or some other attributes as below:
<div class="right" *ngIf="show">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</div>
10 years later but that problem still caught me.
So this is the answer to those that are too late as me.
This does not work
int b = (int) Math.ceil(a / 100);
Cause the result a / 100
turns out to be an integer and it's rounded so Math.ceil
can't do anything about it.
You have to avoid the rounded operation with this
int b = (int) Math.ceil((float) a / 100);
Now it works.
Same situation: Having done multiple Angular projects and moving to React, not having a simple way to provide services through DI seems like a missing piece (the particulars of the service aside).
Using context and ES7 decorators we can come close:
https://jaysoo.ca/2015/06/09/react-contexts-and-dependency-injection/
Seems these guys have taken it a step further / in a different direction:
http://blog.wolksoftware.com/dependency-injection-in-react-powered-inversifyjs
Still feels like working against the grain. Will revisit this answer in 6 months time after undertaking a major React project.
EDIT: Back 6 months later with some more React experience. Consider the nature of the logic:
Some also reach for HOCs for reuse but for me the above covers almost all use cases. Also, consider scaling state management using ducks to keep concerns separate and state UI-centric.
I wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
Perhaps the easiest is to use position: absolute
to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.
css:
<style>
body {
margin: 0 0 20px;
}
.footer {
position: absolute;
bottom: 0;
height: 20px;
background: #f0f0f0;
width: 100%;
}
</style>
Here is the html main content.
<div class="footer"> Here is the footer. </div>
Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().
Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.
The following approach works for me:
<exclude name="**/dir_name_to_exclude/**" />
If you recently update your Android Studio to 3.3.1 that have a problem with com.google.gms:google-services (Below 4.2.0) dependencies So please update com.google.gms:google-services to 4.2.0.
dependencies {
classpath 'com.android.tools.build:gradle:3.3.1'
classpath 'com.google.gms:google-services:4.2.0'
}
The documentation is your friend, NSString
supports a call substringWithRange
that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString
it is immutable. If you have an NSMutableString
is has a method called deleteCharactersInRange
that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...
I used this a little example and it worked.
$('#date').datetimepicker({
defaultDate: new Date()
});
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
From react docs Passing arguments to event handlers
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
Use this one :
onSelect: function(dateText) {
$("input#DateTo").datepicker('option', 'minDate', dateText);
}
This may be useful : http://jsfiddle.net/injulkarnilesh/xNeTe/
If the sent_at field is not there when its not set then:
db.emails.count({sent_at: {$exists: false}})
If its there and null, or not there at all:
db.emails.count({sent_at: null})
Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways
setNull(..)
and
set<ClassName>(.., null))
behave the same way.
This is my solution. It works also in Fragment.
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
The documentation says it best and includes an example, (highlighting mine).
android:weightSum
Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.
So to correct superM's example, suppose you have a LinearLayout
with horizontal orientation that contains two ImageViews
and a TextView
with. You define the TextView
to have a fixed size, and you'd like the two ImageViews
to take up the remaining space equally.
To accomplish this, you would apply layout_weight
1 to each ImageView
, none on the TextView
, and a weightSum
of 2.0 on the LinearLayout
.
in jquery-3.1.1
$("#id").load(function(){_x000D_
//code goes here});
_x000D_
will not work because load function is no more work