===
and !==
are strict comparison operators:
JavaScript has both strict and type-converting equality comparison. For
strict
equality the objects being compared must have the same type and:
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
- Two numbers are strictly equal when they are numerically equal (have the same number value).
NaN
is not equal to anything, includingNaN
. Positive and negative zeros are equal to one another.- Two Boolean operands are strictly equal if both are true or both are false.
- Two objects are strictly equal if they refer to the same
Object
.Null
andUndefined
types are==
(but not===
). [I.e. (Null==Undefined
) istrue
but (Null===Undefined
) isfalse
]
Why ==
is so unpredictable?
What do you get when you compare an empty string ""
with the number zero 0
?
true
Yep, that's right according to ==
an empty string and the number zero are the same time.
And it doesn't end there, here's another one:
'0' == false // true
Things get really weird with arrays.
[1] == true // true
[] == false // true
[[]] == false // true
[0] == false // true
Then weirder with strings
[1,2,3] == '1,2,3' // true - REALLY?!
'\r\n\t' == 0 // true - Come on!
It get's worse:
When is equal not equal?
let A = '' // empty string
let B = 0 // zero
let C = '0' // zero string
A == B // true - ok...
B == C // true - so far so good...
A == C // **FALSE** - Plot twist!
Let me say that again:
(A == B) && (B == C) // true
(A == C) // **FALSE**
And this is just the crazy stuff you get with primitives.
It's a whole new level of crazy when you use ==
with objects.
At this point your probably wondering...
Why does this happen?
Well it's because unlike "triple equals" (===
) which just checks if two values are the same.
==
does a whole bunch of other stuff.
It has special handling for functions, special handling for nulls, undefined, strings, you name it.
It get's pretty wacky.
In fact, if you tried to write a function that does what ==
does it would look something like this:
function isEqual(x, y) { // if `==` were a function
if(typeof y === typeof x) return y === x;
// treat null and undefined the same
var xIsNothing = (y === undefined) || (y === null);
var yIsNothing = (x === undefined) || (x === null);
if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);
if(typeof y === "function" || typeof x === "function") {
// if either value is a string
// convert the function into a string and compare
if(typeof x === "string") {
return x === y.toString();
} else if(typeof y === "string") {
return x.toString() === y;
}
return false;
}
if(typeof x === "object") x = toPrimitive(x);
if(typeof y === "object") y = toPrimitive(y);
if(typeof y === typeof x) return y === x;
// convert x and y into numbers if they are not already use the "+" trick
if(typeof x !== "number") x = +x;
if(typeof y !== "number") y = +y;
// actually the real `==` is even more complicated than this, especially in ES6
return x === y;
}
function toPrimitive(obj) {
var value = obj.valueOf();
if(obj !== value) return value;
return obj.toString();
}
So what does this mean?
It means ==
is complicated.
Because it's complicated it's hard to know what's going to happen when you use it.
Which means you could end up with bugs.
So the moral of the story is...
Make your life less complicated.
Use ===
instead of ==
.
The End.
Sounds like you're entering the commands in command mode (aka. "Ex mode"). In that context :5d
would remove line number 5, nothing else. For 5dd
to work as intended -- that is, remove five consequent lines starting at the cursor -- enter it in normal mode and don't prefix the commands with :
.
To change indicator color and height programmatically you can use reflection. for example for indicator color use code below:
try {
Field field = TabLayout.class.getDeclaredField("mTabStrip");
field.setAccessible(true);
Object ob = field.get(tabLayout);
Class<?> c = Class.forName("android.support.design.widget.TabLayout$SlidingTabStrip");
Method method = c.getDeclaredMethod("setSelectedIndicatorColor", int.class);
method.setAccessible(true);
method.invoke(ob, Color.RED);//now its ok
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
and to change indicator height use "setSelectedIndicatorHeight" instead of "setSelectedIndicatorColor" then invoke it by your desired height
The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...
I ended up having an old reference to a class (an HttpHandler
) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.
System.Convert.IsDbNull][1](table.rows[0][0]);
IIRC, the (table.rows[0][0] == null)
won't work, as DbNull.Value != null;
A few other good references on those topics:
I use the index as a checkpoint.
When I'm about to make a change that might go awry — when I want to explore some direction that I'm not sure if I can follow through on or even whether it's a good idea, such as a conceptually demanding refactoring or changing a representation type — I checkpoint my work into the index.
If this is the first change I've made since my last commit, then I can use the local repository as a checkpoint, but often I've got one conceptual change that I'm implementing as a set of little steps.
I want to checkpoint after each step, but save the commit until I've gotten back to working, tested code.
Notes:
the workspace is the directory tree of (source) files that you see and edit.
The index is a single, large, binary file in
<baseOfRepo>/.git/index
, which lists all files in the current branch, their sha1 checksums, time stamps and the file name -- it is not another directory with a copy of files in it.The local repository is a hidden directory (
.git
) including anobjects
directory containing all versions of every file in the repo (local branches and copies of remote branches) as a compressed "blob" file.Don't think of the four 'disks' represented in the image above as separate copies of the repo files.
They are basically named references for Git commits. There are two major types of refs: tags and heads.
- Tags are fixed references that mark a specific point in history, for example v2.6.29.
- On the contrary, heads are always moved to reflect the current position of project development.
(note: as commented by Timo Huovinen, those arrows are not what the commits point to, it's the workflow order, basically showing arrows as 1 -> 2 -> 3 -> 4
where 1
is the first commit and 4
is the last)
Now we know what is happening in the project.
But to know what is happening right here, right now there is a special reference called HEAD. It serves two major purposes:
- it tells Git which commit to take files from when you checkout, and
- it tells Git where to put new commits when you commit.
When you run
git checkout ref
it pointsHEAD
to the ref you’ve designated and extracts files from it. When you rungit commit
it creates a new commit object, which becomes a child of currentHEAD
. NormallyHEAD
points to one of the heads, so everything works out just fine.
From Bjarne Stroustrup's C++11 FAQ:
The
enum class
es ("new enums", "strong enums") address three problems with traditional C++ enumerations:
- conventional enums implicitly convert to int, causing errors when someone does not want an enumeration to act as an integer.
- conventional enums export their enumerators to the surrounding scope, causing name clashes.
- the underlying type of an
enum
cannot be specified, causing confusion, compatibility problems, and makes forward declaration impossible.The new enums are "enum class" because they combine aspects of traditional enumerations (names values) with aspects of classes (scoped members and absence of conversions).
So, as mentioned by other users, the "strong enums" would make the code safer.
The underlying type of a "classic" enum
shall be an integer type large enough to fit all the values of the enum
; this is usually an int
. Also each enumerated type shall be compatible with char
or a signed/unsigned integer type.
This is a wide description of what an enum
underlying type must be, so each compiler will take decisions on his own about the underlying type of the classic enum
and sometimes the result could be surprising.
For example, I've seen code like this a bunch of times:
enum E_MY_FAVOURITE_FRUITS
{
E_APPLE = 0x01,
E_WATERMELON = 0x02,
E_COCONUT = 0x04,
E_STRAWBERRY = 0x08,
E_CHERRY = 0x10,
E_PINEAPPLE = 0x20,
E_BANANA = 0x40,
E_MANGO = 0x80,
E_MY_FAVOURITE_FRUITS_FORCE8 = 0xFF // 'Force' 8bits, how can you tell?
};
In the code above, some naive coder is thinking that the compiler will store the E_MY_FAVOURITE_FRUITS
values into an unsigned 8bit type... but there's no warranty about it: the compiler may choose unsigned char
or int
or short
, any of those types are large enough to fit all the values seen in the enum
. Adding the field E_MY_FAVOURITE_FRUITS_FORCE8
is a burden and doesn't forces the compiler to make any kind of choice about the underlying type of the enum
.
If there's some piece of code that rely on the type size and/or assumes that E_MY_FAVOURITE_FRUITS
would be of some width (e.g: serialization routines) this code could behave in some weird ways depending on the compiler thoughts.
And to make matters worse, if some workmate adds carelessly a new value to our enum
:
E_DEVIL_FRUIT = 0x100, // New fruit, with value greater than 8bits
The compiler doesn't complain about it! It just resizes the type to fit all the values of the enum
(assuming that the compiler were using the smallest type possible, which is an assumption that we cannot do). This simple and careless addition to the enum
could subtlety break related code.
Since C++11 is possible to specify the underlying type for enum
and enum class
(thanks rdb) so this issue is neatly addressed:
enum class E_MY_FAVOURITE_FRUITS : unsigned char
{
E_APPLE = 0x01,
E_WATERMELON = 0x02,
E_COCONUT = 0x04,
E_STRAWBERRY = 0x08,
E_CHERRY = 0x10,
E_PINEAPPLE = 0x20,
E_BANANA = 0x40,
E_MANGO = 0x80,
E_DEVIL_FRUIT = 0x100, // Warning!: constant value truncated
};
Specifying the underlying type if a field have an expression out of the range of this type the compiler will complain instead of changing the underlying type.
I think that this is a good safety improvement.
So Why is enum class preferred over plain enum?, if we can choose the underlying type for scoped(enum class
) and unscoped (enum
) enums what else makes enum class
a better choice?:
int
.For those who intend to use venv
:
If you don't already have pip
for Python 3:
sudo apt install python3-pip
Install venv
package:
sudo apt install python3.7-venv
Create virtual environment (which will be bootstrapped with pip
by default):
python3.7 -m venv /path/to/new/virtual/environment
To activate the virtual environment, source
the appropriate script for the current shell, from the bin
directory of the virtual environment. The appropriate scripts for the different shells are:
bash/zsh – activate
fish – activate.fish
csh/tcsh – activate.csh
For example, if using bash:
source /path/to/new/virtual/environment/bin/activate
Optionally, to update pip
for the virtual environment (while it is activated):
pip install --upgrade pip
When you want to deactivate the virtual environment:
deactivate
Don't know why, my Neon Eclipse still having this issue, it doesn't seem to be fixed in Mars version as many people said.
I found that using command is too troublesome, I delete the plugin away via the Eclipse Installation Manager.
Just select the plugin "Dali Java Persistence Tools -JPA Support" and click "uninstall" will do. Please take note my screen below doesn't have that because I already uninstalled.
Next to being in the wrong directory I just tripped about another variant:
I had a File.open(my_file).each {|line| puts line}
exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file)
which strangely returned false
. Explanation: my_file
was a symlink which target didn't exist anymore! Since File.exists?
will follow a symlink it will say false
though the link is still there.
The other li elements are not siblings of the a element.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().children().removeClass('current');
});
Please stick to the nio API to perform these checks
import java.nio.file.*;
static Boolean isDir(Path path) {
if (path == null || !Files.exists(path)) return false;
else return Files.isDirectory(path);
}
The answer by @kirilloid seems to be the correct answer, however, the main code needs to be updated. His solution doesn't take care of negative numbers (which someone did mention in the comment section but has not been updated in the main code).
Updating that to a complete final tested solution:
Number.prototype.toFixedDown = function(digits) {
var re = new RegExp("([-]*\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
Sample Usage:
var x = 3.1415629;
Logger.log(x.toFixedDown(2)); //or use whatever you use to log
Fiddle: JS Number Round down
PS: Not enough repo to comment on that solution.
You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.
They take up different amounts of space and they have different ranges of acceptable values.
Here are the sizes and ranges of values for SQL Server, other RDBMSes have similar documentation:
Turns out they all use the same specification (with a few minor exceptions noted below) but support various combinations of those types (Oracle not included because it has just a NUMBER
datatype, see the above link):
| SQL Server MySQL Postgres DB2
---------------------------------------------------
tinyint | X X
smallint | X X X X
mediumint | X
int/integer | X X X X
bigint | X X X X
And they support the same value ranges (with one exception below) and all have the same storage requirements:
| Bytes Range (signed) Range (unsigned)
--------------------------------------------------------------------------------------------
tinyint | 1 byte -128 to 127 0 to 255
smallint | 2 bytes -32768 to 32767 0 to 65535
mediumint | 3 bytes -8388608 to 8388607 0 to 16777215
int/integer | 4 bytes -2147483648 to 2147483647 0 to 4294967295
bigint | 8 bytes -9223372036854775808 to 9223372036854775807 0 to 18446744073709551615
The "unsigned" types are only available in MySQL, and the rest just use the signed ranges, with one notable exception: tinyint
in SQL Server is unsigned and has a value range of 0 to 255
The accepted answer throws a ProtocolException at:
OutputStream os = conn.getOutputStream();
because it does not enable the output for the URLConnection object. The solution should include this:
conn.setDoOutput(true);
to make it work.
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
Here's a simple one liner
$ip = $_SERVER['HTTP_X_FORWARDED_FOR']?: $_SERVER['HTTP_CLIENT_IP']?: $_SERVER['REMOTE_ADDR'];
EDIT:
Above code may return reserved addresses (like 10.0.0.1), a list of addresses of all proxy servers on the way, etc. To handle these cases use the following code:
function valid_ip($ip) {
// for list of reserved IP addresses, see https://en.wikipedia.org/wiki/Reserved_IP_addresses
return $ip && substr($ip, 0, 4) != '127.' && substr($ip, 0, 4) != '127.' && substr($ip, 0, 3) != '10.' && substr($ip, 0, 2) != '0.' ? $ip : false;
}
function get_client_ip() {
// using explode to get only client ip from list of forwarders. see https://en.wikipedia.org/wiki/X-Forwarded-For
return
@$_SERVER['HTTP_X_FORWARDED_FOR'] ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'], 2)[0] :
@$_SERVER['HTTP_CLIENT_IP'] ? explode(',', $_SERVER['HTTP_CLIENT_IP'], 2)[0] :
valid_ip(@$_SERVER['REMOTE_ADDR']) ?:
'UNKNOWN';
}
echo get_client_ip();
There is a new (sometime pre April 2013) option on the site that says "Clone in Windows".
This works very nicely if you already have the Windows GitHub Client as mentioned by @Tommy in his answer on this related question (How to download source in ZIP format from GitHub?).
For XCode 9.3 indexing issue - Uninstall the XCode and instal again from zero. Works for me.
OSX User adjustments.
Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.
I put the cert.pem
file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.
Configure git to trust this certificate:
$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem
This works perfectly
<i class="fa fa-power-off text-gray" style="transform: rotate(90deg);"></i>
For future readers.
I wanted specific control over this issue, so this is what I did:
From a fragment or activity, hide your other views (that aren't needed while the keyboard is up), then restore them to solve this problem:
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
int heightDiff = rootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
//ok now we know the keyboard is up...
view_one.setVisibility(View.GONE);
view_two.setVisibility(View.GONE);
} else {
//ok now we know the keyboard is down...
view_one.setVisibility(View.VISIBLE);
view_two.setVisibility(View.VISIBLE);
}
}
});
I'm guessing you have two python installs, or two pip installs, one of which has been partially removed.
Why do you use sudo
? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissions issues (e.g. see the warning it gives about "parent directory is not owned by the current user").
What do you get if you run this?
$ head -n1 /usr/local/bin/pip
This will show you which python binary pip
is trying to use. If it's pointing /usr/local/opt/python/bin/python2.7
, then try running this:
$ ls -al /usr/local/opt/python/bin/python2.7
If this says "No such file or directory", then pip is trying to use a python binary that has been removed.
Next, try this:
$ which python
$ which python2.7
To see the path of the python binary that's actually working.
Since it looks like pip was successfully installed somewhere, it could be that /usr/local/bin/pip
is part of an older installation of pip that's higher up on the PATH
. To test that, you may try moving the non-functioning pip
binary out of the way like this (might require sudo
):
$ mv /usr/local/bin/pip /usr/local/bin/pip.old
Then try running your pip --version
command again. Hopefully it picks up the correct version and runs successfully.
Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:
private string ComputeHash(Guid input)
{
byte[] source = input.ToByteArray();
var encoder = new SHA256Managed();
byte[] encoded = encoder.ComputeHash(source);
return Convert.ToBase64String(encoded);
}
In CreateAsync
:
var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());
ReceiveAsync
:
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
Guid token;
if (Guid.TryParse(context.Token, out token))
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
{
context.SetTicket(ticket);
}
}
}
EditPad Pro and PowerGREP have a unique feature that allows you to change the case of the backreference.
\U1
inserts the first backreference in uppercase,\L1
in lowercase and\F1
with the first character in uppercase and the remainder in lowercase. Finally,\I1
inserts it with the first letter of each word capitalized, and the other letters in lowercase.
Source: Goyvaerts, Jan (2006). Regular Expressions: The Complete Tutorial. Lulu.com. p. 35. ISBN 1411677609. Google Books. Retrieved on June 25, 2010.
Post-increment:
int x, y, z;
x = 1;
y = x++; //this means: y is assigned the x value first, then increase the value of x by 1. Thus y is 1;
z = x; //the value of x in this line and the rest is 2 because it was increased by 1 in the above line. Thus z is 2.
Pre-increment:
int x, y, z;
x = 1;
y = ++x; //this means: increase the value of x by 1 first, then assign the value of x to y. The value of x in this line and the rest is 2. Thus y is 2.
z = x; //the value of x in this line is 2 as stated above. Thus z is 2.
When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder
add "my-resource.txt" file inside the new folder. Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto
. This is my current favorite solution
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
Just use a custom comparator (it's an optional 3rd argument to std::sort
)
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
If you're using a C++11 compiler, you can write the same using lambdas:
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
then you can do this too:
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
or even
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here
In Xcode 7:
same result as others, different style:
extension UIImage {
func withAlpha(_ alpha: CGFloat) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { _ in
draw(at: .zero, blendMode: .normal, alpha: alpha)
}
}
}
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');
Using writeLines also allows you to dispense with the "\n" newline character, by using c()
. As in:
writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))
This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.
Step For Windows
now command prompt will be open.
after the type cd filepath of file. ex(cd C:\Users\user\Desktop\ ) then hit the enter.
C:\Users\user\Desktop>node app.js
just use this at the end of your button click event
protected void btnAddButton_Click(object sender, EventArgs e)
{
... save data routin
Response.Redirect(Request.Url.AbsoluteUri);
}
I use the sync
subcommand of hub to automate this. I have alias git=hub
in my .bash_profile
, so the command I type is:
git sync
This updates all local branches that have a matching upstream branch. From the man page:
- If the local branch is outdated, fast-forward it;
- If the local branch contains unpushed work, warn about it;
- If the branch seems merged and its upstream branch was deleted, delete it.
It also handles stashing/unstashing uncommitted changes on the current branch.
I used to use a similar tool called git-up, but it's no longer maintained, and git sync
does almost exactly the same thing.
The absolute simplest example I can think of is to make incrementing an atomic operation.
With standard ints:
private volatile int counter;
public int getNextUniqueIndex() {
return counter++; // Not atomic, multiple threads could get the same result
}
With AtomicInteger:
private AtomicInteger counter;
public int getNextUniqueIndex() {
return counter.getAndIncrement();
}
The latter is a very simple way to perform simple mutations effects (especially counting, or unique-indexing), without having to resort to synchronizing all access.
More complex synchronization-free logic can be employed by using compareAndSet()
as a type of optimistic locking - get the current value, compute result based on this, set this result iff value is still the input used to do the calculation, else start again - but the counting examples are very useful, and I'll often use AtomicIntegers
for counting and VM-wide unique generators if there's any hint of multiple threads being involved, because they're so easy to work with I'd almost consider it premature optimisation to use plain ints
.
While you can almost always achieve the same synchronization guarantees with ints
and appropriate synchronized
declarations, the beauty of AtomicInteger
is that the thread-safety is built into the actual object itself, rather than you needing to worry about the possible interleavings, and monitors held, of every method that happens to access the int
value. It's much harder to accidentally violate threadsafety when calling getAndIncrement()
than when returning i++
and remembering (or not) to acquire the correct set of monitors beforehand.
I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url
I created this, just add the function as an argument and whenever the link has any changes it will run the function returning the old and new url
// on-url-change.js v1 (manual verification)
let onUrlChangeCallbacks = [];
let onUrlChangeTimestamp = new Date() * 1;
function onUrlChange(callback){
onUrlChangeCallbacks.push(callback);
};
onUrlChangeAutorun();
function onUrlChangeAutorun(){
let oldURL = window.location.href;
setInterval(function(){
let newURL = window.location.href;
if(oldURL !== newURL){
let event = {
oldURL: oldURL,
newURL: newURL,
type: 'urlchange',
timestamp: new Date() * 1 - onUrlChangeTimestamp
};
oldURL = newURL;
for(let i = 0; i < onUrlChangeCallbacks.length; i++){
onUrlChangeCallbacks[i](event);
};
};
}, 25);
};
For me it works:
document.getElementById("checkyear").value = "1";
alert(document.getElementById("checkyear").value);
Maybe your JS is not executed and you need to add a function() {} around it all.
Write unit tests. You can test a lot of things in Cocoa that might be harder in other frameworks. For example, with UI code, you can generally verify that things are connected as they should be and trust that they'll work when used. And you can set up state & invoke delegate methods easily to test them.
You also don't have public vs. protected vs. private method visibility getting in the way of writing tests for your internals.
Simply add static
in the declaration of these two methods and the compile time error will disappear!
By default in C# methods are instance methods, and they receive the implicit "self" argument. By making them static, no such argument is needed (nor available), and the method must then of course refrain from accessing any instance (non-static) objects or methods of the class.
More info on static methods
Provided the class and the method's access modifiers (public vs. private) are ok, a static method can then be called from anywhere without having to previously instantiate a instance of the class. In other words static methods are used with the following syntax:
className.classMethod(arguments)
rather than
someInstanceVariable.classMethod(arguments)
A classical example of static methods are found in the System.Math class, whereby we can call a bunch of these methods like
Math.Sqrt(2)
Math.Cos(Math.PI)
without ever instantiating a "Math" class (in fact I don't even know if such an instance is possible)
No, it certainly is not. It is just another variable name. The $()
you're talking about is actually the jQuery core function. The $self
is just a variable. You can even rename it to foo
if you want, this doesn't change things. The $
(and _
) are legal characters in a Javascript identifier.
Why this is done so is often just some code convention or to avoid clashes with reversed keywords. I often use it for $this
as follows:
var $this = $(this);
cliff.meyers's original answer that suggested using <env-entry>
will not help when using only System.getProperty()
According to the Tomcat 6.0 docs <env-entry>
is for JNDI. So that means it won't have any effect on System.getProperty()
.
With the <env-entry>
from cliff.meyers's example, the following code
System.getProperty("SMTP_PASSWORD");
will return null, not the value "abc123ftw".
According to the Tomcat 6 docs, to use <env-entry>
you'd have to write code like this to use <env-entry>
:
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");
Caveat: I have not actually tried the example above. But I have tried <env-entry>
with System.getProperty(), and that definitely does not work.
Javascript passes variables by reference
, this means that:
var i = [];
var j = i;
i.push( 1 );
Now because of by reference
part i
is [1], and j
is [1] as well, even though only i
was changed. This is because when we say j = i
javascript doesn't copy the i
variable and assign it to j
but references i
variable through j
.
Angular copy lets us lose this reference, which means:
var i = [];
var j = angular.copy( i );
i.push( 1 );
Now i
here equals to [1], while j
still equals to [].
There are situations when such kind of copy
functionality is very handy.
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
I cross that situation by replacing all androidx.*
to appropiate package name
.
change your line
implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
to
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
NOTED
tools:replace="android:appComponentFactory"
from AndroidManifestint i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
You can also use numpy loadtxt like
from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)
@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:
DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]
OUTPUT:
(2 row(s) affected)
Rows ROWCOUNT
----------- -----------
2 1
(1 row(s) affected)
you get Rows
value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT
command affected 1 row
if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:
--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal int
DECLARE @PeachTotal int
SELECT @AppleTotal=0,@PeachTotal=0
BEGIN TRANSACTION
INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
COMMIT
SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
Caucho Quercus can run PHP code on the jvm.
With recent Maven versions (3) and recent version of the maven compiler plugin (3.7.0), I notice that adding a source folder with the build-helper-maven-plugin
is not required if the folder that contains the source code to add in the build is located in the target
folder or a subfolder of it.
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
For example having some (generated or no) source code in target/a
, target/generated-source/foo
will be compiled and added in the outputDirectory : target/classes
.
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
A variation using just standard color code:
android:textColor="#ff0000"
Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:
Implementors should be aware that this specification is not stable.
Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
m=input("row")
n=input("col")
X=[]
for i in range (m):
m1=[]
for j in range (n):
m1.append(input("num"))
X.append(m1)
Y=[]
for i in range (m):
n1=[]
for j in range (n):
n1.append(input("num"))
Y.append(n1)
# result is 3x3
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Seeing as this isn't already mentioned here and it's how I got around the issue...
Right click the target database and choose Tasks > Export data
and follow that through. One of the destinations on the 'Choose a destination' screen is Microsoft Excel and there's a step that will accept your query.
It's the SQL Server Import and Export wizard. It's a lot more long-winded than the simple Copy with headers option that I normally use but, save jumping through a lot more hoops, when you have a lot of data to get into excel it's a worthy option.
You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:
File > New > Project...
Maven
and select Maven Project
and click Next
.Create a simple project
(to skip the archetype selection).jar
, and a Name.Run as > Maven install
.You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
On a Mac you can can select the text that you are after then press: cmd + ctrl + G
This will select every instance of your selected text within the same document. If you now start typing to replace your original highlighted text, you will replace all of the other occurrences at the same time.
You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1
Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.
You could do:
Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components
In a BST, all values descending on the left side of a node are less than (or equal to, see later) the node itself. Similarly, all values descending on the right side of a node are greater than (or equal to) that node value(a).
Some BSTs may choose to allow duplicate values, hence the "or equal to" qualifiers above. The following example may clarify:
14
/ \
13 22
/ / \
1 16 29
/ \
28 29
This shows a BST that allows duplicates(b) - you can see that to find a value, you start at the root node and go down the left or right subtree depending on whether your search value is less than or greater than the node value.
This can be done recursively with something like:
def hasVal (node, srchval):
if node == NULL:
return false
if node.val == srchval:
return true
if node.val > srchval:
return hasVal (node.left, srchval)
return hasVal (node.right, srchval)
and calling it with:
foundIt = hasVal (rootNode, valToLookFor)
Duplicates add a little complexity since you may need to keep searching once you've found your value, for other nodes of the same value. Obviously that doesn't matter for hasVal
since it doesn't matter how many there are, just whether at least one exists. It will however matter for things like countVal
, since it needs to know how many there are.
(a) You could actually sort them in the opposite direction should you so wish provided you adjust how you search for a specific key. A BST need only maintain some sorted order, whether that's ascending or descending (or even some weird multi-layer-sort method like all odd numbers ascending, then all even numbers descending) is not relevant.
(b) Interestingly, if your sorting key uses the entire value stored at a node (so that nodes containing the same key have no other extra information to distinguish them), there can be performance gains from adding a count to each node, rather than allowing duplicate nodes.
The main benefit is that adding or removing a duplicate will simply modify the count rather than inserting or deleting a new node (an action that may require re-balancing the tree).
So, to add an item, you first check if it already exists. If so, just increment the count and exit. If not, you need to insert a new node with a count of one then rebalance.
To remove an item, you find it then decrement the count - only if the resultant count is zero do you then remove the actual node from the tree and rebalance.
Searches are also quicker given there are fewer nodes but that may not be a large impact.
For example, the following two trees (non-counting on the left, and counting on the right) would be equivalent (in the counting tree, i.c
means c
copies of item i
):
__14__ ___22.2___
/ \ / \
14 22 7.1 29.1
/ \ / \ / \ / \
1 14 22 29 1.1 14.3 28.1 30.1
\ / \
7 28 30
Removing the leaf-node 22
from the left tree would involve rebalancing (since it now has a height differential of two) the resulting 22-29-28-30
subtree such as below (this is one option, there are others that also satisfy the "height differential must be zero or one" rule):
\ \
22 29
\ / \
29 --> 28 30
/ \ /
28 30 22
Doing the same operation on the right tree is a simple modification of the root node from 22.2
to 22.1
(with no rebalancing required).
This thing worked for me pretty well:
<div id="{{ 'object-' + $index }}"></div>
There is also a difference in indexing.
interface MyInterface {
foobar: string;
}
type MyType = {
foobar: string;
}
const exampleInterface: MyInterface = { foobar: 'hello world' };
const exampleType: MyType = { foobar: 'hello world' };
let record: Record<string, string> = {};
record = exampleType; // Compiles
record = exampleInterface; // Index signature is missing
So please consider this example, if you want to index your object
Take a look on this question
I had this exact same problem. Except my solution was to add an "s" to the binding value.
Old: binding="mexHttpBinding"
New: binding="mexHttpsBinding"
web.config snippet:
<services>
<service behaviorConfiguration="ServiceBehavior" name="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService">
<endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding"
contract="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService" />
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</service>
This will also happen anytime a div ends up positioned over controls in another div; like using bootstrap for layout, and having a "col-lg-4" followed by a "col-lg=8" misspelling... the right orphaned/misnamed div covers the left, and captures the mouse events. Easy to blow by that misspelling, - and = next to each other on keyboard. So, pays to examine with inspector and look for 'surprises' to uncover these wild divs.
Is there an unseen window covering the controls and blocking events, and how can that happen? Turns out, fatfingering = for - with bootstrap classnames is one way...
for Laravel 5.6+ users, you can just do
$posts = Post::whereDate('created_at', Carbon::today())->get();
Happy coding
var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;
So i have been struggling too on the same issue. The quick and easiest way to solve the problem is by just adding
modal-lg
on your modal DivExample <div class="modal-dialog modal-lg">
I figured out a way to telnet to a server and change a file permission. Then FTP the file back to your computer and open it. Hopefully this will answer your questions and also help FTP.
The filepath variable is setup so you always login and cd to the same directory. You can change it to a prompt so the user can enter it manually.
:: This will telnet to the server, change the permissions,
:: download the file, and then open it from your PC.
:: Add your username, password, servername, and file path to the file.
:: I have not tested the server name with an IP address.
:: Note - telnetcmd.dat and ftpcmd.dat are temp files used to hold commands
@echo off
SET username=
SET password=
SET servername=
SET filepath=
set /p id="Enter the file name: " %=%
echo user %username%> telnetcmd.dat
echo %password%>> telnetcmd.dat
echo cd %filepath%>> telnetcmd.dat
echo SITE chmod 777 %id%>> telnetcmd.dat
echo exit>> telnetcmd.dat
telnet %servername% < telnetcmd.dat
echo user %username%> ftpcmd.dat
echo %password%>> ftpcmd.dat
echo cd %filepath%>> ftpcmd.dat
echo get %id%>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat %servername%
del ftpcmd.dat
del telnetcmd.dat
You can try this logic because it is worked for me.
frag_profile profile_fragment = new frag_profile();
boolean flag = false;
@SuppressLint("ResourceType")
public void profile_Frag(){
if (flag == false) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
manager.getBackStackEntryCount();
transaction.setCustomAnimations(R.anim.transition_anim0, R.anim.transition_anim1);
transaction.replace(R.id.parentPanel, profile_fragment, "FirstFragment");
transaction.commit();
flag = true;
}
}
@Override
public void onBackPressed() {
if (flag == true) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
manager.getBackStackEntryCount();
transaction.remove(profile_fragment);
transaction.commit();
flag = false;
}
else super.onBackPressed();
}
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
Say you want to access the scope of the element like
<div ng-controller="hw"></div>
You could use the following in the console:
angular.element(document.querySelector('[ng-controller=hw]')).scope();
This will give you the scope at that element.
There is something very important about this thread that has been touched on but not fully explained. The HTML approach (adding a meta tag in the head) only works consistently on raw HTML or very basic server pages. My site is a very complex server-driven site with master pages, themeing and a lot of third party controls, etc. What I found was that some of these controls were programmatically adding their own tags to the final HTML which were being pushed to the browser at the beginning of the head tag. This effectively rendered the HTML meta tags useless.
Well, if you can't beat them, join them. The only solution that worked for me is to do exactly the same thing in the pre-render event of my master pages as such:
Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim MetaTag As HtmlMeta = New HtmlMeta()
MetaTag.Attributes("http-equiv") = "Content-Type"
MetaTag.Attributes("content") = "text/html; charset=utf-8;"
Page.Header.Controls.AddAt(0, MetaTag)
MetaTag = New HtmlMeta()
MetaTag.Attributes("http-equiv") = "X-UA-Compatible"
MetaTag.Attributes("content") = "IE=9,chrome=1"
Page.Header.Controls.AddAt(0, MetaTag)
End Sub
This is VB.NET but the same approach would work for any server-side technology. As long as you make sure it's the last thing that gets done right before the page is rendered.
This is a favorite interview question. With this questions, the interviewer tries to find out how well you understand the behavior of objects with respect to constructors, methods, class variables (static variables) and instance variables.
import java.util.ArrayList;
import java.util.List;
class Test {
private final List foo;
public Test() {
foo = new ArrayList();
foo.add("foo"); // Modification-1
}
public void setFoo(List foo) {
//this.foo = foo; Results in compile time error.
}
}
In the above case, we have defined a constructor for 'Test' and gave it a 'setFoo' method.
About constructor: Constructor can be invoked only one time per object creation by using the new
keyword. You cannot invoke constructor multiple times, because constructor are not designed to do so.
About method: A method can be invoked as many times as you want (Even never) and the compiler knows it.
Scenario 1
private final List foo; // 1
foo
is an instance variable. When we create Test
class object then the instance variable foo
, will be copied inside the object of Test
class. If we assign foo
inside the constructor, then the compiler knows that the constructor will be invoked only once, so there is no problem assigning it inside the constructor.
If we assign foo
inside a method, the compiler knows that a method can be called multiple times, which means the value will have to be changed multiple times, which is not allowed for a final
variable. So the compiler decides constructor is good choice! You can assign a value to a final variable only one time.
Scenario 2
private static final List foo = new ArrayList();
foo
is now a static variable. When we create an instance of Test
class, foo
will not be copied to the object because foo
is static. Now foo
is not an independent property of each object. This is a property of Test
class. But foo
can be seen by multiple objects and if every object which is created by using the new
keyword which will ultimately invoke the Test
constructor which changes the value at the time of multiple object creation (Remember static foo
is not copied in every object, but is shared between multiple objects.)
Scenario 3
t.foo.add("bar"); // Modification-2
Above Modification-2
is from your question. In the above case, you are not changing the first referenced object, but you are adding content inside foo
which is allowed. Compiler complains if you try to assign a new ArrayList()
to the foo
reference variable.
Rule If you have initialized a final
variable, then you cannot change it to refer to a different object. (In this case ArrayList
)
final classes cannot be subclassed
final methods cannot be overridden. (This method is in superclass)
final methods can override. (Read this in grammatical way. This method is in a subclass)
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019
(depending on the current date)
chandan@cmaster:~/More$ javac New.java
chandan@cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error
So if you by mistake after compiling again use javac
for running a program.
@Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records
$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
it gives records having date form 2015-10-16 to less than 2015-10-23. If value of recur_at is 2015-10-23 00:00:00 then only it shows that record else if it is 2015-10-23 12:00:45 then it is not shown.
#!/bin/bash
ping_count="4"
avg_max_limit="1500"
router="sagemcom-fast-2804-v2"
adress="192.168.1.1"
user="admin"
pass="admin"
VAR=$(
expect -c "
set timeout 3
spawn telnet "$adress"
expect \"Login:\"
send \"$user\n\"
expect \"Password:\"
send \"$pass\n\"
expect \"commands.\"
send \"ping ya.ru -c $ping_count\n\"
set timeout 9
expect \"transmitted\"
send \"exit\"
")
count_ping=$(echo "$VAR" | grep packets | cut -c 1)
avg_ms=$(echo "$VAR" | grep round-trip | cut -d '/' -f 4 | cut -d '.' -f 1)
echo "1_____ping___$count_ping|||____$avg_ms"
echo "$VAR"
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
I found this question while Googling. Note that if you just want to make use of the URI's content via something like a string, consider using Apache's IOUtils.toString()
method.
For example, a sample line of code could be:
String pageContent = IOUtils.toString("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de", Charset.UTF_8);
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
Another solution is to create a normal class which implements PropertyChanger like this
public class ViewProps : PropertyChanger
{
private string _MyValue = string.Empty;
public string MyValue
{
get {
return _MyValue
}
set
{
if (_MyValue == value)
{
return;
}
SetProperty(ref _MyValue, value);
}
}
}
Then create a static instance of the class somewhere you wont
public class MyClass
{
private static ViewProps _ViewProps = null;
public static ViewProps ViewProps
{
get
{
if (_ViewProps == null)
{
_ViewProps = new ViewProps();
}
return _ViewProps;
}
}
}
And now use it as static property
<TextBlock Text="{x:Bind local:MyClass.ViewProps.MyValue, Mode=OneWay}" />
And here is PropertyChanger implementation if necessary
public abstract class PropertyChanger : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Here's another sample using JQuery 1.10.2
$(".chkcc9").on('click', function() {
$(this)
.parents('table')
.find('.group1')
.prop('checked', $(this).is(':checked'));
});
You can use // instead of single /. That converts to int
directly.
If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.
#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent
#firewall-cmd --reload
And check the Port opened or not after reloading the firewall.
#firewall-cmd --list-port
For other configuration [Linuxwindo.com][1]
Library Seaborn has this built in with function .despine()
.
Just add:
import seaborn as sns
Now create your graph. And add at the end:
sns.despine()
If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:
sns.despine(top=True, right=True, left=False, bottom=False)
Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html
Use the rand
function:
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Quote:
A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
I use this command for simple rotate a file:
mv output.log `date +%F`-output.log
In local folder I have 2019-09-25-output.log
For generating the publish output provide one more parameter. msbuild example.sln /p:publishprofile=profilename /p:deployonbuild=true /p:configuration=debug/or any
You have to use:
abs() for int
fabs() for double
fabsf() for float
Above function will also work but you can also try something like this.
if(a<0)
{
a=-a;
}
It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:
The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.
There are two events on client side as given below.
1. window.onbeforeunload (calls on Browser/tab Close & Page Load)
2. window.onload (calls on Page Load)
On server Side
public JsonResult TestAjax( string IsRefresh)
{
JsonResult result = new JsonResult();
return result = Json("Called", JsonRequestBehavior.AllowGet);
}
On Client Side
<script type="text/javascript">_x000D_
window.onbeforeunload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: { IsRefresh: 'Close' }_x000D_
});_x000D_
};_x000D_
_x000D_
window.onload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: {IsRefresh:'Load'}_x000D_
});_x000D_
};_x000D_
</script>
_x000D_
On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".
On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.
Here you go: Here you go: Create a System Restore Point. Log on under an admin account. Delete the folder C:\SomeUser. Move the folder c:\Users\SomeUser so that it becomes c:\SomeUser. Open the registry editor. Navigate to HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList. Search for "ProfileImagePath" until you find the one that points at c:\Users\SomeUser. Modify it so that it points at c:\SomeUser. Use System Restore in case things go wrong.
I found it useful to wrap this function as a jQuery plugin:
$.fn.selectText = function () {
return $(this).each(function (index, el) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(el);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(el);
window.getSelection().addRange(range);
}
});
}
So, it becomes a reusable solution. Then you can do this:
<div onclick="$(this).selectText()">http://example.com/page.htm</div>
And it will selected test in the div.
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
If treating strings as bytes is more your thing, you can use the following functions
function u_atob(ascii) {
return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));
}
function u_btoa(buffer) {
var binary = [];
var bytes = new Uint8Array(buffer);
for (var i = 0, il = bytes.byteLength; i < il; i++) {
binary.push(String.fromCharCode(bytes[i]));
}
return btoa(binary.join(''));
}
// example, it works also with astral plane characters such as ''
var encodedString = new TextEncoder().encode('?');
var base64String = u_btoa(encodedString);
console.log('?' === new TextDecoder().decode(u_atob(base64String)))
Made it into a function. You can now call splitCsv <Filename> [chunkSize]
splitCsv() {
HEADER=$(head -1 $1)
if [ -n "$2" ]; then
CHUNK=$2
else
CHUNK=1000
fi
tail -n +2 $1 | split -l $CHUNK - $1_split_
for i in $1_split_*; do
sed -i -e "1i$HEADER" "$i"
done
}
Found on: http://edmondscommerce.github.io/linux/linux-split-file-eg-csv-and-keep-header-row.html
No.
What if there is no default action, context matters. What if you only care to act on a few values?
Take the example of reading keypresses for a game
switch(a)
{
case 'w':
// Move Up
break;
case 's':
// Move Down
break;
case 'a':
// Move Left
break;
case 'd':
// Move Right
break;
}
Adding:
default: // Do nothing
Is just a waste of time and increases the complexity of the code for no reason.
Download and install Fiddler
Open Fiddler and go to Rule menu to tick Automatically authenticate
Now open visual studio and click on sign-in button.
Enter your email and password.
Hopefully it will work
You should prefer generic types over arrays. As mentioned by others, arrays are inflexible and do not have the expressive power of generic types. (They do however support runtime typechecking, but that mixes badly with generic types.)
But, as always, when optimizing you should always follow these steps:
background:url(bgimage.jpg) no-repeat; background-size: cover;
This did the trick
No need to use any CSS or JQuery. You can do it right from the HTML input tag.
For example, In below email box, the placeholder text will disappear after clicking inside and the text will appear again if clicked outside.
<input type="email" placeholder="Type your email here..." onfocus="this.placeholder=''" onblur="this.placeholder='Type your email here...'">
Another option is to use a ToggleButton with null background and a custom button.
Bellow an example that includes a selector to the text color as well.
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/toggle_selector"
android:background="@null"
android:paddingLeft="10dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="@drawable/toggle_text"
android:textOn="My on state"
android:textOff="My off state" />
toggle_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/state_on" />
<item
android:drawable="@drawable/state_off" />
</selector>
toggle_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:color="@color/app_color" />
<item
android:color="@android:color/darker_gray" />
</selector>
If i say without loop, i can use GOTO
statement for delete large amount of records using sql server.
exa.
IsRepeat:
DELETE TOP (10000)
FROM <TableName>
IF @@ROWCOUNT > 0
GOTO IsRepeat
like this way you can delete large amount of data with smaller size of delete.
let me know if requires more information.
I had similar problem - I want to replace picture on :hover but can't use BACKGRUND-IMAGE due to lack of Bootstrap's adaptive design.
If you like me only want to change the picture on :hover (but not insist of change SRC for the certain image tag) you can do something like this - it's CSS-only solution.
HTML:
<li>
<img src="/picts/doctors/SmallGray/Zharkova_smallgrey.jpg">
<img class="hoverPhoto" src="/picts/doctors/Small/Zharkova_small.jpg">
</li>
CSS:
li { position: relative; overflow: hidden; }
li img.hoverPhoto {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
opacity: 0;
}
li.hover img { /* it's optional - for nicer transition effect */
opacity: 0;
-web-kit-transition: opacity 1s ease;
-moz-transition: opacity 1s ease;li
-o-transition: opacity 1s ease;
transition: opacity 1s ease;
}
li.hover img.hoverPhoto { opacity: 1; }
If you want IE7-compatible code you may hide/show :HOVER image by positioning not by opacity.
var name = document.getElementById('login_name').value;
if ( name.length < 4 && name.length > 30 )
{
alert ( 'Name length is mismatch ' ) ;
}
var pattern = new RegExp("^[a-z\.0-9 ]+$");
var return_value = var pattern.exec(name);
if ( return_value == null )
{
alert ( "Please give valid Name");
return false;
}
A more modern solution:
Using display: flex
and flex-direction: row
form {_x000D_
display: flex; /* 2. display flex to the rescue */_x000D_
flex-direction: row;_x000D_
}_x000D_
_x000D_
label, input {_x000D_
display: block; /* 1. oh noes, my inputs are styled as block... */_x000D_
}
_x000D_
<form>_x000D_
<label for="name">Name</label>_x000D_
<input type="text" id="name" />_x000D_
<label for="address">Address</label>_x000D_
<input type="text" id="address" />_x000D_
<button type="submit">_x000D_
Submit_x000D_
</button>_x000D_
</form>
_x000D_
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
This is what is actually happening:
global_list = []
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to global_list
useTheList(global_list)
main()
This is what you want:
def defineAList():
local_list = ['1','2','3']
print "For checking purposes: in defineAList, list is", local_list
return local_list
def useTheList(passed_list):
print "For checking purposes: in useTheList, list is", passed_list
def main():
# returned list is ignored
returned_list = defineAList()
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(returned_list)
main()
You can even skip the temporary returned_list
and pass the returned value directly to useTheList
:
def main():
# passed_list inside useTheList is set to what is returned from defineAList
useTheList(defineAList())
awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103
It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:
Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();
I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:
<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>
Lumia phones give wrong screen.width (at least on emulator).
So maybe Math.min(window.innerWidth || Infinity, screen.width)
will work on all devices?
Or something crazier:
for (var i = 100; !window.matchMedia('(max-device-width: ' + i + 'px)').matches; i++) {}
var deviceWidth = i;
I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.
Then i use COM Dataport Emulator to recieve from COM4.
Then i open COM3 with the app im developping (c#) and send data to COM3.
The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).
So with this 2 great programs i managed to emulate Serial RS-232 comunication.
Hope it helps.
Both programs are free!!!!!
don't have to chain so many tools. Just one awk command does the job
COMPANY_NAME=$(awk -F"=" '/company_name/{gsub(/;$/,"",$2) ;print $2}' file.txt)
dos2unix is a commandline utility that will do this, or :%s/^M//g
will if you use Ctrl-v Ctrl-m to input the ^M, or you can :set ff=unix
and Vim will do it for you.
There is documentation on the fileformat setting, and the Vim wiki has a comprehensive page on line ending conversions.
Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do :set ff=dos
, so Vim will know it's a DOS file and use DOS conventions for line endings.
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
Found a good code with comments explaining each statement. Code found at - accessallinone
Sub DAOLooping()
On Error GoTo ErrorHandler
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)
Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!!
'In English, this means that we have opened up a recordset
'and can access its values using the rs variable.
With rs
If Not .BOF And Not .EOF Then
'We don’t know if the recordset has any records,
'so we use this line of code to check. If there are no records
'we won’t execute any code in the if..end if statement.
.MoveLast
.MoveFirst
'It is not necessary to move to the last record and then back
'to the first one but it is good practice to do so.
While (Not .EOF)
'With this code, we are using a while loop to loop
'through the records. If we reach the end of the recordset, .EOF
'will return true and we will exit the while loop.
Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
'prints info from fields to the immediate window
.MoveNext
'We need to ensure that we use .MoveNext,
'otherwise we will be stuck in a loop forever…
'(or at least until you press CTRL+Break)
Wend
End If
.close
'Make sure you close the recordset...
End With
ExitSub:
Set rs = Nothing
'..and set it to nothing
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.
These properties let us know when we have reached the limits of a recordset.
This discussion has been for a while and @Alexander T.'s answer provided a good guide to follow for newer of React like me. And I'm gonna share some additional know-hows about calling the same API multiple times to refresh the component, I think it's probably a common problem that newbie may face at the beginning.
componentWillReceiveProps(nextProps)
, from official documentation :
If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
We could conclude that here is the place we handle props from the parent component, have API calls, and update state.
Base on @Alexander T.'s example:
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {person: []};
}
componentDidMount() {
//For our first load.
this.UserList(this.props.group); //maybe something like "groupOne"
}
componentWillReceiveProps(nextProps) {
// Assuming parameter comes from url.
// let group = window.location.toString().split("/")[*indexParameterLocated*];
// this.UserList(group);
// Assuming parameter comes from props that from parent component.
let group = nextProps.group; // Maybe something like "groupTwo"
this.UserList(group);
}
UserList(group) {
$.getJSON('https://randomuser.me/api/' + group)
.then(({ results }) => this.setState({ person: results }));
}
render() {
return (...)
}
}
componentWillReceiveProps()
would be deprecated.
Here are only some methods (all of them in Doc) in the life cycle which I think would be related to deploying API in general case:
By referring the diagram above:
Deploy API in componentDidMount()
The proper scenario to have API call here is that the content (from the response of API) of this component will be static, componentDidMount()
only fire once while the component is mounting, even new props are passed from parent component or have actions to lead re-rendering
.
The component do check difference to re-render but not re-mount.
Quote from doc:
If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
static getDerivedStateFromProps(nextProps, prevState)
We should notice that there are two kinds of component updating, setState()
in current component would not lead this method to trigger, but re-rendering or new props from parent component do.
We could found out that this method also fires while mounting.
This is a proper place to deploy API if we want to use the current component like a template, and the new parameters for API are props coming from parent component.
We receive a different response from API and return a new state
here to change the content of this component.
For example:
We have a dropdown list for different Cars in the parent component, this component needs to show the details of the selected one.
componentDidUpdate(prevProps, prevState)
Differ from static getDerivedStateFromProps()
, this method is invoked immediately after every rendering except the initial rendering. We could have API calling and render difference in one component.
Extend the previous example:
The component to show Car's details may contain a list of series of this car, if we want to check the 2013 production one, we may click or select or ... the list item to lead a first setState()
to reflect this behavior (such as highlighting the list item) in this component, and in the following componentDidUpdate()
we send our request with new parameters (state). After getting the response, we setState()
again for rendering the different content of the Car details. To prevent the following componentDidUpdate()
from causing the infinity loop, we need to compare the state by utilizing prevState
at the beginning of this method to decide if we send the API and render the new content.
This method really could be utilized just like static getDerivedStateFromProps()
with props, but need to handle the changes of props
by utilizing prevProps
. And we need to cooperate with componentDidMount()
to handle the initial API call.
Quote from doc:
... This is also a good place to do network requests as long as you compare the current props to previous props ...
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
Alex, try this: svn merge [WorkingFolderPath] -r 1944:1943
Do not create separate lists; create a list of lists:
results = []
with open('inputfile.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split(','))
or better still, use the csv
module:
import csv
results = []
with open('inputfile.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
results.append(row)
Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.
Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append()
just process that line right there.
Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:
import csv
with open('inputfile.txt', newline='') as inputfile:
results = list(csv.reader(inputfile))
I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain
The spread
Syntax
You can use the spread syntax, an Array Initializer introduced in ECMAScript 2015 (ES6) standard:
var arr = [...str];
Examples
function a() {_x000D_
return arguments;_x000D_
}_x000D_
_x000D_
var str = 'Hello World';_x000D_
_x000D_
var arr1 = [...str],_x000D_
arr2 = [...'Hello World'],_x000D_
arr3 = new Array(...str),_x000D_
arr4 = a(...str);_x000D_
_x000D_
console.log(arr1, arr2, arr3, arr4);
_x000D_
The first three result in:
["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
The last one results in
{0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "W", 7: "o", 8: "r", 9: "l", 10: "d"}
Browser Support
Check the ECMAScript ES6 compatibility table.
Further reading
spread
is also referenced as "splat
" (e.g. in PHP or Ruby or as "scatter
" (e.g. in Python).
Demo
I know there should be a proper way to solve it but just to save time
I uploaded my xlsx sheet to Google Sheets and then again downloaded it from Google Sheets it working now
If you don't have time to solve the problem, you can try this
The fundamental issue with your code is that you mix two APIs. Unfortunately online resources are not great at pointing this out, but there are two semaphore APIs on UNIX-like systems:
Looking at the code above you used semget() from the System V API and tried to post through sem_post() which comes from the POSIX API. It is not possible to mix them.
To decide which semaphore API you want you don't have so many great resources. The simple best is the "Unix Network Programming" by Stevens. The section that you probably interested in is in Vol #2.
These two APIs are surprisingly different. Both support the textbook style semaphores but there are a few good and bad points in the System V API worth mentioning:
You can use ISNULL(....)
SET @Concatenated = ISNULL(@Column1, '') + ISNULL(@Column2, '')
If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.
Why not something like this?
It uses a combination of lists, iteration, and interpolation.
@mixin placeholder ($rules) {
@each $rule in $rules {
::-webkit-input-placeholder,
:-moz-placeholder,
::-moz-placeholder,
:-ms-input-placeholder {
#{nth($rule, 1)}: #{nth($rule, 2)};
}
}
}
$rules: (('border', '1px solid red'),
('color', 'green'));
@include placeholder( $rules );
I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model
def update_state(chat_id, state):
try:
value = Users.query.filter(Users.chat_id == str(chat_id)).first()
value.state = str(state)
db.session.flush()
db.session.commit()
#db.session.close()
except:
print('Error in def update_state')
Why use db.session.flush()
? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?
You should check out this site. The TO_TIMESTAMP section could be useful for you!
Syntax:
TO_TIMESTAMP ( string , [ format_mask ] [ 'nlsparam' ] )
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector()
and .querySelectorAll()
.
Assuming you are trying to find if a div exists
$('div').length ? alert('div found') : alert('Div not found')
From the documentation for sys.exit
:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
One example where exit codes are used are in shell scripts. In Bash you can check the special variable $?
for the last exit status:
me@mini:~$ python -c ""; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(0)"; echo $?
0
me@mini:~$ python -c "import sys; sys.exit(43)"; echo $?
43
Personally I try to use the exit codes I find in /usr/include/asm-generic/errno.h
(on a Linux system), but I don't know if this is the right thing to do.
Typically you need to do 5 things to include a library in your project:
1) Add #include statements necessary files with declarations/interfaces, e.g.:
#include "library.h"
2) Add an include directory for the compiler to look into
-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)
3) Add a library directory for *.lib files:
-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)
4) Link the lib's *.lib files
-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;
5) Place *.dll files either:
-> in the directory you'll be opening your final executable from or into Windows/system32
In most cases you have to initialize the array,
let list: number[] = [];
(http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png)
worked really well for me.
This will match URLs in the following forms:
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif
https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png
https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png
https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png
Check this regular expression against the URLs here: http://regexr.com/3g1v7
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
As King King said, you must add the browser specific prefix. This should cover most browsers:
@keyframes flickerAnimation {_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
-webkit-animation: flickerAnimation 1s infinite;_x000D_
-moz-animation: flickerAnimation 1s infinite;_x000D_
-o-animation: flickerAnimation 1s infinite;_x000D_
animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
How do I edit my global Git configuration?
Short answer: git config --edit --global
To understand Git configuration, you should know that:
Git configuration variables can be stored at three different levels. Each level overrides values at the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user).
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How do I view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow do I read one particular configuration?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
The only solution that worked for me and $.each
was definitely causing the error. so i used for loop
and it's not throwing error anymore.
Example code
$.ajax({
type: 'GET',
url: 'https://example.com/api',
data: { get_param: 'value' },
success: function (data) {
for (var i = 0; i < data.length; ++i) {
console.log(data[i].NameGerman);
}
}
});
Type "gg" in command mode. This brings the cursor to the first line.
I've already encountered this error and this is the best solution I've found:
In your root folder (probably called public_html)please add this code to your .htaccess file...
REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999
#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
In your wp-admin folder please add this code to your .htaccess file...
#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running
Execute the below code if you want to update all record in all columns:
update config set column1='value',column2='value'...columnN='value';
and if you want to update all columns of a particular row then execute below code:
update config set column1='value',column2='value'...columnN='value' where column1='value'
One better check that can be done if you get such error while accessing a file is to use the file.exists("file_path/file_name")
function. This function will return TRUE
if the file is existing and accessible, else False
.
One of the things you need to understand, before you try to understand Apache Camel, are Enterprise Integration Patterns. Not everyone in the field is actually aware of them. While you can certainly read the Enterprise Integration Patterns book, a quicker way to get up to speed on them would be to read something like the Wikipedia article on Enterprise Application Integration.
One you have read and understood the subject area, you would be much more likely to understand the purpose of Apache Camel
HTH
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important
directive! But sometimes it's the only way to override the inline style
attribute. So it's a best practice trying to avoid both.
Working off of Matt's solution, I used the following Compass/SCSS implementation.
@for $i from 1 through 20 {
li:first-child:nth-last-child( #{$i} ),
li:first-child:nth-last-child( #{$i} ) ~ li {
width: calc(100% / #{$i} - 10px);
}
}
This allows you to quickly expand the number of items.
The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE
statements, and I don't think there is a better way.
If you are going to make heavy use of this, you could consider writing your own function:
CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
CREATE FUNCTION multiple_replace(
in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
RETURN VARCHAR2
AS
v_result VARCHAR2(32767);
BEGIN
IF( in_old.COUNT <> in_new.COUNT ) THEN
RETURN in_text;
END IF;
v_result := in_text;
FOR i IN 1 .. in_old.COUNT LOOP
v_result := REPLACE( v_result, in_old(i), in_new(i) );
END LOOP;
RETURN v_result;
END;
and then use it like this:
SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
NEW t_text( 'text', 'tokens', 'replace' )
)
FROM dual
This is text with some tokens to replace
If all of your tokens have the same format ('#VAL' || i || '#'
), you could omit parameter in_old
and use your loop-counter instead.
check java version in pom.xml and jre version in Eclipse->Window->Preferences->Installed JREs. In my case pom.xml has different version(it had 1.8 while eclipse using 1.7). Fixing the version in pom.xml to 1.7 worked.
I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :
$input = "ažškunrukiš ? àéò ??? ©€ ?? ? ?? ? R?";
echo htmlentities($input, ENT_HTML5 , 'UTF-8');
result :
āžšķūņrūķīš ○ àéò ∀∂∋ ©€ ♣♦ ↠ ↔↛ ↙ ℜ℞rx;
If you came across this error while using the command line its because you must be using php 7 to execute whatever it is you are trying to execute. What happened is that the code is trying to use an operator thats only available in php7+ and is causing a syntax error.
If you already have php 7+ on your computer try pointing the command line to the higher version of php you want to use.
export PATH=/usr/local/[php-7-folder]/bin/:$PATH
Here is the exact location that worked based off of my setup for reference:
export PATH=/usr/local/php5-7.1.4-20170506-100436/bin/:$PATH
The operator thats actually caused the break is the "null coalesce operator" you can read more about it here:
string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
dest = source.Substring(0, source.Length - 1);
}
We faced the same issue and changed commandname=""
to modelAttribute=""
in jsp page to solve this issue.
You should have access to the POST dictionary on the request object.
Just try below a simple solution:
JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);
whenever my JSON request is like:
{
"role": "RT",
"orders": [
{
"order_id": "ORDER201908aPq9Gs",
"cart_id": 164444,
"affiliate_id": 0,
"orm_order_status": 9,
"status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
"status_date": "2020-04-15",
}
]
}
And version which uses commons-collections
CollectionUtils.getCardinalityMap
method:
final List<Integer> values = Arrays.asList(1, 1, 2, 3, 3, 3);
final Map<Integer, Integer> cardinalityMap = CollectionUtils.getCardinalityMap(values);
System.out.println(cardinalityMap
.entrySet()
.stream().filter(e -> e.getValue() > 1)
.map(e -> e.getKey())
.collect(Collectors.toList()));
```
In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.
My best advise when having the error is to use [] braquets to sorround table names, the abbreviation of tables causes sometimes errors, (sometime table abbreviations just work fine...weird)
adjustcolor("blanchedalmond",alpha.f = 0.3)
The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").
Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D
." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")
By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!
Why PendingIntent is required ? I was thinking like
Intent
orIntent
for the same purpose.E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
If I send bluetoothIntent
to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN
, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent)
.
The limitation is overcome using PendingIntent
. With PendingIntent
the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN
for enabling Bluetooth. Source.
In my case, this error occurred because of windows 7 shortcuts. In windows we create shortcuts on desktop by using right click > send to > desktop. In my pc, there is no option for desktop, but there is one for "documents". I created the shortcuts there and then moved them to the desktop. Executing these shortcuts causes the error. Eclipse works fine when I run it directly from the folder where it is installed. I fixed it by using right click > create shortcut and then moving this shortcut to the desktop.
As you are using Python 3, the module has been renamed to tkinter
, as stated in the documentation:
Note Tkinter has been renamed to tkinter in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
Ok...Ok... Don't worry i am also ruined by this error and fatal and when i got it i was so serious even i was not giving an attention to other work, but i got it, Simply first of all copy this code and paste in your system variable Under path ...
C:\Program Files;C:\Winnt;C:\Winnt\System32;C:\Program Files\Java\jre6\bin\javaw.exe
Now copy the "jre" folder from your path like i have have "jre" under this path
C:\Program Files\Java
and paste it in your eclipse folder means where your eclipse.exe file is placed. like i have my eclipse set up in this location
F:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse
So inside the eclipse Folder paste the "jre" FOLDER . If you have "jre6" then rename it as "jre"....and run your eclipse you will got the solution...
//<<<<<<<<<<<<<<----------------------------->>>>>>>>>>>>>>>>>>>
OTHER SOLUTION: 2
If the problem could't solve with the above steps, then follow these steps
-vmF:\Softwares\LANGUAGES SOFTEARE\Android Setup\eclipse Indigo version 32 Bit\jre\bin/javaw.exe
Now this time when you will start eclipse it will search for javaw.exe, so it will search the path in the eclipse.ini, as it is now in the same folder so, it will start the javaw.exe and it will start working.
If You still have any query you can ask it again, just go on my profile and find out my email id. because i love stack overflow forum, and it made me a programmer.*
Be very, very aware of this problem that can occur when using utf8_general_ci
.
MySQL will not distinguish between some characters in select statements, if the utf8_general_ci
collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.
This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.
I'm no DBA, but to avoid this problem, I always go with utf8-bin
instead of a case-insensitive one.
The script below describes the problem by example.
-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;
-- next, make sure that your client connection is of the same
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci
-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');
-- (verify)
SELECT * FROM `test`;
-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';
--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are
-- case insensitive (ending with _ci) do not distinguish between
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--
-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to
-- do the same with the 'latin1' charset:
--
-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci
-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Again, only one key is returned (expected). This shows
-- that the problem with utf8/utf8_generic_ci isn't present
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:
-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same
-- way (for any sceptics out there):
-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Two keys.
--
DROP DATABASE sandbox;
The math.log
function is to the base e
, i.e. natural logarithm. If you want to the base 10 use math.log10
.
to @primpop answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>
-i
says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak
.
Assertj is good at this.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(myClass.getMyItems()).extracting("name").contains("foo", "bar");
Big plus for assertj compared to hamcrest is easy use of code completion.
I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.
I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).
Function ConvertToLetter2(iCol As Integer) As String
Dim First As Integer
Dim Second As Integer
Dim FirstChar As String
Dim SecondChar As String
First = Int(iCol / 26)
If First = iCol / 26 Then
First = First - 1
End If
If First = 0 Then
FirstChar = ""
Else
FirstChar = Chr(First + 64)
End If
Second = iCol Mod 26
If Second = 0 Then
SecondChar = Chr(26 + 64)
Else
SecondChar = Chr(Second + 64)
End If
ConvertToLetter2 = FirstChar & SecondChar
End Function
After I set core.autocrlf=true
I was getting "LF will be replaced by CRLF" (note not "CRLF will be replaced by LF") when I was git add
ing (or perhaps it was it on git commit
?) edited files in windows on a repository (that does use LF) that was checked out before I set core.autocrlf=true
.
I made a new checkout with core.autocrlf=true
and now I'm not getting those messages.
I use the code to increase the default limit globally:
require('events').EventEmitter.prototype._maxListeners = 100;
Style the row-element with css:
border-bottom: 1px solid black;
var timeout_check_change_class;
function check_change_class( selector )
{
$(selector).each(function(index, el) {
var data_old_class = $(el).attr('data-old-class');
if (typeof data_old_class !== typeof undefined && data_old_class !== false)
{
if( data_old_class != $(el).attr('class') )
{
$(el).trigger('change_class');
}
}
$(el).attr('data-old-class', $(el).attr('class') );
});
clearTimeout( timeout_check_change_class );
timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );
$('.breakpoint').on('change_class', function(event) {
console.log('haschange');
});
See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
To summarize: the way a directive accesses its parent ($parent
) scope depends on the type of scope the directive creates:
default (scope: false
) - the directive does not create a new scope, so there is no inheritance here. The directive's scope is the same scope as the parent/container. In the link function, use the first parameter (typically scope
).
scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. Properties that are defined on the parent scope are available to the directive scope
(because of prototypal inheritance). Just beware of writing to a primitive scope property -- that will create a new property on the directive scope (that hides/shadows the parent scope property of the same name).
scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit the parent scope. You can still access the parent scope using $parent
, but this is not normally recommended. Instead, you should specify which parent scope properties (and/or function) the directive needs via additional attributes on the same element where the directive is used, using the =
, @
, and &
notation.
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. If the directive also creates an isolate scope, the transcluded and the isolate scopes are siblings. The $parent
property of each scope references the same parent scope.
Angular v1.3 update: If the directive also creates an isolate scope, the transcluded scope is now a child of the isolate scope. The transcluded and isolate scopes are no longer siblings. The $parent
property of the transcluded scope now references the isolate scope.
The above link has examples and pictures of all 4 types.
You cannot access the scope in the directive's compile function (as mentioned here: https://github.com/angular/angular.js/wiki/Dev-Guide:-Understanding-Directives). You can access the directive's scope in the link function.
Watching:
For 1. and 2. above: normally you specify which parent property the directive needs via an attribute, then $watch it:
<div my-dir attr1="prop1"></div>
scope.$watch(attrs.attr1, function() { ... });
If you are watching an object property, you'll need to use $parse:
<div my-dir attr2="obj.prop2"></div>
var model = $parse(attrs.attr2);
scope.$watch(model, function() { ... });
For 3. above (isolate scope), watch the name you give the directive property using the @
or =
notation:
<div my-dir attr3="{{prop3}}" attr4="obj.prop4"></div>
scope: {
localName3: '@attr3',
attr4: '=' // here, using the same name as the attribute
},
link: function(scope, element, attrs) {
scope.$watch('localName3', function() { ... });
scope.$watch('attr4', function() { ... });
<uses-permission android:name="android.permission.INTERNET"/>
add this tag above into AndroidManifest.xml of your Android project
,and it will be ok.
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
Column values from the SELECT statement are assigned into @low
and @day
local variables; the @adjustedLow
value is not assigned into any variable and it causes the problem:
The problem is here:
select
top 1 @low = low
, @day = day
, @adjustedLow -- causes error!
--select high
from
securityquote sq
...
Detailed explanation and workaround: SQL Server Error Messages - Msg 141 - A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
First: monkey patching is an evil hack (in my opinion).
It is often used to replace a method on the module or class level with a custom implementation.
The most common usecase is adding a workaround for a bug in a module or class when you can't replace the original code. In this case you replace the "wrong" code through monkey patching with an implementation inside your own module/package.
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
BlockingQueue.java
public class BlockingQueue
{
int item;
boolean available = false;
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
} catch (InterruptedException e) {
}
}
item = value;
available = true;
notifyAll();
}
public synchronized int get()
{
while(available == false)
{
try
{
wait();
}
catch(InterruptedException e){
}
}
available = false;
notifyAll();
return item;
}
}
Consumer.java
package com.sukanya.producer_Consumer;
public class Consumer extends Thread
{
blockingQueue queue;
private int number;
Consumer(BlockingQueue queue,int number)
{
this.queue = queue;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = queue.get();
System.out.println("Consumer #" + this.number+ " got: " + value);
}
}
}
ProducerConsumer_Main.java
package com.sukanya.producer_Consumer;
public class ProducerConsumer_Main
{
public static void main(String args[])
{
BlockingQueue queue = new BlockingQueue();
Producer producer1 = new Producer(queue,1);
Consumer consumer1 = new Consumer(queue,1);
producer1.start();
consumer1.start();
}
}
My guess the compiler is complaining about an invalid annotation. I've noticed that Eclipse doesnt show all errors, like a comma at the end of an array in a annotation. But the standard javac
does.
Elizabeth Castro has an interesting article on this problem: Bye Bye Embed. Worth a read on how she attacked this problem, as well as handling QuickTime content.
I think you need to add some context to your question. However, basic information about these things can be found here:
window.opener
https://developer.mozilla.org/en-US/docs/Web/API/Window.opener
I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.
window.parent
https://developer.mozilla.org/en-US/docs/Web/API/Window.parent
I've used this mostly when working with IFrames that need to communicate with the window object that contains them.
window.top
https://developer.mozilla.org/en-US/docs/Web/API/Window.top
This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.
If you add some more detail to your question, I can supply other more relevant examples.
UPDATE:
There are a few ways you can handle your situation.
You have the following structure:
When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.
So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:
childwindow.appMainWindow = window.opener
After making the assignment above, close dialog 1.
Then from the code running inside dialog2, you should be able to use
window.appMainWindow
to reference the main window, window object.
Hope this helps.
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
Simply, you can use COLLATE NOCASE in your SELECT query:
SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE
Based on Tabare's Answer, I had to add one more day at the end, since the cycle is cut before
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
alert(start);
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}