I had same issue for windows , the cause of the problem was currupted or missing dll files. I had to change them.
In android studio ,
Help Menu -> Show log in explorer.
It opens log folder, where you can find all logs . In my situation error like "Emulator terminated with exit code -1073741515"
Go to folder ~\Android\Sdk\emulator
Run this command:
emulator.exe -netdelay none -netspeed full -avd <virtual device name>
ex: emulator.exe -netdelay none -netspeed full -avd Nexus_5X_API_26.avd
You can find this command from folder ~.android\avd\xxx.avd\emu-launch-params.txt
Search and download the appropriate vcruntime140.dll file for your system from the internet (32 / 64 bit version) , and replace it with the vcruntime140.dll file in the folder ~\Android\Sdk\emulator
Try step 1
If you get error about vcruntime140_1 , change the file name as vcruntime140_1.dll ,try step 1
If it runs , you can run it from Android Studio also.
for importing the image in flask you want a sub folder named static into the folder keep your img
and go into your html file and write
When I had this problem, I had literally just forgot to fill in a parameter value in the XAML of the code.
For some reason though, the exception would send me to the CS of the WPF program rather than the XAML. No idea why.
In addition to what @berguiga-mohamed-amine stated, I just found that a wildcard requires leaving the module argument the empty string:
compile ("com.github.jsonld-java:jsonld-java:$jsonldJavaVersion") {
exclude group: 'org.apache.httpcomponents', module: ''
exclude group: 'org.slf4j', module: ''
}
First of all you need to create a surface once and keep it somewhere handy. Example:
var surface = dojox.gfx.createSurface(domNode, widthInPx, heightInPx);
domNode
is usually an unadorned <div>
, which is used as a placeholder for a surface.
You can clear everything on the surface in one go (all existing shape objects will be invalidated, don't use them after that):
surface.clear();
All surface-related functions and methods can be found in the official documentation on dojox.gfx.Surface. Examples of use can be found in dojox/gfx/tests/
.
The solution given earlier leads to a situation where images may be too small for the carousel box. A proper solution to the problem of bumping controls is to override Bootstraps CSS.
Original code:
.carousel-control {
top: 40%;
}
Override the variable with a fixed value inside your own stylesheet (300px worked in my design):
.carousel-control {
top: 300px;
}
Hopefully this will solve your problem.
You can use:
SELECT SUBDATE(NOW(), 1);
or
SELECT SUBDATE(NOW(), INTERVAL 1 DAY);
or
SELECT NOW() - INTERVAL 1 DAY;
or
SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);
UPDATE: This is only true if you use ONLYOFFICE instead of MS Excel.
There is actually a flow in all answers provided here and also in the accepted one. The flow is that whenever you have an empty cell in excel and copy that, in the clipboard you have 2 tab chars next to each other, so after splitting you get one additional item in array, which then appears as an extra cell in that row and moves all other cells by one. So to avoid that you basically need to replace all double tab (tabs next to each other only) chars in a string with one tab char and only then split it.
An updated version of @userfuser's jsfiddle is here to fix that issue by filtering pasted data with removeExtraTabs
http://jsfiddle.net/sTX7y/794/
function removeExtraTabs(string) {
return string.replace(new RegExp("\t\t", 'g'), "\t");
}
function generateTable() {
var data = removeExtraTabs($('#pastein').val());
var rows = data.split("\n");
var table = $('<table />');
for (var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for (var x in cells) {
row.append('<td>' + cells[x] + '</td>');
}
table.append(row);
}
// Insert into DOM
$('#excel_table').html(table);
}
$(document).ready(function() {
$('#pastein').on('paste', function(event) {
$('#pastein').on('input', function() {
generateTable();
$('#pastein').off('input');
})
})
})
If you face this problem in Angular 6, you can fix it by adding the parameter scrollPositionRestoration: 'enabled'
to app-routing.module.ts 's RouterModule:
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'enabled'
})],
exports: [RouterModule]
})
I had this question twice, and it was always caused by the corruption of the git cache file at my local branch. I fixed it by writing the missing commit hash into that file. I got the right commit hash from the server and ran the following command locally:
cat .git/refs/remotes/origin/feature/mybranch \
echo 1edf9668426de67ab764af138a98342787dc87fe \
>> .git/refs/remotes/origin/feature/mybranch
An alternative solution is using an external table: http://www.orafaq.com/node/848
Use this when you have to do this import very often and very fast.
Consider John Doe a document rather than a collection
Give it a collection of things and thingsSharedWithOthers
Then you can map and query John Doe's shared things in that parallel thingsSharedWithOthers collection.
proprietary: "John Doe"(a document)
things(collection of John's things documents)
thingsSharedWithOthers(collection of John's things being shared with others):
[thingId]:
{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}
then set thingsSharedWithOthers
firebase.firestore()
.collection('thingsSharedWithOthers')
.set(
{ [thingId]:{ who: "[email protected]", when: new Date() } },
{ merge: true }
)
Make sure you are running from that folder of your application, where you have the package.json.
Each deployed webapp has a context.xml
file that lives in
$CATALINA_BASE/conf/[enginename]/[hostname]
(conf/Catalina/localhost by default)
and has the same name as the webapp (manager.xml
in this case). If no file is present, default values are used.
So, you need to create a file conf/Catalina/localhost/manager.xml
and specify the rule you want to allow remote access. For example, the following content of manager.xml
will allow access from all machines:
<Context privileged="true" antiResourceLocking="false"
docBase="${catalina.home}/webapps/manager">
<Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="^YOUR.IP.ADDRESS.HERE$" />
</Context>
Note that the allow attribute of the Valve
element is a regular expression that matches the IP address of the connecting host. So substitute your IP address for YOUR.IP.ADDRESS.HERE (or some other useful expression).
Other Valve
classes cater for other rules (e.g. RemoteHostValve
for matching host names). Earlier versions of Tomcat use a valve class org.apache.catalina.valves.RemoteIpValve for IP address matching.
Once the changes above have been made, you should be presented with an authentication dialog when accessing the manager URL. If you enter the details you have supplied in tomcat-users.xml
you should have access to the Manager.
The function JSON.stringify will turn your json object into a string:
var jsonAsString = JSON.stringify(obj);
In case the browser does not implement it (IE6/IE7), use the JSON2.js script. It's safe as it uses the native implementation if it exists.
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.
void show2() throws Exception //Why throws is necessary here ?
{
show();
}
Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
Use the latest fs-extra
.
I had that problem on Ubuntu
(16 and 18) with plenty of file/socket-descriptors space (count with lsof |wc -l
). Used fs-extra
version 8.1.0
. After the update to 9.0.0
the "Error: EMFILE, too many open files" vanished.
I've experienced diverse problems on diverse OS' with node handling filesystems. Filesystems are obviously not trivial.
Alternative:
df.shape[1]
(df.shape[0]
is the number of rows)
Say we have two date select fields, field1, and field2. field2 date depends on field1
$('#field2').datepicker();
$('#field1').datepicker({
onSelect: function(dateText, inst) {
$('#field2').val("");
$('#field2').datepicker("option", "minDate", new Date(dateText));
}
});
WHERE NOT (someColumn LIKE '%Apples%')
If we split it up, the mess is equal to:
++[[]][+[]]
+
[+[]]
In JavaScript, it is true that +[] === 0
. +
converts something into a number, and in this case it will come down to +""
or 0
(see specification details below).
Therefore, we can simplify it (++
has precendence over +
):
++[[]][0]
+
[0]
Because [[]][0]
means: get the first element from [[]]
, it is true that:
[[]][0]
returns the inner array ([]
). Due to references it's wrong to say [[]][0] === []
, but let's call the inner array A
to avoid the wrong notation.
++
before its operand means “increment by one and return the incremented result”. So ++[[]][0]
is equivalent to Number(A) + 1
(or +A + 1
).
Again, we can simplify the mess into something more legible. Let's substitute []
back for A
:
(+[] + 1)
+
[0]
Before +[]
can coerce the array into the number 0
, it needs to be coerced into a string first, which is ""
, again. Finally, 1
is added, which results in 1
.
(+[] + 1) === (+"" + 1)
(+"" + 1) === (0 + 1)
(0 + 1) === 1
Let's simplify it even more:
1
+
[0]
Also, this is true in JavaScript: [0] == "0"
, because it's joining an array with one element. Joining will concatenate the elements separated by ,
. With one element, you can deduce that this logic will result in the first element itself.
In this case, +
sees two operands: a number and an array. It’s now trying to coerce the two into the same type. First, the array is coerced into the string "0"
, next, the number is coerced into a string ("1"
). Number +
String ===
String.
"1" + "0" === "10" // Yay!
Specification details for +[]
:
This is quite a maze, but to do +[]
, first it is being converted to a string because that's what +
says:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber()
says:
Object
Apply the following steps:
Let primValue be ToPrimitive(input argument, hint String).
Return ToString(primValue).
ToPrimitive()
says:
Object
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
[[DefaultValue]]
says:
8.12.8 [[DefaultValue]] (hint)
When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:
Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
If IsCallable(toString) is true then,
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
The .toString
of an array says:
15.4.4.2 Array.prototype.toString ( )
When the toString method is called, the following steps are taken:
Let array be the result of calling ToObject on the this value.
Let func be the result of calling the [[Get]] internal method of array with argument "join".
If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).
Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.
So +[]
comes down to +""
, because [].join() === ""
.
Again, the +
is defined as:
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
Let expr be the result of evaluating UnaryExpression.
Return ToNumber(GetValue(expr)).
ToNumber
is defined for ""
as:
The MV of StringNumericLiteral ::: [empty] is 0.
So +"" === 0
, and thus +[] === 0
.
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.
Following the answer by @seangwright, I've written an abstract class that handles "infinite" observables' subscriptions in components:
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import { PartialObserver } from 'rxjs/Observer';
export abstract class InfiniteSubscriberComponent implements OnDestroy {
private onDestroySource: Subject<any> = new Subject();
constructor() {}
subscribe(observable: Observable<any>): Subscription;
subscribe(
observable: Observable<any>,
observer: PartialObserver<any>
): Subscription;
subscribe(
observable: Observable<any>,
next?: (value: any) => void,
error?: (error: any) => void,
complete?: () => void
): Subscription;
subscribe(observable: Observable<any>, ...subscribeArgs): Subscription {
return observable
.takeUntil(this.onDestroySource)
.subscribe(...subscribeArgs);
}
ngOnDestroy() {
this.onDestroySource.next();
this.onDestroySource.complete();
}
}
To use it, just extend it in your angular component and call the subscribe()
method as follows:
this.subscribe(someObservable, data => doSomething());
It also accepts the error and complete callbacks as usual, an observer object, or not callbacks at all. Remember to call super.ngOnDestroy()
if you are also implementing that method in the child component.
Find here an additional reference by Ben Lesh: RxJS: Don’t Unsubscribe.
Use the continue statement:
foreach(object number in mycollection) {
if( number < 0 ) {
continue;
}
}
For Bootstrap 4 simply remove the 'data-ride="carousel"' from the carousel div. This removes auto play at load time.
To enable the auto play again you would still have to use the "play" call in javascript.
I was looking for a solution to a similar TypeScript error with React:
Property 'dataset' does not exist on type EventTarget in TypeScript
I wanted to get to event.target.dataset
of a clicked button element in React:
<button
onClick={onClickHandler}
data-index="4"
data-name="Foo Bar"
>
Delete Candidate
</button>
Here is how I was able to get the dataset
value to "exist" via TypeScript:
const onClickHandler = (event: React.MouseEvent<HTMLButtonElement>) => {
const { name, index } = (event.target as HTMLButtonElement).dataset
console.log({ name, index })
// do stuff with name and index…
}
You need to start the script with a preceding dot, this will put the exported variables in the current environment.
#!/bin/bash
...
export output="SUCCESS"
Then execute it like so
chmod +x /tmp/test.sh
. /tmp/test.sh
When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate
You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.
Passing null would be better. The full codes is like:
WebView wv = (WebView)this.findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadDataWithBaseURL(null, "<html>...</html>", "text/html", "utf-8", null);
Edit:
In 2.7 / 3.2 there is a new writeheader()
method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader()
method now available in 2.7 / 3.2:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
dw.writeheader()
# continue on to write data
Instantiating DictWriter requires a fieldnames argument.
From the documentation:
The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with
statement was added in 2.6. If using 2.5: from __future__ import with_statement
with open(infile,'rb') as fin:
dr = csv.DictReader(fin, delimiter='\t')
# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
headers = {}
for n in dw.fieldnames:
headers[n] = n
dw.writerow(headers)
for row in dr:
dw.writerow(row)
As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
for row in dr:
dw.writerow(row)
Sadly, Mark Rushakoff's answer (now deleted - it referenced the code from here) does not seem to work correctly when adapted to:
source=/home/part2/part3/part4
target=/work/proj1/proj2
The thinking outlined in the commentary can be refined to make it work correctly for most cases. I'm about to assume that the script takes a source argument (where you are) and a target argument (where you want to get to), and that either both are absolute pathnames or both are relative. If one is absolute and the other relative, the easiest thing is to prefix the relative name with the current working directory - but the code below does not do that.
The code below is close to working correctly, but is not quite right.
xyz/./pqr
'.xyz/../pqr
'../
' from paths.Dennis's code is better because it fixes 1 and 5 - but has the same issues 2, 3, 4. Use Dennis's code (and up-vote it ahead of this) because of that.
(NB: POSIX provides a system call realpath()
that resolves pathnames so that there are no symlinks left in them. Applying that to the input names, and then using Dennis's code would give the correct answer each time. It is trivial to write the C code that wraps realpath()
- I've done it - but I don't know of a standard utility that does so.)
For this, I find Perl easier to use than shell, though bash has decent support for arrays and could probably do this too - exercise for the reader. So, given two compatible names, split them each into components:
Thus:
#!/bin/perl -w
use strict;
# Should fettle the arguments if one is absolute and one relative:
# Oops - missing functionality!
# Split!
my(@source) = split '/', $ARGV[0];
my(@target) = split '/', $ARGV[1];
my $count = scalar(@source);
$count = scalar(@target) if (scalar(@target) < $count);
my $relpath = "";
my $i;
for ($i = 0; $i < $count; $i++)
{
last if $source[$i] ne $target[$i];
}
$relpath = "." if ($i >= scalar(@source) && $relpath eq "");
for (my $s = $i; $s < scalar(@source); $s++)
{
$relpath = "../$relpath";
}
$relpath = "." if ($i >= scalar(@target) && $relpath eq "");
for (my $t = $i; $t < scalar(@target); $t++)
{
$relpath .= "/$target[$t]";
}
# Clean up result (remove double slash, trailing slash, trailing slash-dot).
$relpath =~ s%//%/%;
$relpath =~ s%/$%%;
$relpath =~ s%/\.$%%;
print "source = $ARGV[0]\n";
print "target = $ARGV[1]\n";
print "relpath = $relpath\n";
Test script (the square brackets contain a blank and a tab):
sed 's/#.*//;/^[ ]*$/d' <<! |
/home/part1/part2 /home/part1/part3
/home/part1/part2 /home/part4/part5
/home/part1/part2 /work/part6/part7
/home/part1 /work/part1/part2/part3/part4
/home /work/part2/part3
/ /work/part2/part3/part4
/home/part1/part2 /home/part1/part2/part3/part4
/home/part1/part2 /home/part1/part2/part3
/home/part1/part2 /home/part1/part2
/home/part1/part2 /home/part1
/home/part1/part2 /home
/home/part1/part2 /
/home/part1/part2 /work
/home/part1/part2 /work/part1
/home/part1/part2 /work/part1/part2
/home/part1/part2 /work/part1/part2/part3
/home/part1/part2 /work/part1/part2/part3/part4
home/part1/part2 home/part1/part3
home/part1/part2 home/part4/part5
home/part1/part2 work/part6/part7
home/part1 work/part1/part2/part3/part4
home work/part2/part3
. work/part2/part3
home/part1/part2 home/part1/part2/part3/part4
home/part1/part2 home/part1/part2/part3
home/part1/part2 home/part1/part2
home/part1/part2 home/part1
home/part1/part2 home
home/part1/part2 .
home/part1/part2 work
home/part1/part2 work/part1
home/part1/part2 work/part1/part2
home/part1/part2 work/part1/part2/part3
home/part1/part2 work/part1/part2/part3/part4
!
while read source target
do
perl relpath.pl $source $target
echo
done
Output from the test script:
source = /home/part1/part2
target = /home/part1/part3
relpath = ../part3
source = /home/part1/part2
target = /home/part4/part5
relpath = ../../part4/part5
source = /home/part1/part2
target = /work/part6/part7
relpath = ../../../work/part6/part7
source = /home/part1
target = /work/part1/part2/part3/part4
relpath = ../../work/part1/part2/part3/part4
source = /home
target = /work/part2/part3
relpath = ../work/part2/part3
source = /
target = /work/part2/part3/part4
relpath = ./work/part2/part3/part4
source = /home/part1/part2
target = /home/part1/part2/part3/part4
relpath = ./part3/part4
source = /home/part1/part2
target = /home/part1/part2/part3
relpath = ./part3
source = /home/part1/part2
target = /home/part1/part2
relpath = .
source = /home/part1/part2
target = /home/part1
relpath = ..
source = /home/part1/part2
target = /home
relpath = ../..
source = /home/part1/part2
target = /
relpath = ../../../..
source = /home/part1/part2
target = /work
relpath = ../../../work
source = /home/part1/part2
target = /work/part1
relpath = ../../../work/part1
source = /home/part1/part2
target = /work/part1/part2
relpath = ../../../work/part1/part2
source = /home/part1/part2
target = /work/part1/part2/part3
relpath = ../../../work/part1/part2/part3
source = /home/part1/part2
target = /work/part1/part2/part3/part4
relpath = ../../../work/part1/part2/part3/part4
source = home/part1/part2
target = home/part1/part3
relpath = ../part3
source = home/part1/part2
target = home/part4/part5
relpath = ../../part4/part5
source = home/part1/part2
target = work/part6/part7
relpath = ../../../work/part6/part7
source = home/part1
target = work/part1/part2/part3/part4
relpath = ../../work/part1/part2/part3/part4
source = home
target = work/part2/part3
relpath = ../work/part2/part3
source = .
target = work/part2/part3
relpath = ../work/part2/part3
source = home/part1/part2
target = home/part1/part2/part3/part4
relpath = ./part3/part4
source = home/part1/part2
target = home/part1/part2/part3
relpath = ./part3
source = home/part1/part2
target = home/part1/part2
relpath = .
source = home/part1/part2
target = home/part1
relpath = ..
source = home/part1/part2
target = home
relpath = ../..
source = home/part1/part2
target = .
relpath = ../../..
source = home/part1/part2
target = work
relpath = ../../../work
source = home/part1/part2
target = work/part1
relpath = ../../../work/part1
source = home/part1/part2
target = work/part1/part2
relpath = ../../../work/part1/part2
source = home/part1/part2
target = work/part1/part2/part3
relpath = ../../../work/part1/part2/part3
source = home/part1/part2
target = work/part1/part2/part3/part4
relpath = ../../../work/part1/part2/part3/part4
This Perl script works fairly thoroughly on Unix (it does not take into account all the complexities of Windows path names) in the face of weird inputs. It uses the module Cwd
and its function realpath
to resolve the real path of names that exist, and does a textual analysis for paths that don't exist. In all cases except one, it produces the same output as Dennis's script. The deviant case is:
source = home/part1/part2
target = .
relpath1 = ../../..
relpath2 = ../../../.
The two results are equivalent - just not identical. (The output is from a mildly modified version of the test script - the Perl script below simply prints the answer, rather than the inputs and the answer as in the script above.) Now: should I eliminate the non-working answer? Maybe...
#!/bin/perl -w
# Based loosely on code from: http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-10/1256.html
# Via: http://stackoverflow.com/questions/2564634
use strict;
die "Usage: $0 from to\n" if scalar @ARGV != 2;
use Cwd qw(realpath getcwd);
my $pwd;
my $verbose = 0;
# Fettle filename so it is absolute.
# Deals with '//', '/./' and '/../' notations, plus symlinks.
# The realpath() function does the hard work if the path exists.
# For non-existent paths, the code does a purely textual hack.
sub resolve
{
my($name) = @_;
my($path) = realpath($name);
if (!defined $path)
{
# Path does not exist - do the best we can with lexical analysis
# Assume Unix - not dealing with Windows.
$path = $name;
if ($name !~ m%^/%)
{
$pwd = getcwd if !defined $pwd;
$path = "$pwd/$path";
}
$path =~ s%//+%/%g; # Not UNC paths.
$path =~ s%/$%%; # No trailing /
$path =~ s%/\./%/%g; # No embedded /./
# Try to eliminate /../abc/
$path =~ s%/\.\./(?:[^/]+)(/|$)%$1%g;
$path =~ s%/\.$%%; # No trailing /.
$path =~ s%^\./%%; # No leading ./
# What happens with . and / as inputs?
}
return($path);
}
sub print_result
{
my($source, $target, $relpath) = @_;
if ($verbose)
{
print "source = $ARGV[0]\n";
print "target = $ARGV[1]\n";
print "relpath = $relpath\n";
}
else
{
print "$relpath\n";
}
exit 0;
}
my($source) = resolve($ARGV[0]);
my($target) = resolve($ARGV[1]);
print_result($source, $target, ".") if ($source eq $target);
# Split!
my(@source) = split '/', $source;
my(@target) = split '/', $target;
my $count = scalar(@source);
$count = scalar(@target) if (scalar(@target) < $count);
my $relpath = "";
my $i;
# Both paths are absolute; Perl splits an empty field 0.
for ($i = 1; $i < $count; $i++)
{
last if $source[$i] ne $target[$i];
}
for (my $s = $i; $s < scalar(@source); $s++)
{
$relpath = "$relpath/" if ($s > $i);
$relpath = "$relpath..";
}
for (my $t = $i; $t < scalar(@target); $t++)
{
$relpath = "$relpath/" if ($relpath ne "");
$relpath = "$relpath$target[$t]";
}
print_result($source, $target, $relpath);
For such a seemingly simple thing this can be a royal pain in the butt! I found a solution that works beautifully (class="video-close" is obviously particular to this button and optional)
<a href="javascript:window.open('','_self').close();" class="video-close">Close this window</a>
A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
You can't. You can only have one slide size and one orientation per presentation.
Are you projecting the presentation or delivering it on a laptop?
If so, the size is sort of irrelevant.
Regardless of the slide size, the projected/displayed image will never be longer or wider than the projector/display accepts.
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
Programmatic options for controlling services:
StartService
method. This is good for cases where you need to be able to perform other processing (e.g. to select which service).Start-Service
via RunspaceInvoke
or by creating your own Runspace
and using its CreatePipeline
method to execute. This is good for cases where you need to be able to perform other processing (e.g. to select which service) with a much easier coding model than WMI, but depends on PSH being installed.ServiceController
java.sql.Timestamp
.valueOf( // Class-method parses SQL-style formatted date-time strings.
"2007-11-11 12:13:14"
) // Returns a `Timestamp` object.
.toInstant() // Converts from terrible legacy classes to modern *java.time* class.
java.sql.Timestamp.valueOf
parses SQL formatIf you can use the full four digits for the year, your input string of 2007-11-11 12:13:14
would be in standard SQL format assuming this value is meant to be in UTC time zone.
The java.sql.Timestamp
class has a valueOf
method to directly parse such strings.
String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;
In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString
method. In contrast, the java.time classes by default use the standard ISO 8601 formats.
System.out.println( "Output: " + ts.toInstant().toString() );
Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.
If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow
How to convert <select> dropdown into an unordered list using jquery?
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
Yes, nowadays you can develop apps for iOS in Python.
There are two frameworks that you may want to checkout: Kivy and PyMob.
Please consider the answers to this question too, as they are more up-to-date than this one.
well you need to understand there are always two things the API and the implementation (mind the gradle format of the following code)
compile group:'javax.servlet.jsp.jstl', name:'javax.servlet.jsp.jstl-api', version:'1.2.1'
compile group:'org.glassfish.web', name:'javax.servlet.jsp.jstl',version:'1.2.1'
so If you're using a servlet container with no jstl support then of course it will not provide both of them, a mistake which I made is that I only put the first one, but if you're using full stack application server i.e glassfish then glassfish will have both of them already inside.
Another solution which worked for me is to go to Java--> Appearence --> Type Filters and do disable all
If you don't mind changing your HTML, you can use the data-toggle
attribute on <button>
s. See the Single toggle section of the button examples:
<button type="button" class="btn btn-primary" data-toggle="button">
Single toggle
</button>
The only way to ensure code is executed is to place your setTimeout logic in a different process.
Use the child process module to spawn a new node.js program that does your logic and pass data to that process through some kind of a stream (maybe tcp).
This way even if some long blocking code is running in your main process your child process has already started itself and placed a setTimeout in a new process and a new thread and will thus run when you expect it to.
Further complication are at a hardware level where you have more threads running then processes and thus context switching will cause (very minor) delays from your expected timing. This should be neglible and if it matters you need to seriously consider what your trying to do, why you need such accuracy and what kind of real time alternative hardware is available to do the job instead.
In general using child processes and running multiple node applications as separate processes together with a load balancer or shared data storage (like redis) is important for scaling your code.
Check out Peter Norvig's essay on becoming a master programmer in 10 years: http://norvig.com/21-days.html. I'd wager it holds true for any language.
You can access the array index directly:
var csv = 'zero,one,two,three';
csv.split(',')[0]; //result: zero
csv.split(',')[3]; //result: three
From the reference docs of Comparable.compareTo(T):
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
In short:
this.compareTo(that)
returns
where the implementation of this method determines the actual semantics of <
>
and ==
(I don't mean ==
in the sense of java's object identity operator)
"abc".compareTo("def")
will yield something smaller than 0 as abc
is alphabetically before def
.
Integer.valueOf(2).compareTo(Integer.valueOf(1))
will yield something larger than 0 because 2 is larger than 1.
Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.
Note: you should read at least one of the following:
Warning: you should never rely on the return values of compareTo being -1
, 0
and 1
. You should always test for x < 0
, x == 0
, x > 0
, respectively.
dt
accessorA common source of confusion revolves around when to use .year
and when to use .dt.year
.
The former is an attribute for pd.DatetimeIndex
objects; the latter for pd.Series
objects. Consider this dataframe:
df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))
The definition of the series and index look similar, but the pd.DataFrame
constructor converts them to different types:
type(df.index) # pandas.tseries.index.DatetimeIndex
type(df['Dates']) # pandas.core.series.Series
The DatetimeIndex
object has a direct year
attribute, while the Series
object must use the dt
accessor. Similarly for month
:
df.index.month # array([1, 1, 1])
df['Dates'].dt.month.values # array([ 1, 10, 12], dtype=int64)
A subtle but important difference worth noting is that df.index.month
gives a NumPy array, while df['Dates'].dt.month
gives a Pandas series. Above, we use pd.Series.values
to extract the NumPy array representation.
Here's an example of the ImageCodecInfo suggestion (in VB):
Imports System.Drawing.Imaging
...
Dim ofd as new OpenFileDialog()
ofd.Filter = ""
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
Dim sep As String = String.Empty
For Each c As ImageCodecInfo In codecs
Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
sep = "|"
Next
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")
And it looks like this:
To find prime numbers between 0 to n. You just have to check if a number x is getting divisible by any number between 0 - (square root of x). If we pass n and to find all prime numbers between 0 and n, logic can be implemented as -
function findPrimeNums(n)
{
var x= 3,j,i=2,
primeArr=[2],isPrime;
for (;x<=n;x+=2){
j = (int) Math.sqrt (x);
isPrime = true;
for (i = 2; i <= j; i++)
{
if (x % i == 0){
isPrime = false;
break;
}
}
if(isPrime){
primeArr.push(x);
}
}
return primeArr;
}
For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.
Definitely EditPad Lite !
It's extremely fast not just while opening files, but also functions like "Replace All", trimming of leading/trailing whitespaces or converting content to lowercase are very fast.
And it is also very similar to Notepad++ ;)
That isn't the problem, Jack. Android SDK isn't x64, but works ok with x64 jvm (and x64 eclipse IDE).
As helios said, you must set project compatibility to Java 5.0 or Java 6.0.
To do that, 2 options:
"Android Tools -> Fix
Project Properties"
(if this din't work, try second option)"Properties -> Java
Compiler"
, check "Enable project specific settings" and select
1.5 or 1.6 from "Compiler compliance settings" select box.I wrapped the top answer in a polyfill so I can call .sortIgnoreCase() on string arrays
// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
Array.prototype.sortIgnoreCase = function () {
return this.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
};
}
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);
With num_rows()
you first perform the query, and then you can check how many rows you got. count_all_results()
on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.
// num rows example
$this->db->select('*');
$this->db->where('whatever');
$query = $this->db->get('table');
$num = $query->num_rows();
// here you can do something with $query
// count all example
$this->db->where('whatever');
$num = $this->db->count_all_results('table');
// here you only have $num, no $query
A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.
When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.
In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.
All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.
If you are a Windows user once go through this link you will get more.
This should show all files modified within the last 7 days.
find . -type f -mtime -7 -print
Pipe that into tar/zip, and you should be good.
Try the following, no extra headers
wget -qO- www.google.com
Note the trailing -
. This is part of the normal command argument for -O
to cat out to a file, but since we don't use >
to direct to a file, it goes out to the shell. You can use -qO-
or -qO -
.
Your string is not valid JSON, so JSON.parse
(or jQuery's $.parseJSON
) won't work.
One way would be to use eval
to "parse" the "invalid" JSON, and then stringify
it to "convert" it to valid JSON.
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));
I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str
being generated, it should be fixed there, before it's generated, not after.
EDIT: You said (in the comments) this string is stored in a data attribute:
<div data-object="{hello:'world'}"></div>
I suggest you fix it here, so it can just be JSON.parse
d. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):
<div data-object='{"hello":"world"}'></div>
Now, you can just use JSON.parse
(or jQuery's $.parseJSON
).
var str = '{"hello":"world"}';
var obj = JSON.parse(str);
Based on your comment to Issun:
Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated Collection
with no items added shows <No Variables>
in the watch window. If your object is indeed a collection, you can check for the <No Variables>
condition using the .Count
property:
Sub TestObj()
Dim Obj As Object
Set Obj = New Collection
If Obj Is Nothing Then
Debug.Print "Object not instantiated"
Else
If Obj.Count = 0 Then
Debug.Print "<No Variables> (ie, no items added to the collection)"
Else
Debug.Print "Object instantiated and at least one item added"
End If
End If
End Sub
It is also worth noting that if you declare any object As New
then the Is Nothing
check becomes useless. The reason is that when you declare an object As New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
The other offical way would be using git bundle
That will create a file that support git fetch
and git pull
in order to update your second repo.
Useful for incremental backup and restore.
But if you need to backup everything (because you do not have a second repo with some older content already in place), the backup is a bit more elaborate to do, as mentioned in my other answer, after Kent Fredric's comment:
$ git bundle create /tmp/foo master
$ git bundle create /tmp/foo-all --all
$ git bundle list-heads /tmp/foo
$ git bundle list-heads /tmp/foo-all
(It is an atomic operation, as opposed to making an archive from the .git
folder, as commented by fantabolous)
Warning: I wouldn't recommend Pat Notz's solution, which is cloning the repo.
Backup many files is always more tricky than backing up or updating... just one.
If you look at the history of edits of the OP Yar answer, you would see that Yar used at first a clone --mirror
, ... with the edit:
Using this with Dropbox is a total mess.
You will have sync errors, and you CANNOT ROLL A DIRECTORY BACK IN DROPBOX.
Usegit bundle
if you want to back up to your dropbox.
Yar's current solution uses git bundle
.
I rest my case.
Ok if anyone else is having this problem this may be your answer:
If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.
For the 10 MB memory constraint:
When finished, just take a path that has not been created before to create the requested number.
4 billion number = 2^32, meaning 10 MB might not be sufficient.
EDIT
An optimization is possible, if two ends leafs have been created and have a common parent, then they can be removed and the parent flagged as not a solution. This cuts branches and reduces the need for memory.
EDIT II
There is no need to build the tree completely too. You only need to build deep branches if numbers are similar. If we cut branches too, then this solution might work in fact.
rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber
Very Simple way to create an object in Java using Class<?>
with constructor argument(s) passing:
Case 1:-
Here, is a small code in this Main
class:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Get class name as string.
String myClassName = Base.class.getName();
// Create class of type Base.
Class<?> myClass = Class.forName(myClassName);
// Create constructor call with argument types.
Constructor<?> ctr = myClass.getConstructor(String.class);
// Finally create object of type Base and pass data to constructor.
String arg1 = "My User Data";
Object object = ctr.newInstance(new Object[] { arg1 });
// Type-cast and access the data from class Base.
Base base = (Base)object;
System.out.println(base.data);
}
}
And, here is the Base
class structure:
public class Base {
public String data = null;
public Base()
{
data = "default";
System.out.println("Base()");
}
public Base(String arg1) {
data = arg1;
System.out.println("Base("+arg1+")");
}
}
Case 2:- You, can code similarly for constructor with multiple argument and copy constructor. For example, passing 3 arguments as parameter to the Base
constructor will need the constructor to be created in class and a code change in above as:
Constructor<?> ctr = myClass.getConstructor(String.class, String.class, String.class);
Object object = ctr.newInstance(new Object[] { "Arg1", "Arg2", "Arg3" });
And here the Base class should somehow look like:
public class Base {
public Base(String a, String b, String c){
// This constructor need to be created in this case.
}
}
Note:- Don't forget to handle the various exceptions which need to be handled in the code.
The easiest way to do this, is to install a JDK and tell Eclipse to use it as the default JRE. Use the default install.
(from memory)
Open Window -> Prefences. Select Installed Java runtimes, and choose Add. Navigate to root of your JDK (\Programs...\Java) and click Ok. Then select it to be the default JRE (checkmark).
After a workspace rebuild, you should have source attached to all JRE classes.
If there's a period in the table name, it will fail for
SELECT * FROM poorly_named.table;
Use backticks to get it to find the table
SELECT * FROM `poorly_named.table`;
For Visual Studio users: Right click on the npm folder and "Restore Packages".
Either replace double quotes around type="text"
with single quotes, Like
"<form><input type='text'/></form>"
OR
replace double quotes wrapping data-content
with singe quotes, Like
data-content='<form><input type="text"/></form>'
Here is a working solution:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char str1[16];
char str2[16];
strcpy(str1, "sssss");
strcpy(str2, "kkkk");
strcat(str1, str2);
printf("%s", str1);
return 0;
}
Output:
ssssskkkk
You have to allocate memory for your strings. In the above code, I declare str1
and str2
as character arrays containing 16 characters. I used strcpy
to copy characters of string literals into them, and strcat
to append the characters of str2
to the end of str1
. Here is how these character arrays look like during the execution of the program:
After declaration (both are empty):
str1: [][][][][][][][][][][][][][][][][][][][]
str2: [][][][][][][][][][][][][][][][][][][][]
After calling strcpy (\0 is the string terminator zero byte):
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
After calling strcat:
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
Assuming employee numbers are in the first column and their names are in the second:
=VLOOKUP(A1, Sheet2!A:B, 2,false)
I'm using this:
String URL = Resources.getSystem().getString(R.string.mess_1);
var ArrayofObjects = [{}]; //An empty array of objects.
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
Use a subselect:
SELECT row FROM table WHERE id=(
SELECT max(id) FROM table
)
Note: ID must be unique, else multiple rows are returned
suppose you're posting a html form with this:
<input type="text" name="username">
If using raw cgi:
import cgi
form = cgi.FieldStorage()
print form["username"]
If using Django, Pylons, Flask or Pyramid:
print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method
Using Turbogears, Cherrypy:
from cherrypy import request
print request.params['username']
form = web.input()
print form.username
print request.form['username']
If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:
def index(self, username):
print username
class SomeHandler(webapp2.RequestHandler):
def post(self):
name = self.request.get('username') # this will get the value from the field named username
self.response.write(name) # this will write on the document
So you really will have to choose one of those frameworks.
select t.username, t.date, t.value
from MyTable t
inner join (
select username, max(date) as MaxDate
from MyTable
group by username
) tm on t.username = tm.username and t.date = tm.MaxDate
The following works for me when disabling Findbugs in a child POM:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<executions>
<execution>
<id>ID_AS_IN_PARENT</id> <!-- id is necessary sometimes -->
<phase>none</phase>
</execution>
</executions>
</plugin>
Note: the full definition of the Findbugs plugin is in our parent/super POM, so it'll inherit the version and so-on.
In Maven 3, you'll need to use:
<configuration>
<skip>true</skip>
</configuration>
for the plugin.
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
I don't know how good or bad this is, but you can try something like this:
try:
obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
obj = Model.objects.create()
obj.__dict__.update(your_fields_dict)
obj.save()
The simple version is 0x is a prefix denoting a hexadecimal number, source.
So the value you're computing is after the prefix, in this case 10.
But that is not the number 10. The most significant bit 1
denotes the hex value while 0
denotes the units.
So the simple math you would do is
0x10
1 * 16 + 0 = 16
Note - you use 16 because hex is base 16.
Another example:
0xF7
15 * 16 + 7 = 247
You can get a list of values by searching for a hex table. For instance in this chart notice F corresponds with 15.
You can use list comprehension together with the string methods.
>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'
As far as I can tell after reading the docs for javadoc there is no such feature.
Don't use <code>foo</code>
as recommended in other answers; you can use {@code foo}
. This is especially good to know when you refer to a generic type such as {@code Iterator<String>}
-- sure looks nicer than <code>Iterator<String></code>
, doesn't it!
You can add more key value pair in the same object without replacing old ones in following way:
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj["3"] = "cc";
Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:
var obj = {
"1": "aa",
"2": "bb"
};
var noOfItems = Object.keys(obj).length;
$('#btnAddProperty').on('click', function() {
noOfItems++;
obj[noOfItems] = $.trim($('#txtName').val());
console.log(obj);
});
Here is the snippet worked in my case
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
`
If you use auto-layout.
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.numberOfLines = 2
$('p:contains("dogsss")').text('dollsss');
I believe that, if you need to use the %20
variant, you could perhaps use rawurlencode()
.
//in html
<nav class="navbar navbar-default" id="mainnav">
<nav>
// add in jquery
$(document).ready(function() {
var navpos = $('#mainnav').offset();
console.log(navpos.top);
$(window).bind('scroll', function() {
if ($(window).scrollTop() > navpos.top) {
$('#mainnav').addClass('navbar-fixed-top');
}
else {
$('#mainnav').removeClass('navbar-fixed-top');
}
});
});
Here is the jsfiddle to play around : -http://jsfiddle.net/shubhampatwa/46ovg69z/
EDIT: if you want to apply this code only for mobile devices the you can use:
var newWindowWidth = $(window).width();
if (newWindowWidth < 481) {
//Place code inside it...
}
I had this problem recently where apt install wget
does not find anything. As it turns out apt update
was never run.
apt update
apt install wget
After discussing this with a coworker we mused that apt update
is likely not run in order to save both time and space in the docker image.
IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment
Will do the job as Buttle Butkus suggested.
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
I used that and it work fine :)
$("#textarea").html("Put here your content");
Remi
I was presented with the same issue. The cause for me was Grunt concatenating my JavaScript file.
I was using a ;\n
as a separator which caused the path to the source map to 404.
So dev tools was looking for jquery.min.map;
instead of jquery.min.map
.
I know that isn't the answer to the original question, but I am sure there are others out there with a similar Grunt configuration.
Set the Format to Custom and then specify the format:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";
or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)
Don't know about the picker for date and time together. Sounds like a custom control to me.
public class DateComparator implements Comparator<Marker> {
@Override
public int compare(Mark lhs, Mark rhs) {
Double distance = Double.valueOf(lhs.getDistance());
Double distance1 = Double.valueOf(rhs.getDistance());
if (distance.compareTo(distance1) < 0) {
return -1;
} else if (distance.compareTo(distance1) > 0) {
return 1;
} else {
return 0;
}
}
}
ArrayList(Marker) arraylist;
How To use:
Collections.sort(arraylist, new DateComparator());
You may also download a file directly from your template where you use download attribute and to [attr.href]
you can provide a property value from the component.
This simple solution should work on most browsers.
<a download [attr.href]="yourDownloadLink"></a>
Reference: https://www.w3schools.com/tags/att_a_download.asp
Just set an onload function on the body:
<body onload="init()">
Then do something like this in javascript:
function init() {
var someimage = 'changableBackgroudImage';
document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}
You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.
You can try lubridate package which makes life much easier
library(lubridate)
mdy_hms(mydate)
The above will change the date format to POSIXct
A sample working example:
> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt"
For case with factor use as.character
data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))
I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.
I used the following settings in the webpack:
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},
This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.
Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.
I updated my webpack with the following settings
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},
I then used the following command to import the images
import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">
<img style={{ width: 300, height: 150 }} src={img} />
</div>
public class HelloWorld{
public static void main(String[] args){
int[] LA = {1,2,4,5};
int k = 2;
int item = 3;
int j = LA.length;
int[] LA_NEW = new int[LA.length+1];
while(j >k){
LA_NEW[j] = LA[j-1];
j = j-1;
}
LA_NEW[k] = item;
for(int i = 0;i<k;i++){
LA_NEW[i] = LA[i];
}
for(int i : LA_NEW){
System.out.println(i);
}
}
}
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
In my experience, using the 32-bit version is more trouble-free. Unless you are working on applications that make heavy use of memory (mostly scientific computing, that uses more than 2GB memory), you're better off with 32-bit versions because:
This is a very common misconception. There is no live HTML5 video support (except for HLS on iOS and Mac Safari). You may be able to 'hack' it using a webm container, but I would not expect that to be universally supported. What you are looking for is included in the Media Source Extensions, where you can feed the fragments to the browser one at a time. but you will need to write some client side javascript.
Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):
var ListenerTracker=new function(){
var is_active=false;
// listener tracking datas
var _elements_ =[];
var _listeners_ =[];
this.init=function(){
if(!is_active){//avoid duplicate call
intercep_events_listeners();
}
is_active=true;
};
// register individual element an returns its corresponding listeners
var register_element=function(element){
if(_elements_.indexOf(element)==-1){
// NB : split by useCapture to make listener easier to find when removing
var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
_elements_.push(element);
_listeners_.push(elt_listeners);
}
return _listeners_[_elements_.indexOf(element)];
};
var intercep_events_listeners = function(){
// backup overrided methods
var _super_={
"addEventListener" : HTMLElement.prototype.addEventListener,
"removeEventListener" : HTMLElement.prototype.removeEventListener
};
Element.prototype["addEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["addEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])listeners[useCapture][type]=[];
listeners[useCapture][type].push(listener);
};
Element.prototype["removeEventListener"]=function(type, listener, useCapture){
var listeners=register_element(this);
// add event before to avoid registering if an error is thrown
_super_["removeEventListener"].apply(this,arguments);
// adapt to 'elt_listeners' index
useCapture=useCapture?1:0;
if(!listeners[useCapture][type])return;
var lid = listeners[useCapture][type].indexOf(listener);
if(lid>-1)listeners[useCapture][type].splice(lid,1);
};
Element.prototype["getEventListeners"]=function(type){
var listeners=register_element(this);
// convert to listener datas list
var result=[];
for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
if(typeof(type)=="string"){// filtered by type
if(list[type]){
for(var id in list[type]){
result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
}
}
}else{// all
for(var _type in list){
for(var id in list[_type]){
result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
}
}
}
}
return result;
};
};
}();
ListenerTracker.init();
Yes, it does, specially for very large SPA.
In some scenario, RequireJS is a must. For example, I develop PhoneGap applications using AngularJS that also uses Google Map API. Without AMD loader like RequireJS, the app would simply crash upon launch when offline as it cannot source the Google Map API scripts. An AMD loader gives me a chance to display an error message to the user.
However, integration between AngularJS and RequireJS is a bit tricky. I created angularAMD to make this a less painful process:
Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.
Here is a sample:
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
With this, perhaps you do not need to use a web service at all.
? extends HasWord
means "A class/interface that extends HasWord
." In other words, HasWord
itself or any of its children... basically anything that would work with instanceof HasWord
plus null
.
In more technical terms, ? extends HasWord
is a bounded wildcard, covered in Item 31 of Effective Java 3rd Edition, starting on page 139. The same chapter from the 2nd Edition is available online as a PDF; the part on bounded wildcards is Item 28 starting on page 134.
Update: PDF link was updated since Oracle removed it a while back. It now points to the copy hosted by the Queen Mary University of London's School of Electronic Engineering and Computer Science.
Update 2: Lets go into a bit more detail as to why you'd want to use wildcards.
If you declare a method whose signature expect you to pass in List<HasWord>
, then the only thing you can pass in is a List<HasWord>
.
However, if said signature was List<? extends HasWord>
then you could pass in a List<ChildOfHasWord>
instead.
Note that there is a subtle difference between List<? extends HasWord>
and List<? super HasWord>
. As Joshua Bloch put it: PECS = producer-extends, consumer-super.
What this means is that if you are passing in a collection that your method pulls data out from (i.e. the collection is producing elements for your method to use), you should use extends
. If you're passing in a collection that your method adds data to (i.e. the collection is consuming elements your method creates), it should use super
.
This may sound confusing. However, you can see it in List
's sort
command (which is just a shortcut to the two-arg version of Collections.sort). Instead of taking a Comparator<T>
, it actually takes a Comparator<? super T>
. In this case, the Comparator is consuming the elements of the List
in order to reorder the List itself.
Did you add
-vmargs
...
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
to your eclipse.ini?
Because if you have (and if you have added the lombok.jar to the libraries used by your project), it works just fine with Eclipse Helios:
Ian Tegebo mentions in the comments that:
a simple "restart" was not sufficient to pick up the changed vmargs:
I needed to explicitly exit and then start again.
chrisjleu mentions in the comments:
If you happen to be running a customized Eclipse Helios (3.6+) distribution then you may have to use the full path to
lombok.jar
in both thevm
arguments.
See commit b47e87f for more details.
boolean fullPathRequired = IdeFinder.getOS() == EclipseFinder.OS.UNIX || System.getProperty("lombok.installer.fullpath") != null;
Perhaps this:
str = str.Split(",").First();
You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway() # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass() # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method
As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.
The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)
Disclaimer: I am the author of Py4J
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
Just type mbox
then hit tab it will give you a magic shortcut to pump up a message box.
on my mac i found this file .gitignore_global
..it was in my home directory hidden so do a ls -altr
to see it.
I added eclipse files i wanted git to ignore. the contents looks like this:
*~
.DS_Store
.project
.settings
.classpath
.metadata
Using @Marc-François approach Firefox prompted me to download the html file
Finally the following is working for me (using both):
AddType application/x-httpd-php .htm .html
AddHandler x-httpd-php .htm .html
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
AngularJS has some methods called JQlite so we can use it. see link
Select the element in DOM is
angular.element( document.querySelector( '#div1' ) );
add the class like .addClass('alpha');
So finally
var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');
simplest method is just the copy the text that you want to paste it in cmd and open cmd goto "properties"---> "option" tab----> check the (give tick mark) "quickEdit mode" and click "ok" .....now you can paste any text from clipboard by doing right click from ur mouse.
Thank you..
I'm a newbie in Ansible, but I would suggest next solution:
playbook.yml
...
vars:
command_output_full:
stdout: will be overriden below
command_output: {{ command_output_full.stdout }}
...
...
...
tasks:
- name: Create variable from command
command: "echo Hello"
register: command_output_full
- debug: msg="{{ command_output }}"
It should work (and works for me) because Ansible uses lazy evaluation. But it seems it checks validity before the launch, so I have to define command_output_full.stdout
in vars.
And, of course, if it is too many such vars in vars
section, it will look ugly.
Understand this has been solved, but the solution provided above might not work in all situation.
For my case,
<div style="height: 490px; position:relative; overflow:hidden">
<div id="map-canvas"></div>
</div>
The base64 encoding of Content-Type: multipart/form-data
adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$http.post
Requests Directly from a FileList$scope.upload = function(url, fileList) {
var config = {
headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the File object and automatically set the content type.
ng-model
1The <input type=file>
element does not by default work with the ng-model directive. It needs a custom directive:
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
_x000D_
In iOS 6, the
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
is deprecated.
Use following code instead
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
NSLog(@"lat%f - lon%f", location.coordinate.latitude, location.coordinate.longitude);
}
For iOS 6~8, the above method is still necessary, but you have to handle authorization.
_locationManager = [CLLocationManager new];
_locationManager.delegate = self;
_locationManager.distanceFilter = kCLDistanceFilterNone;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse
//[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways
) {
// Will open an confirm dialog to get user's approval
[_locationManager requestWhenInUseAuthorization];
//[_locationManager requestAlwaysAuthorization];
} else {
[_locationManager startUpdatingLocation]; //Will update location immediately
}
This is the delegate method which handle user's authorization
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusNotDetermined: {
NSLog(@"User still thinking..");
} break;
case kCLAuthorizationStatusDenied: {
NSLog(@"User hates you");
} break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways: {
[_locationManager startUpdatingLocation]; //Will update location immediately
} break;
default:
break;
}
}
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
The solution is start the HttpClient into another execution task without sincronization context:
var submit = httpClient.PostAsync(uri, new StringContent(body, Encoding.UTF8,"application/json"));
var t = Task.Run(() => submit.ConfigureAwait(false));
await t.ConfigureAwait(false);
I'm not sure of the question, so here are two answers :
If you want to move your repository :
Simply copy the whole repository (with its .git
directory).
There is no absolute path in the .git
structure and nothing preventing it to be moved so you have nothing to do after the move. All the links to github (see in .git/config
) will work as before.
If you want to move files inside the repository :
Simply move the files. Then add the changes listed in git status
. The next commit
will do the necessary. You'll be happy to learn that no file will be duplicated : moving a file in git is almost costless.
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
I'm assuming the contents of src/main/resources/
is copied to WEB-INF/classes/
inside your .war at build time. If that is the case you can just do (substituting real values for the classname and the path being loaded).
URL sqlScriptUrl = MyServletContextListener.class
.getClassLoader().getResource("sql/script.sql");
Disabling SQL Net Banners saved us.
For me deleting the following code fixed it !
mLocationClient.setMockMode(true);
If for a block cipher you're not going to use a Cipher
transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.
So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher
objects. For example, you could use:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.
Ok, your second problem is that you are using String
to hold the ciphertext.
In general,
String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();
will not have someBytes
and retrievedBytes
being identical.
If you want/have to hold the ciphertext in a String
, base64-encode the ciphertext bytes first and construct the String
from the base64-encoded bytes. Then when you decrypt you'll getBytes()
to get the base64-encoded bytes out of the String
, then base64-decode them to get the real ciphertext, then decrypt that.
The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String
from the ciphertext, the String
constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.
In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.
I had this error for the first time ever while trying to debug some old legacy code, running now on PHP 7.30. The simplified code looked like this:
$testOK = true;
if ($testOK) {
$x['error'][] = 0;
$x['size'][] = 10;
$x['type'][] = 'file';
$x['tmp_name'][] = 'path/to/file/';
}
The simplest fix possible was to declare $x as array() before:
$x = array();
if ($testOK) {
// same code
}
FOR Swift 5+
let searchBarButtonItem = UIBarButtonItem(image: UIImage(named: "searchIcon"), style: .plain, target: self, action: #selector(onSearchButtonClicked))
self.navigationItem.rightBarButtonItem = searchBarButtonItem
@objc func onSearchButtonClicked(_ sender: Any){
print("SearchButtonClicked")
}
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
I know this is an older post but I ran across this while trying to solve the same problem in vbscript. I haven't tested this with mulitple network adapters but hope that it's helpful nonetheless.
for /f "delims=: tokens=2" %%a in ('ipconfig ^| findstr /R /C:"IPv4 Address"') do (set tempip=%%a)
set tempip=%tempip: =%
echo %tempip%
This assumes Win7. For XP, replace IPv4 Address
with IP Address
.
Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();
//patName will provide you parent window
String patName = itr.next();
//chldName will provide you child window
String chldName = itr.next();
//Switch to child window
driver.switchto().window(chldName);
//Do normal selenium code for performing action in child window
//To come back to parent window
driver.switchto().window(patName);
Take a look at the JSONObject reference:
http://www.json.org/javadoc/org/json/JSONObject.html
Without actually using the object, it looks like using either getNames() or keys() which returns an Iterator is the way to go.
We Use:
@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")
the project is a eclipse dynamic web project, then the path is:
{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml
This page shows how to add an UIAlertController if you are using Swift.
If you want to continue exactly one Docker container with a known name:
docker start `docker ps -a -q --filter "name=elas"`
I use macOS and used to have the same problem.
Running the following command in the terminal saved me:
conda install -c conda-forge keras tensorflow
Hope it helps.
Have a look at the documentation. You can have a .env file which picks up the PUBLIC_URL
Although you should remember that what its used for -
You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/
If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:
printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n",
sp->name,
sp->args,
sp->value,
sp->arraysize);
As for the connect by
use case, this approach should work for you:
select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level)
from dual
connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;
Because you have to have an index on a foreign key field you can just create a simple index on the field 'AID'
CREATE INDEX aid_index ON mytable (AID);
and only then drop the unique index 'AID'
ALTER TABLE mytable DROP INDEX AID;
I would use a two file setup like this:
index.php
<?php
session_start();
define('DS', TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF', $_SERVER['PHP_SELF'] );
if (!USERNAME or isset($_GET['logout']))
include('login.php');
// everything below will show after correct login
?>
login.php
<?php defined('DS') OR die('No direct access allowed.');
$users = array(
"user" => "userpass"
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: ' . $_SERVER['PHP_SELF']);
}else {
//invalid login
echo "<p>error logging in</p>";
}
}
echo '<form method="post" action="'.SELF.'">
<h2>Login</h2>
<p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
<p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
<p><input type="submit" name="submit" value="Login" class="button"/></p>
</form>';
exit;
?>
This: "Disconnected: No supported authentication methods available (server sent: publickey)" happened to me after I turned on Microsoft One Drive backup and sync for my files including the directory where I saved my ssh key. In my case the solution is simple: just go to Putty => SSH => Auth and just (re)browse again to where my same key is located and saved, then it worked. It looks backup and sync software such as Microsoft One Drive (and may be the same with Google Drive), affect the way Putty sees and identifies directories if the key directory is specified and then later some time installing or turning on backup and sync including that directory.
when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.
When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).
Well, the only thing I can make it work is like so:
servers: >
dev.example.com,
another.example.com
@Value("${servers}")
private String[] array;
And dont forget the @Configuration above your class....
Without the "," separation, no such luck...
Works too (boot 1.5.8 versie)
servers:
dev.example.com,
another.example.com
Add more than one class based on the condition:
<div ng-click="AbrirPopUp(s)"
ng-class="{'class1 class2 class3':!isNew,
'class1 class4': isNew}">{{ isNew }}</div>
Apply: class1 + class2 + class3 when isNew=false,
Apply: class1+ class4 when isNew=true
updated for Swift 3 :
used below code to make UIButton corner round:
yourButtonOutletName.layer.cornerRadius = 0.3 *
yourButtonOutletName.frame.size.height
With a little PowerShell script:
sqlcmd -Q "set nocount on select top 0 * from [DB].[schema].[table]" -o c:\temp\header.txt_x000D_
bcp [DB].[schema].[table] out c:\temp\query.txt -c -T -S BRIZA_x000D_
Get-Content c:\temp\*.txt | Set-Content c:\temp\result.txt_x000D_
Remove-Item c:\temp\header.txt_x000D_
Remove-Item c:\temp\query.txt
_x000D_
Warning: The concatenation follows the .txt file name (in alphabetical order)
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.
Example without using the apply
method:
function a(...args){_x000D_
b(...args);_x000D_
b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
Note This snippet returns a syntax error if your browser still uses ES5.
Editor's note: Since the snippet uses console.log()
, you must open your browser's JS console to see the result - there will be no in-page result.
It will display this result:
In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters
100%-100px is the same
div.thediv {
width: auto;
margin-right:100px;
}
With jQuery:
$(window).resize(function(){
$('.thediv').each(function(){
$(this).css('width', $(this).parent().width()-100);
})
});
Similar way is to use jQuery resize plugin
I'm just dropping in to say that using a soft link to accomplish this is a terrible, no-good, horrible idea.
One of the key things about writing software is reproduceability - you want to be able to get the same results every time. These systems are so complex that you want to reduce all invisible sources of error.
Having a soft link is an invisible source of error. It's the sort of thing you'll forget in a month, then move to a different machine, and wonder why you are getting different results - or, you'll try to upgrade your system, and you'll get weird errors because it's not expecting a softlink there.
Moreover, this isn't guaranteed to work - in particular, it's not clear that you will get the correct system include files, which have certainly changed between iterations of gcc.
gcc_select is a systematic way of doing the same thing which will work predictably, or in the very worst case you can file a bug report and get an eventual fix or fix it yourself.
Unfortunately :-( gcc_select does not affect which compiler XCode uses so it's not the way to go if you need to work in XCode (which I do). I still don't know what that way might be.
Bootstrap uses the variable:
$font-size-base: 1rem; // Assumes the browser default, typically 16px
I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:
html {
font-size: 14px;
}
Bootstrap will then take that value and use it via rems to set values for all kinds of things.
First of all we should not read parameters within the filter. Usually the headers are read in the filter to do few authentication tasks. Having said that one can read the HttpRequest body completely in the Filter or Interceptor by using the CharStreams:
String body = com.google.common.io.CharStreams.toString(request.getReader());
This does not affect the subsequent reads at all.
Put the threads in a list and then use the Join method
threads = []
t = Thread(...)
threads.append(t)
...repeat as often as necessary...
# Start all threads
for x in threads:
x.start()
# Wait for all of them to finish
for x in threads:
x.join()
To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:
output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6
# output =
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
output = output[,-1] # this removes column 1 for all rows
# output =
# [,1] [,2]
# [1,] 3 5
# [2,] 4 6
So you can just add output = output[,-1]
after the for loop in your original code.
Extracted from CodeIgniter :
if ( ! function_exists('is_https'))
{
/**
* Is HTTPS?
*
* Determines if the application is accessed via an encrypted
* (HTTPS) connection.
*
* @return bool
*/
function is_https()
{
if ( ! empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
{
return TRUE;
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
{
return TRUE;
}
elseif ( ! empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
{
return TRUE;
}
return FALSE;
}
}
This error can also be caused by the fact that files are still "locked" because of prior git actions. It has to do with how the Windows filesystem layer works. I once read a nice explanation on this, but I can't remember where.
In that case however, since it is basically a race condition, all you have to do is continue your interrupted rebase process. Unfortunately this happens to me all the time, so I wrote this little dangerous helper to keep my rebases going:
#!/bin/sh
set -e
git checkout .
git clean -df
git rebase --continue
If you want to be extra sure, you can use git rebase --edit-todo
to check if the next commit to be applied is really the one that failed to be applied before. Use git clean -dn
to make sure you do not delete any important files.
Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var()
with FILTER_SANITIZE_NUMBER_INT
.
echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);
A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are alphanumeric, colon, or spaces is to use ltrim()
with a character mask then cast the remaining string as an integer.
$string = "In My Cart : 11 items";
echo (int)ltrim($string, 'A..z: ');
// 11
If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.
echo preg_match('/\d+/', $string, $m) ? $m[0] : '';
No need to convert the channel to public then make it private.
find the id of your private channel. (There are numerous methods to do this, for example see this SO answer)
curl -X POST "https://api.telegram.org/botxxxxxx:yyyyyyyyyyy/sendMessage" -d "chat_id=-100CHAT_ID&text=my sample text"
replace xxxxxx:yyyyyyyyyyy with your bot id, and replace CHAT_ID with the channel id found in step 1. So if channel id is 1234 it would be chat_id=-1001234.
All done!
Maybe I'm over simplifying here, and that may be the case, but this seems to work for me. Haven't ran into any problems with it yet...
CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7 - 7) as 'FirstDayOfWeek'
CAST('1/1/' + CAST(YEAR(GETDATE()) AS VARCHAR(30)) AS DATETIME) + (DATEPART(wk, YOUR_DATE) * 7) as 'LastDayOfWeek'
With urlsearchparams:
const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`
You do have an RTRIM
and an LTRIM
function. You can combine them to get the trim function you want.
UPDATE Table
SET Name = RTRIM(LTRIM(Name))
On the Swiss-French keyboard : use CTRL + SHIFT + ^
I'm guessing you're using the date_select
helper to generate the tags for the date. Another way you could do it is to use select form helper for the day, month, year fields. Like this (example I used is the created_at date field):
<%= f.select :month, (1..12).to_a, selected: @user.created_at.month %>
<%= f.select :day, (1..31).to_a, selected: @user.created_at.day %>
<%= f.select :year, ((Time.now.year - 20)..Time.now.year).to_a, selected: @user.created_at.year %>
And in the model, you validate the date:
attr_accessor :month, :day, :year
validate :validate_created_at
private
def convert_created_at
begin
self.created_at = Date.civil(self.year.to_i, self.month.to_i, self.day.to_i)
rescue ArgumentError
false
end
end
def validate_created_at
errors.add("Created at date", "is invalid.") unless convert_created_at
end
If you're looking for a plugin solution, I'd checkout the validates_timeliness plugin. It works like this (from the github page):
class Person < ActiveRecord::Base
validates_date :date_of_birth, on_or_before: lambda { Date.current }
# or
validates :date_of_birth, timeliness: { on_or_before: lambda { Date.current }, type: :date }
end
The list of validation methods available are as follows:
validates_date - validate value as date
validates_time - validate value as time only i.e. '12:20pm'
validates_datetime - validate value as a full date and time
validates - use the :timeliness key and set the type in the hash.
Interesting if maddening puzzle...but here's the best I could get:
The data seems to repeat every 8 bytes or so.
import struct
import base64
target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'''
data = base64.b64decode(target)
cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))
That gives output like the following (a sampling of lines from the first 100 or so):
(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)
That first number does seem to monotonically increase through the entire set. If you plot it:
import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))
format = 'hhhh'
(possibly with various paddings/directions (e.g. '<hhhh'
, '<xhhhh'
) also might be worth a look (again, random lines):
(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)
This is an example of using XOR(^), from this answer
byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };
byte[] array_3 = new byte[6];
int i = 0;
for (byte b : array_1)
array_3[i] = b ^ array_2[i++];
Output
0 0 1 1 1 0
Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.
The calling code looks like this:
var @switch = this.Switch(new []
{
this.Case<WebControl>(x => { /* WebControl code here */ }),
this.Case<TextBox>(x => { /* TextBox code here */ }),
this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});
@switch(obj);
The x
in each lambda above is strongly-typed. No casting required.
And to make this magic work you need these two methods:
private Action<object> Switch(params Func<object, Action>[] tests)
{
return o =>
{
var @case = tests
.Select(f => f(o))
.FirstOrDefault(a => a != null);
if (@case != null)
{
@case();
}
};
}
private Func<object, Action> Case<T>(Action<T> action)
{
return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}
Almost brings tears to your eyes, right?
Nonetheless, it works. Enjoy.
You are replacing the starting tag and then putting that back in innerHTML
, so the code will be invalid. Make all the replacements before you put the code back in the element:
var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
You can use System.Diagnostics.Process.Start
.
Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.
public partial class Window1 : Window
{
public Window1()
{
ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
InitializeComponent();
}
public enum ShowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
ShowCommands nShowCmd);
}
The declarations come from the pinvoke.net website.
How about XStream? Not 1 class but 2 jars for many use cases including yours, very simple to use yet quite powerful.
I'm not sure but:
If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?
If you call the delete method with a transient object, then it is possible that you have a cascade="delete"
or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.
Edit: Calling delete() with a transient instance means doing something like that:
MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);
This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.
If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18
.
You can have two choices for this to actually implement:
Using IIF, which got introduced from SQL Server 2012:
SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
Using Select Case
:
SELECT CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END as Saleable, *
FROM Product
My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:
python3 -m pip install numpy
In your CSS Style tag put this:
body {
background: url('yourgif.gif') no-repeat center center fixed;
background-size: cover;
}
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
I too experienced same problem in the DataGridView but figured out that the DefaultCell style was inheriting the font of the groupbox (Datagrid is placed in groupbox). So changing the font of the groupbox changed the DefaultCellStyle too.
Regards
You can use str_pad
for adding 0's
str_pad($month, 2, '0', STR_PAD_LEFT);
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
With Python 3.8 this workes for me. For instance to execute a python script within the venv:
import subprocess
import sys
res = subprocess.run([
sys.executable, # venv3.8/bin/python
'main.py', '--help',],
stdout=PIPE,
text=True)
print(res.stdout)
I think the jQuery plugin freezeframe.js might come in handy for you. freezeframe.js is a jQuery Plugin To Automatically Pause GIFs And Restart Animating On Mouse Hover.
I guess you can easily adapt it to make it work on page load instead.
I think what TCSgrad was trying to ask (a few years ago) was how to make Linux behave like his Windows machine does. That is, there is an agent (pageant) which holds a decrypted copy of a private key so that the passphrase only needs to be put in once. Then, the ssh client, putty, can log in to machines where his public key is listed as "authorized" without a password prompt.
The analog for this is that Linux, acting as an ssh client, has an agent holding a decrypted private key so that when TCSgrad types "ssh host" the ssh command will get his private key and go without being prompted for a password. host would, of course, have to be holding the public key in ~/.ssh/authorized_keys.
The Linux analog to this scenario is accomplished using ssh-agent (the pageant analog) and ssh-add (the analog to adding a private key to pageant).
The method that worked for me was to use: $ ssh-agent $SHELL That $SHELL was the magic trick I needed to make the agent run and stay running. I found that somewhere on the 'net and it ended a few hours of beating my head against the wall.
Now we have the analog of pageant running, an agent with no keys loaded.
Typing $ ssh-add by itself will add (by default) the private keys listed in the default identity files in ~/.ssh .
A web article with a lot more details can be found here
getting following error
It happens: Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
_x000D_
Use Concat
or Union
extension methods. You have to make sure that you have this direction using System.Linq;
in order to use LINQ extensions methods.
Use the AddRange
method.
TO CHANGE ConstraintLayout to RelativeLayout: This will work in Android studio 3.0.1
Change->
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
into
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
and->
</android.support.constraint.ConstraintLayout>
nto
</android.widget.RelativeLayout>
First List the Variable that you want to use them in Script task at ReadOnlyVariables in the Script task editor and Edit the Script
To use your ReadOnlyVariables in script code
String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();
this line of code will treat the ssis package variable as a string.
you can simply prevent adding non-numerical chars by this simple code
if (long.TryParse(TextBox.Text,out long isparsable))
{
// your code to handle numbers
}
else
{
TextBox.Text="Only Numbers Allowed";
TextBox.Focus();
TextBox.SelectAll();
}
Why not merge the rows that contain the same values? -
13 21 29 37 45
1000] -75.2 -- 79.21 -- 80.02
5000] ---------------------87.9---88.54----88.56
10000] -------------------90.11--90.97----90.87
Excel can use that pretty well..
Check to ensure you are running npm install from the proper directory.
(The package.json file could be one extra directory down, for example.)
You can actually send it as JSON the following way:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
For posterity sake,the answer maybe too late.You should check for the return value of the variable and throw an exception. In that case you are assured that the program will jump from where the exception is being raised to the catch block. Find below.
try{
$tableAresults = $dbHandler->doSomethingWithTableA();
if (!tableAresults)
throw new Exception('Problem with tableAresults');
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if (!tableBresults)
throw new Exception('Problem with tableBresults');
} catch (Exception $e) {
echo $e->getMessage();
}
Use $ne
-- $not
should be followed by the standard operator:
An examples for $ne
, which stands for not equal:
use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }
And now $not
, which takes in predicate ($ne
) and negates it ($not
):
db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }
You should use static String.Compare
function like following
x => String.Compare (x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase) == 0
spans default to inline style, which you can't specify the width of.
display: inline-block;
would be a good way, except IE doesn't support it
you can, however, hack a multiple browser solution
why not use flexbox ? so wrap them into another div like that
.flexContainer { _x000D_
_x000D_
margin: 2px 10px;_x000D_
display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
<div style="margin:0;padding:0;display:inline">_x000D_
<input type="hidden" value="?" name="utf8">_x000D_
<input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
</div>_x000D_
<div class="flexContainer">_x000D_
<div class="left">Proj Name:</div>_x000D_
<div class="right">must have a name</div>_x000D_
</div>_x000D_
<div class="input string required"> </div>_x000D_
</form>
_x000D_
feel free to play with flex-basis percentage to get more customized space.
It's a little late but a slightly faster version of the accepted answer is below:
function formatBytes($bytes, $precision)
{
$unit_list = array
(
'B',
'KB',
'MB',
'GB',
'TB',
);
$bytes = max($bytes, 0);
$index = floor(log($bytes, 2) / 10);
$index = min($index, count($unit_list) - 1);
$bytes /= pow(1024, $index);
return round($bytes, $precision) . ' ' . $unit_list[$index];
}
It's more efficient, due to performing a single log-2 operation instead of two log-e operations.
It's actually faster to do the more obvious solution below, however:
function formatBytes($bytes, $precision)
{
$unit_list = array
(
'B',
'KB',
'MB',
'GB',
'TB',
);
$index_max = count($unit_list) - 1;
$bytes = max($bytes, 0);
for ($index = 0; $bytes >= 1024 && $index < $index_max; $index++)
{
$bytes /= 1024;
}
return round($bytes, $precision) . ' ' . $unit_list[$index];
}
This is because as the index is calculated at the same time as the value of the number of bytes in the appropriate unit. This cut the execution time by about 35% (a 55% speed increase).
You should \usepackage{longtable}
.