set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
i++ is known as Post Increment whereas ++i is called Pre Increment.
i++
i++
is post increment because it increments i
's value by 1 after the operation is over.
Lets see the following example:
int i = 1, j;
j = i++;
Here value of j = 1
but i = 2
. Here value of i
will be assigned to j
first then i
will be incremented.
++i
++i
is pre increment because it increments i
's value by 1 before the operation.
It means j = i;
will execute after i++
.
Lets see the following example:
int i = 1, j;
j = ++i;
Here value of j = 2
but i = 2
. Here value of i
will be assigned to j
after the i
incremention of i
.
Similarly ++i
will be executed before j=i;
.
For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one.. doesn't matter. It will execute your for loop same no. of times.
for(i=0; i<5; i++)
printf("%d ",i);
And
for(i=0; i<5; ++i)
printf("%d ",i);
Both the loops will produce same output. ie 0 1 2 3 4
.
It only matters where you are using it.
for(i = 0; i<5;)
printf("%d ",++i);
In this case output will be 1 2 3 4 5
.
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
Slice notation a[start_index:end_index:step]
return a[::2]
where start_index
defaults to 0
and end_index
defaults to the len(a)
.
First, create a empty DataFrame with column names, after that, inside the for loop, you must define a dictionary (a row) with the data to append:
df = pd.DataFrame(columns=['A'])
for i in range(5):
df = df.append({'A': i}, ignore_index=True)
df
A
0 0
1 1
2 2
3 3
4 4
If you want to add a row with more columns, the code will looks like this:
df = pd.DataFrame(columns=['A','B','C'])
for i in range(5):
df = df.append({'A': i,
'B': i * 2,
'C': i * 3,
}
,ignore_index=True
)
df
A B C
0 0 0 0
1 1 2 3
2 2 4 6
3 3 6 9
4 4 8 12
Try the bash
built-in help:
$ help for
for: for NAME [in WORDS ... ;] do COMMANDS; done
The `for' loop executes a sequence of commands for each member in a
list of items. If `in WORDS ...;' is not present, then `in "$@"' is
assumed. For each element in WORDS, NAME is set to that element, and
the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
Equivalent to
(( EXP1 ))
while (( EXP2 )); do
COMMANDS
(( EXP3 ))
done
EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is
omitted, it behaves as if it evaluates to 1.
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Something like this:
setUsers = function (data) {
for (k in data) {
user[k] = data[k];
}
}
for
(int i = 0; i < 8; i++)
It's a for
loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.
for (int i = 0; i < 8; i++)
Start by setting i = 0
for (int i = 0;i < 8; i++)
Continue looping while i < 8
.
for (int i = 0; i < 8;i++)
Every time you've been around the loop, increase i
by 1.
For example;
for (int i = 0; i < 8; i++)
do(i);
will call do(0), do(1), ... do(7) in order, and stop when i
reaches 8 (ie i < 8
is false)
You need to put the worksheet identifier in your range statements as shown below ...
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next
End Sub
Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub
Well, performance impact is mostly insignificant, but isn't zero. If you look at JavaDoc of RandomAccess
interface:
As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:
for (int i=0, n=list.size(); i < n; i++) list.get(i);
runs faster than this loop:
for (Iterator i=list.iterator(); i.hasNext();) i.next();
And for-each loop is using version with iterator, so for ArrayList
for example, for-each loop isn't fastest.
Because 1
is numeric, but not integer (i.e. it's a floating point number), and 1:6000
is numeric and integer.
> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"
60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:
> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow
3.6 billion is easily representable in floating point, however:
> as.single(60000)*as.single(60000)
[1] 3.6e+09
To fix your for
code, convert to a floating point representation:
function (N)
{
for(i in as.single(1:N)) {
y <- i*i
}
}
The easiest solution is to just run your own counter thus:
int i = 0;
for (String s : stringArray) {
doSomethingWith(s, i);
i++;
}
The reason for this is because there's no actual guarantee that items in a collection (which that variant of for
iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).
See for example, the following code:
import java.util.*;
public class TestApp {
public static void AddAndDump(AbstractSet<String> set, String str) {
System.out.println("Adding [" + str + "]");
set.add(str);
int i = 0;
for(String s : set) {
System.out.println(" " + i + ": " + s);
i++;
}
}
public static void main(String[] args) {
AbstractSet<String> coll = new HashSet<String>();
AddAndDump(coll, "Hello");
AddAndDump(coll, "My");
AddAndDump(coll, "Name");
AddAndDump(coll, "Is");
AddAndDump(coll, "Pax");
}
}
When you run that, you can see something like:
Adding [Hello]
0: Hello
Adding [My]
0: Hello
1: My
Adding [Name]
0: Hello
1: My
2: Name
Adding [Is]
0: Hello
1: Is
2: My
3: Name
Adding [Pax]
0: Hello
1: Pax
2: Is
3: My
4: Name
indicating that, rightly so, order is not considered a salient feature of a set.
There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.
Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:
l = locals()
for i in xrange(3):
exec("group" + str(i) + "= self.getGroup(selected, header + i)")
Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:
Class A(models.Model):
....
def __getitem__(self, item): # a.__getitem__('id')
#exec("attrb = self." + item)
#return attrb
return self.__dict__[item]
It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.
A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.
There are two problems with your attempt.
First, you've used n+1
instead of i+1
, so you're going to return something like [5, 5, 5, 5]
instead of [1, 2, 3, 4]
.
Second, you can't for
-loop over a number like n
, you need to loop over some kind of sequence, like range(n)
.
So:
def naturalNumbers(n):
return [i+1 for i in range(n)]
But if you already have the range
function, you don't need this at all; you can just return range(1, n+1)
, as arshaji showed.
So, how would you build this yourself? You don't have a sequence to loop over, so instead of for
, you have to build it yourself with while
:
def naturalNumbers(n):
results = []
i = 1
while i <= n:
results.append(i)
i += 1
return results
Of course in real-life code, you should always use for
with a range
, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range
function first, just to use it for naturalNumbers
. (It's already pretty close.)
There is one more option, if you want to get clever.
If you have a list, you can slice it. For example, the first 5 elements of my_list
are my_list[:5]
. So, if you had an infinitely-long list starting with 1
, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count
or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice
. So:
from itertools import count, islice
def naturalNumbers(n):
return list(islice(count(1), n))
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
This is another way:
end=5
for i in $(bash -c "echo {1..${end}}"); do echo $i; done
#/bin/bash
TESTSTR="abc,def,ghij"
for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done
I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.
other solution is to set IFS to certain separator
WHILE is more flexible. FOR is more concise in those instances in which it applies.
FOR is great for loops which have a counter of some kind, like
for (int n=0; n<max; ++n)
You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.
FOR can also work nicely with things other than a counter, of course. Like
for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())
Etc.
But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:
initializeList();
while (listHasMoreElements())
{
n=getCurrentElement();
int status=processElement(n);
if (status>0)
{
skipElements(status);
advanceElementPointer();
}
else
{
n=-status;
findElement(n);
}
}
That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.
In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).
Just in case, if someone is looking for a similar problem...
Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.
[print(i) for i in x]
BTW, the return values will be a list on None s.
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
Do you want to iterate over characters or words?
For words, you'll have to split the words first, such as
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index
This prints the index of the word.
For the absolute character position you'd need something like
chars = 0
for index, word in enumerate(loopme.split(" ")):
print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
chars += len(word) + 1
If copy assignment operator of foo and bar is cheap (eg. int, char, pointer etc), you can do the following:
foo f; bar b;
BOOST_FOREACH(boost::tie(f,b),testing)
{
cout << "Foo is " << f << " Bar is " << b;
}
Remove obj
and just do this inside your for loop:
arr.push(i);
Also, the i < yearEnd
condition will not include the final year, so change it to i <= yearEnd
.
You can also do it with recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
And a simple example for the string hello
:
reverse(hello)
= reverse(ello) + h # The recursive step
= reverse(llo) + e + h
= reverse(lo) + l + e + h
= reverse(o) + l + l + e + h # Base case
= o + l + l + e + h
= olleh
I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.
import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
, password="***"
, port="5432"
, database="myDB"
, host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()
myList = [...]
for item in myList:
cursor_psql.execute('''
-- The query goes here
''')
connection_psql.commit()
cursor_psql.close()
System.out.println(result/count)
you can't do this because result/count is not a String type, and System.out.println() only takes a String parameter. perhaps try:
double avg = (double)result / (double)args.length
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.
You could use macros to simulate the repeat-until syntax.
#define repeat do
#define until(exp) while(!(exp))
Because your else
isn't attached to anything. The if
without braces only encompasses the single statement that immediately follows it.
if (choice==5)
{
System.out.println("End of Game\n Thank you for playing with us!");
break;
}
else
{
System.out.println("Not a valid choice!\n Please try again...\n");
}
Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.
In addition, using a switch
here would make more sense.
int choice;
boolean keepGoing = true;
while(keepGoing)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch(choice)
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
// your other cases
// ...
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
keepGoing = false;
break;
default:
System.out.println("Not a valid choice!\n Please try again...\n");
}
}
Note that instead of an infinite for
loop I used a while(boolean)
, making it easy to exit the loop. Another approach would be using break with labels.
It's an old question but the solution below (without a for loop) might be helpful:
def new_fun(df):
prev_value = df.iloc[0]["C"]
def func2(row):
# non local variable ==> will use pre_value from the new_fun function
nonlocal prev_value
new_value = prev_value * row['A'] + row['B']
prev_value = row['C']
return new_value
# This line might throw a SettingWithCopyWarning warning
df.iloc[1:]["C"] = df.iloc[1:].apply(func2, axis=1)
return df
df = new_fun(df)
As for infinite loops for(;;)
loop is better than while(1)
since while
evaluates every time the condition but again it depends on the compiler.
Since nobody else has actually tackled Could someone please explain this to me?
I believe I will:
j++
is shorthand, it's not an actual operation (ok it really IS, but bear with me for the explanation)
j++
is really equal to the operation j = j + 1;
except it's not a macro or something that does inline replacement. There are a lot of discussions on here about the operations of i+++++i
and what that means (because it could be intepreted as i++ + ++i
OR (i++)++ + i
Which brings us to: i++
versus ++i
. They are called the post-increment
and pre-increment
operators. Can you guess why they are so named? The important part is how they're used in assignments. For instance, you could do: j=i++;
or j=++i;
We shall now do an example experiment:
// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;
// yes we could have already set the value to 5 before, but I chose not to.
i = 5;
j = i++;
k = ++i;
print(i, j, k);
//pretend this command prints them out nicely
//to the console screen or something, it's an example
What are the values of i, j, and k?
I'll give you the answers and let you work it out ;)
i = 7, j = 5, k = 7;
That's the power of the pre and post increment operators, and the hazards of using them wrong. But here's the alternate way of writing that same order of operations:
// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;
// yes we could have already set the value to 5 before, but I chose not to.
i = 5;
j = i;
i = i + 1; //post-increment
i = i + 1; //pre-increment
k = i;
print(i, j, k);
//pretend this command prints them out nicely
//to the console screen or something, it's an example
Ok, now that I've shown you how the ++
operator works, let's examine why it doesn't work for j+3
... Remember how I called it a "shorthand" earlier? That's just it, see the second example, because that's effectively what the compiler does before using the command (it's more complicated than that, but that's not for first explanations). So you'll see that the "expanded shorthand" has i =
AND i + 1
which is all that your request has.
This goes back to math. A function is defined where f(x) = mx + b
or an equation y = mx + b
so what do we call mx + b
... it's certainly not a function or equation. At most it is an expression. Which is all j+3
is, an expression. An expression without assignment does us no good, but it does take up CPU time (assuming the compiler doesn't optimize it out).
I hope that clarifies things for you and gives you some room to ask new questions. Cheers!
Let me add another solution:
>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f =
'f1'
'f2'
'f3'
'f4'
'f5'
If N
is more than two digits long (>= 10
), you will start getting extra spaces. Add a call to strtrim(f)
to get rid of them.
As a bonus, there is an undocumented built-in function sprintfc
which nicely returns a cell arrays of strings:
>> N = 10;
>> f = sprintfc('f%d', 1:N)
f =
'f1' 'f2' 'f3' 'f4' 'f5' 'f6' 'f7' 'f8' 'f9' 'f10'
if I got it right, you can try
for item in [x for x in checklist if x not in mylist]:
print (item)
I know rather old question but....came across looking other thing so I give my shot:
[each*2 for each in [1,2,3,4,5] if each % 10 == 0])
A simple way to find unique common elements of lists a and b:
a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
print(both)
To iterate through all files and folders you can use
for /F "delims=" %%a in ('dir /b /s') do echo %%a
To iterate through all folders only not with files, then you can use
for /F "delims=" %%a in ('dir /a:d /b /s') do echo %%a
Where /s
will give all results throughout the directory tree in unlimited depth. You can skip /s
if you want to iterate through the content of that folder not their sub folder
To iterate through a particular named files and folders you can search for the name and iterate using for loop
for /F "delims=" %%a in ('dir "file or folder name" /b /s') do echo %%a
To iterate through a particular named folders/directories and not files, then use /AD
in the same command
for /F "delims=" %%a in ('dir "folder name" /b /AD /s') do echo %%a
Null check in an enhanced for loop
public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
return iterable == null ? Collections.<T>emptyList() : iterable;
}
Then use:
for (Object object : emptyIfNull(someList)) { ... }
Very simple example:
def loadById(self, id):
if id in range(len(self.itemList)):
self.load(self.itemList[id])
I can't think of a solution that does not use the range-len composition quickly.
But probably instead this should be done with try .. except
to stay pythonic i guess..
The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)
The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential
If you want your loop to be executed in parallel you could simply write
joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
You will have to write some extra code for thread handling etc.
Note: For my answer I assumed joins implementing the java.util.Stream
interface. If joins implements only the java.util.Iterable
interface this is no longer true.
Since you are always initialising self.listMyData
to an empty list in clkFindMost
your code will always lead to this error* because after that both unique_names
and frequencies
are empty iterables, so fix this.
Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.
Lastly dict.get
is a method not a list or dictionary so you can't use []
with it:
Correct way is:
if frequencies.get(name):
And Pythonic way is:
if name in frequencies:
The Pythonic way to get the frequency of items is to use collections.Counter
:
from collections import Counter #Add this at the top of file.
def clkFindMost(self, parent):
#self.listMyData = []
if self.listMyData:
frequencies = Counter(self.listMyData)
self.txtResults.Value = max(frequencies, key=frequencies.get)
else:
self.txtResults.Value = ''
max()
and min()
throw such error when an empty iterable is passed to them. You can check the length of v
before calling max()
on it.
>>> lst = []
>>> max(lst)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
mx = max(lst)
else:
#Handle this here
If you are using it with an iterator then you need to consume the iterator first before calling max()
on it because boolean value of iterator is always True
, so we can't use if
on them directly:
>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
mx = max(lst)
else:
#Handle this here
Good news is starting from Python 3.4 you will be able to specify an optional return value for min()
and max()
in case of empty iterable.
This should do it:
[entry for tag in tags for entry in entries if tag in entry]
There is a reason for this: performance. i++ generates a copy, and that's a waste if you immediately discard it. Granted, the compiler can optimize away this copy if i
is a primitive, but it can't if it isn't. See this question.
If you have an existing list and you want to loop over it and keep track of the indices you can use the enumerate
function. For example
l = ["apple", "pear", "banana"]
for i, fruit in enumerate(l):
print "index", i, "is", fruit
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[@name="genderS"]:checked').val();
anymore, which was working in jQuery 1.7 (with the @).
In your case you can do that without using push
at all:
var myArray = [
[1,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1]
]
var newRows = 8;
var newCols = 7;
var item;
for (var i = 0; i < newRows; i++) {
item = myArray[i] || (myArray[i] = []);
for (var k = item.length; k < newCols; k++)
item[k] = 0;
}
See "Is there a way to define variables of two types in for loop?" for another way involving nesting multiple for loops. The advantage of the other way over Georg's "struct trick" is that it (1) allows you to have a mixture of static and non-static local variables and (2) it allows you to have non-copyable variables. The downside is that it is far less readable and may be less efficient.
Although that question is pretty old, I came here via google and I found a quite simple way: List slicing. Let's say you want to put an '&' between all list entries.
s = ""
l = [1, 2, 3]
for i in l[:-1]:
s = s + str(i) + ' & '
s = s + str(l[-1])
This returns '1 & 2 & 3'.
We can break both a $(selector).each()
loop and a $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false
is the same as a continue statement in a for
loop; it will skip immediately to the next iteration.
return false; // this is equivalent of 'break' for jQuery loop
return; // this is equivalent of 'continue' for jQuery loop
Note that $(selector).each()
and $.each()
are different functions.
References:
I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:
{% for basename, perms in permsByBasenames %}
{% if basename == 'agency' %}
{# do nothing #}
{% else %}
<a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
{% endif %}
{% endfor %}
OR I simply skip it if it doesn't meet my criteria:
{% for tr in time_reports %}
{% if not tr.isApproved %}
.....
{% endif %}
{% endfor %}
I got a situation like the code below
for(id<-0 to 99) {
try {
var symbol = ctx.read("$.stocks[" + id + "].symbol").toString
var name = ctx.read("$.stocks[" + id + "].name").toString
stocklist(symbol) = name
}catch {
case ex: com.jayway.jsonpath.PathNotFoundException=>{break}
}
}
I am using a java lib and the mechanism is that ctx.read throw a Exception when it can find nothing. I was trapped in the situation that :I have to break the loop when a Exception was thrown, but scala.util.control.Breaks.break using Exception to break the loop ,and it was in the catch block thus it was caught.
I got ugly way to solve this: do the loop for the first time and get the count of the real length. and use it for the second loop.
take out break from Scala is not that good,when you are using some java libs.
This has the same two answers as most "which is faster" questions:
1) If you don't measure, you don't know.
2) (Because...) It depends.
It depends on how expensive the "MoveNext()" method is, relative to how expensive the "this[int index]" method is, for the type (or types) of IEnumerable that you will be iterating over.
The "foreach" keyword is shorthand for a series of operations - it calls GetEnumerator() once on the IEnumerable, it calls MoveNext() once per iteration, it does some type checking, and so on. The thing most likely to impact performance measurements is the cost of MoveNext() since that gets invoked O(N) times. Maybe it's cheap, but maybe it's not.
The "for" keyword looks more predictable, but inside most "for" loops you'll find something like "collection[index]". This looks like a simple array indexing operation, but it's actually a method call, whose cost depends entirely on the nature of the collection that you're iterating over. Probably it's cheap, but maybe it's not.
If the collection's underlying structure is essentially a linked list, MoveNext is dirt-cheap, but the indexer might have O(N) cost, making the true cost of a "for" loop O(N*N).
As mentioned in all other answers, the keyword continue
will skip to the end of the current iteration.
Additionally you can label your loop starts and then use continue [labelname];
or break [labelname];
to control what's going on in nested loops:
loop1: for (int i = 1; i < 10; i++) {
loop2: for (int j = 1; j < 10; j++) {
if (i + j == 10)
continue loop1;
System.out.print(j);
}
System.out.println();
}
There can be a difference for loops. This is the practical application of post/pre-increment.
int i = 0;
while(i++ <= 10) {
Console.Write(i);
}
Console.Write(System.Environment.NewLine);
i = 0;
while(++i <= 10) {
Console.Write(i);
}
Console.ReadLine();
While the first one counts to 11 and loops 11 times, the second does not.
Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).
This can also be solved using a boolean.
For Each rngCol In rngAll.Columns
doCol = False '<==== Resets to False at top of each column
For Each cell In Selection
If cell.row = 1 Then
If thisColumnShouldBeProcessed Then doCol = True
End If
If doCol Then
'Do what you want to do to each cell in this column
End If
Next cell
Next rngCol
For example, here is the full example that:
(1) Identifies range of used cells on worksheet
(2) Loops through each column
(3) IF column title is an accepted title, Loops through all cells in the column
Sub HowToSkipForLoopIfConditionNotMet()
Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
Set rngAll = Range("A1").CurrentRegion
'MsgBox R.Address(0, 0), , "All data"
cnt = 0
For Each rngCol In rngAll.Columns
rngCol.Select
doCol = False
For Each cell In Selection
If cell.row = 1 Then
If cell.Value = "AnAllowedColumnTitle" Then doCol = True
End If
If doCol Then '<============== THIS LINE ==========
cnt = cnt + 1
Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
End If
Next cell
Next rngCol
End Sub
Note: If you didn't immediately catch it, the line If docol Then
is your inverted CONTINUE. That is, if doCol
remains False, the script CONTINUES to the next cell and doesn't do anything.
Certainly not as fast/efficient as a proper continue
or next for
statement, but the end result is as close as I've been able to get.
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Old way (if you don't now the length of arguments/parameters)
>> function sumla1(){
result=0
for(let i=0; i<arguments.length;i++){
result+=arguments[i];
}
return result;
}
>> sumla1(45,67,88);
>> 200
ES6 (destructuring of array)
>> function sumla2(...x){return x.reduce((a,b)=>a+b)}
>>
>> sumla2(5,5,6,7,8)
>>
>> 31
>>
>> var numbers = [4, 9, 16, 25];
>> sumla2(...numbers);
>> 54
So I realize this is kind of old, but after much Googling, I couldn't find an answer I was happy with, so I came up with my own solution for breaking a FOR loop that immediately stops iteration, and thought I'd share it.
It requires the loop to be in a separate file, and exploits a bug in CMD error handling to immediately crash the batch processing of the loop file when redirecting the STDOUT of DIR to STDIN.
MainFile.cmd
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO.
ECHO After LOOP
PAUSE
LOOP.cmd
FOR /L %%A IN (1,1,10) DO (
ECHO %%A
IF %%A EQU 3 DIR >&0 2>NUL )
)
When run, this produces the following output. You'll notice that both iteration and execution of the loop stops when %A = 3.
:>MainFile.cmd
:>ECHO Simple test demonstrating loop breaking.
Simple test demonstrating loop breaking.
:>ECHO.
:>CMD /C Z:\LOOP.cmd
:>FOR /L %A IN (1 1 10) DO (
ECHO %A
IF %A EQU 3 DIR 1>&0 2>NUL
)
:>(
ECHO 1
IF 1 EQU 3 DIR 1>&0 2>NUL
)
1
:>(
ECHO 2
IF 2 EQU 3 DIR 1>&0 2>NUL
)
2
:>(
ECHO 3
IF 3 EQU 3 DIR 1>&0 2>NUL
)
3
:>ECHO.
:>ECHO After LOOP
After LOOP
:>PAUSE
Press any key to continue . . .
If you need to preserve a single variable from the loop, have the loop ECHO the result of the variable, and use a FOR /F loop in the MainFile.cmd to parse the output of the LOOP.cmd file.
Example (using the same LOOP.cmd file as above):
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
FOR /F "delims=" %%L IN ('CMD /C %~dp0\LOOP.cmd') DO SET VARIABLE=%%L
ECHO After LOOP
ECHO.
ECHO %VARIABLE%
ECHO.
PAUSE
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
3
Press any key to continue . . .
If you need to preserve multiple variables, you'll need to redirect them to temporary files as shown below.
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO After LOOP
ECHO.
SET /P VARIABLE1=<%TEMP%\1
SET /P VARIABLE2=<%TEMP%\2
ECHO %VARIABLE1%
ECHO %VARIABLE2%
ECHO.
PAUSE
LOOP.cmd
@ECHO OFF
FOR /L %%A IN (1,1,10) DO (
IF %%A EQU 1 ECHO ONE >%TEMP%\1
IF %%A EQU 2 ECHO TWO >%TEMP%\2
IF %%A EQU 3 DIR >&0 2>NUL
)
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
ONE
TWO
Press any key to continue . . .
I hope others find this useful for breaking loops that would otherwise take too long to exit due to continued iteration.
for (var i = 0; i < 10; i = i + 2) {
// code here
}?
for i in count:
means for i in 7:
, which won't work. The bit after the in
should be of an iterable type, not a number. Try this:
for i in range(count):
The best answer here is to use all()
, which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:
>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
Note that all(flag == 0 for (_, _, flag) in items)
is directly equivalent to all(item[2] == 0 for item in items)
, it's just a little nicer to read in this case.
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
If you want to check at least one element is 0, the better option is to use any()
which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
bool breakInnerLoop=false
for(int i=0;i<=10;i++)
{
for(int J=0;i<=10;i++)
{
if(i<=j)
{
breakInnerLoop=true;
break;
}
}
if(breakInnerLoop)
{
continue
}
}
There are some already defined data types which allows us to iterate over them easily e.g Array, Map, String Objects
Normal for in iterates over the iterator and in response provides us with the keys that are in the order of insertion as shown in below example.
const numbers = [1,2,3,4,5];
for(let number in number) {
console.log(number);
}
// result: 0, 1, 2, 3, 4
Now if we try same with for of, then in response it provides us with the values not the keys. e.g
const numbers = [1,2,3,4,5];
for(let numbers of numbers) {
console.log(number);
}
// result: 1, 2, 3, 4, 5
So looking at both of the iterators we can easily differentiate the difference between both of them.
Note:- For of only works with the Symbol.iterator
So if we try to iterate over normal object, then it will give us an error e.g-
const Room = {
area: 1000,
height: 7,
floor: 2
}
for(let prop in Room) {
console.log(prop);
}
// Result area, height, floor
for(let prop of Room) {
console.log(prop);
}
Room is not iterable
Now for iterating over we need to define an ES6 Symbol.iterator e.g
const Room= {
area: 1000, height: 7, floor: 2,
[Symbol.iterator]: function* (){
yield this.area;
yield this.height;
yield this.floors;
}
}
for(let prop of Room) {
console.log(prop);
}
//Result 1000, 7, 2
This is the difference between For in and For of. Hope that it might clear the difference.
Probably you want something like:
firstline = True
for row in kidfile:
if firstline: #skip first line
firstline = False
continue
# parse the line
An other way to achive the same result is calling readline
before the loop:
kidfile.readline() # skip the first line
for row in kidfile:
#parse the line
To switch to C99 mode in CodeBlocks, follow the next steps:
Click Project/Build options, then in tab Compiler Settings choose subtab Other options, and place -std=c99
in the text area, and click Ok.
This will turn C99 mode on for your Compiler.
I hope this will help someone!
def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
As with list.sort() and random.shuffle this does NOT return
"""
changed = True
while changed:
changed = False
for i in xrange(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return None
if __name__ == "__main__":
"""Sample usage and simple test suite"""
from random import shuffle
testset = range(100)
testcase = testset[:] # make a copy
shuffle(testcase)
assert testcase != testset # we've shuffled it
bubble_sort(testcase)
assert testcase == testset # we've unshuffled it back into a copy
.forEach
already has this ability:
const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
});
But if you want the abilities of for...of
, then you can map
the array to the index and value:
for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
console.log(index); // 0, 1, 2
console.log(value); // 9, 2, 5
}
That's a little long, so it may help to put it in a reusable function:
function toEntries<T>(a: T[]) {
return a.map((value, index) => [index, value] as const);
}
for (const [index, value] of toEntries(someArray)) {
// ..etc..
}
Iterable Version
This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration
compiler option.
function* toEntries<T>(values: T[] | IterableIterator<T>) {
let index = 0;
for (const value of values) {
yield [index, value] as const;
index++;
}
}
Array.prototype.entries() - ES6+
If you are able to target ES6+ environments then you can use the .entries()
method as outlined in Arnavion's answer.
I've found that in the majority of cases doing block clauses on one line is a bad idea.
It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.
In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:
newlist = [splitColon.split(a) for a in someList]
although unless you need a reusable list specifically you may want to consider using a generator instead
listgen = (splitColon.split(a) for a in someList)
note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.
There is also a built in ternary operator in modern versions of python that allow you to do things like
string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print
or
iterator = max_value if iterator > max_value else iterator
Some people may find these more readable and usable than the similar if (condition):
block.
When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input
with input
.
Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:
IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;
The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).
I disagree!
Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.
I think it makes more sense to have your checks at the top of your for loop like so
for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}
or if you need to process the row first
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}
This way you can write a function to perform everything and make much cleaner code.
for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
Or if your condition is complicated you can move that code out too!
for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
DoAllThatCrazyStuff(myCollection[i]);
}
"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)
for(i=0;i<=5;i++)_x000D_
{_x000D_
for(j=0;j<=i;j++)_x000D_
{_x000D_
document.write('*');_x000D_
}_x000D_
document.write('<br>')_x000D_
}
_x000D_
You can't, because IEnumerable
doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue
elements (or long.MaxValue
if you use a long
index), you can:
Don't use foreach, and use a for
loop, converting your IEnumerable
to a generic enumerable first:
var genericList = list.Cast<object>();
for(int i = 0; i < genericList.Count(); ++i)
{
var row = genericList.ElementAt(i);
/* .... */
}
Have an external index:
int i = 0;
foreach(var row in list)
{
/* .... */
++i;
}
Get the index via Linq:
foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
{
var row = rowObject.Row;
var i = rowObject.Index;
/* .... */
}
In your case, since your IEnumerable
is not a generic one, I'd rather use the foreach
with external index (second method)... otherwise, you may want to make the Cast<object>
outside your loop to convert it to an IEnumerable<object>
.
Your datatype is not clear from the question, but I'm assuming object
since it's an items source (it could be DataGridRow
)... you may want to check if it's directly convertible to a generic IEnumerable<object>
without having to call Cast<object>()
, but I'll make no such assumptions.
The concept of an "index" is foreign to an IEnumerable
. An IEnumerable
can be potentially infinite. In your example, you are using the ItemsSource
of a DataGrid
, so more likely your IEnumerable
is just a list of objects (or DataRows
), with a finite (and hopefully less than int.MaxValue
) number of members, but IEnumerable
can represent anything that can be enumerated (and an enumeration can potentially never end).
Take this example:
public static IEnumerable InfiniteEnumerable()
{
var rnd = new Random();
while(true)
{
yield return rnd.Next();
}
}
So if you do:
foreach(var row in InfiniteEnumerable())
{
/* ... */
}
Your foreach
will be infinite: if you used an int
(or long
) index, you'll eventually overflow it (and unless you use an unchecked
context, it'll throw an exception if you keep adding to it: even if you used unchecked
, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).
So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.
var arr = [1, 2, 3, 1023, 1024];
for (var value; value = arr.pop();) {
value + 1
}
http://jsperf.com/native-loop-performance/8
Comparing methods for looping through an array of 100000 items and do a minimal operation with the new value each time.
Preparation:
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
// Fake function with minimal action on the value
var tmp = 0;
var process = function(value) {
tmp = value; // Hold a reference to the variable (prevent engine optimisation?)
};
// Declare the test Array
var arr = [];
for (var i = 0; i < 100000; i++)
arr[i] = i;
};
</script>
Tests:
<a href="http://jsperf.com/native-loop-performance/16"
title="http://jsperf.com/native-loop-performance/16"
><img src="http://i.imgur.com/YTrO68E.png" title="Hosted by imgur.com" /></a>
How would you write this for-each loop a different way so as to not incorporate the ":"?
Assuming that list
is a Collection
instance ...
public String toString() {
String cardString = "";
for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
PlayingCard c = it.next();
cardString = cardString + c + "\n";
}
}
I should add the pedantic point that :
is not an operator in this context. An operator performs an operation in an expression, and the stuff inside the ( ... )
in a for
statement is not an expression ... according to the JLS.
var text ="";
for (var member in list) {
text += list[member];
}
You should use 'zip' function. Here is an example how your own zip function can look like
def custom_zip(seq1, seq2):
it1 = iter(seq1)
it2 = iter(seq2)
while True:
yield next(it1), next(it2)
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2
, so you do not need a loop at all, just use the formula n*(n+1)/2
.
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
As of 2016 (ES6) we may use for…of
for array iteration, as John Slegers already noticed.
I would just like to add this simple demonstration code, to make things clearer:
Array.prototype.foo = 1;
var arr = [];
arr[5] = "xyz";
console.log("for...of:");
var count = 0;
for (var item of arr) {
console.log(count + ":", item);
count++;
}
console.log("for...in:");
count = 0;
for (var item in arr) {
console.log(count + ":", item);
count++;
}
The console shows:
for...of:
0: undefined
1: undefined
2: undefined
3: undefined
4: undefined
5: xyz
for...in:
0: 5
1: foo
In other words:
for...of
counts from 0 to 5, and also ignores Array.prototype.foo
. It shows array values.
for...in
lists only the 5
, ignoring undefined array indexes, but adding foo
. It shows array property names.
for (i,j) in [(i,j) for i in range(x) for j in range(y)]
should do it.
None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.
The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.
Use a regular for loop and format the index to be used in the selector.
var array = [];
for (var i = 0; i < 4; i++) {
var selector = '' + i;
if (selector.length == 1)
selector = '0' + selector;
selector = '#event' + selector;
array.push($(selector, response).html());
}
One thing to watch out for in benchmarks (especially phpbench.com), is even though the numbers are sound, the tests are not. Alot of the tests on phpbench.com are doing things at are trivial and abuse PHP's ability to cache array lookups to skew benchmarks or in the case of iterating over an array doesn't actually test it in real world cases (no one writes empty for loops). I've done my own benchmarks that I've found are fairly reflective of the real world results and they always show the language's native iterating syntax foreach
coming out on top (surprise, surprise).
//make a nicely random array
$aHash1 = range( 0, 999999 );
$aHash2 = range( 0, 999999 );
shuffle( $aHash1 );
shuffle( $aHash2 );
$aHash = array_combine( $aHash1, $aHash2 );
$start1 = microtime(true);
foreach($aHash as $key=>$val) $aHash[$key]++;
$end1 = microtime(true);
$start2 = microtime(true);
while(list($key) = each($aHash)) $aHash[$key]++;
$end2 = microtime(true);
$start3 = microtime(true);
$key = array_keys($aHash);
$size = sizeOf($key);
for ($i=0; $i<$size; $i++) $aHash[$key[$i]]++;
$end3 = microtime(true);
$start4 = microtime(true);
foreach($aHash as &$val) $val++;
$end4 = microtime(true);
echo "foreach ".($end1 - $start1)."\n"; //foreach 0.947947025299
echo "while ".($end2 - $start2)."\n"; //while 0.847212076187
echo "for ".($end3 - $start3)."\n"; //for 0.439476966858
echo "foreach ref ".($end4 - $start4)."\n"; //foreach ref 0.0886030197144
//For these tests we MUST do an array lookup,
//since that is normally the *point* of iteration
//i'm also calling noop on it so that PHP doesn't
//optimize out the loopup.
function noop( $value ) {}
//Create an array of increasing indexes, w/ random values
$bHash = range( 0, 999999 );
shuffle( $bHash );
$bstart1 = microtime(true);
for($i = 0; $i < 1000000; ++$i) noop( $bHash[$i] );
$bend1 = microtime(true);
$bstart2 = microtime(true);
$i = 0; while($i < 1000000) { noop( $bHash[$i] ); ++$i; }
$bend2 = microtime(true);
$bstart3 = microtime(true);
foreach( $bHash as $value ) { noop( $value ); }
$bend3 = microtime(true);
echo "for ".($bend1 - $bstart1)."\n"; //for 0.397135972977
echo "while ".($bend2 - $bstart2)."\n"; //while 0.364789962769
echo "foreach ".($bend3 - $bstart3)."\n"; //foreach 0.346374034882
Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
let arr = [1,2,3,4,5];
for (let ele of arr) {
if (ele > 3) break;
console.log(ele);
}
C++ does not have the for_each
loop feature in its syntax. You have to use c++11 or use the template function std::for_each
.
struct Function {
int input;
Function(int input): input(input) {}
void operator()(Attack& attack) {
if(attack->m_num == input) attack->makeDamage();
}
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);
Break any number of loops by just one bool
variable see below :
bool check = true;
for (unsigned int i = 0; i < 50; i++)
{
for (unsigned int j = 0; j < 50; j++)
{
for (unsigned int k = 0; k < 50; k++)
{
//Some statement
if (condition)
{
check = false;
break;
}
}
if (!check)
{
break;
}
}
if (!check)
{
break;
}
}
In this code we break;
all the loops.
Using node I have a collection of stuff @stuff
and access it like this:
- each stuff in stuffs
p
= stuff.sentence
for(n in 1:5) {
if(n==3) next # skip 3rd iteration and go to next iteration
cat(n)
}
Great answers are:
My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):
x = 2
while x > 3:
print("foo")
break
else:
print("boo")
has the same flow (excluding low level differences) as:
x = 2
if x > 3:
print("foo")
else:
print("boo")
The point is that if-else can be considered as syntactic sugar for while-else which has implicit break
at the end of its if
block. The opposite implication, that while
loop is extension to if
, is more common (it's just repeated/looped conditional check), because if
is often taught before while
. However that isn't true because that would mean else
block in while-else would be executed each time when condition is false.
To ease your understanding think of it that way:
Without
break
,return
, etc., loop ends only when condition is no longer true and in such caseelse
block will also execute once. In case of Pythonfor
you must consider C-stylefor
loops (with conditions) or translate them towhile
.
Another note:
Premature
break
,return
, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.
A fun, simple solution:
for (int i = 0; i < 5; i++)
System.out.println(" *********".substring(i, 5 + 2*i));
Late, but can be done by using Object.keys like,
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
If I want to exit a for-to loop, I just set the index beyond the limit:
For i = 1 To max
some code
if this(i) = 25 Then i = max + 1
some more code...
Next`
Poppa.
In list comprehension the loop variable i becomes global. After the iteration in the for loop it is a reference to the last element in your list.
If you want all matches then assign the list to a variable:
filtered = [ i for i in my_list if i=='two']
If you want only the first match you could use a function generator
try:
m = next( i for i in my_list if i=='two' )
except StopIteration:
m = None
Have a max int and set it to the first value in the array. Then in a for loop iterate through the whole array and see if the max int is larger than the int at the current index.
int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}
}
I had a similar issue that cropped up when using tight_layout
for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle
at a certain distance above your top subplot:
import matplotlib.pyplot as plt
n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)
#make plots ...
# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)
For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.
No, you can't name the tuple members.
The in-between would be to use ExpandoObject instead of Tuple.
suitable for tcsh .alias file:
alias gisrc 'grep -I -r -i --exclude="*\.svn*" --include="*\."{mm,m,h,cc,c} \!* *'
Took me a while to figure out that the {mm,m,h,cc,c} portion should NOT be inside quotes. ~Keith
The reason your code fails is because post()
will start an asynchronous request to the server. What that means for you is that post()
returns immediately, not after the request completes, like you are expecting.
What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,
var it_works = false;
$.ajax({
url: 'some_file.php',
async: false, # makes request synchronous
success: function() {
it_works = true;
}
});
alert(it_works);
Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree
mysql cli - create database db2
linux cli - cp db1 db2
I had the same problem 2 years ago and I solved it in the following way:
1) I build my projects with makefiles, not managed by eclipse 2) I use a SAMBA connection to edit the files inside Eclipse 3) Building the project: Eclipse calles a "local" make with a makefile which opens a SSH connection to the Linux Host. On the SSH command line you can give parameters which are executed on the Linux host. I use for that parameter a makeit.sh shell script which call the "real" make on the linux host. The different targets for building you can give also by parameters from the local makefile --> makeit.sh --> makefile on linux host.
I show you my example with modal windows...you create your modal and give it an id then In your table you have tr section, just ad the first line you see below (don't forget to set the on the first row like this
<tr onclick="input" data-toggle="modal" href="#the name for my modal windows" >
<td><label>Some value here</label></td>
</tr>
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
or better:
baos.toString( codepage );
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
I think the problem happened when you use rbenv. Try the below commands to fix it.
rbenv shell {rb_version}
rbenv global {rb_version}
or
rbenv local {rb_version}
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
encodeURIComponent doesn't encode -_.!~*'()
, causing problem in posting data to php in xml string.
For example:
<xml><text x="100" y="150" value="It's a value with single quote" />
</xml>
General escape with encodeURI
%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E
You can see, single quote is not encoded. To resolve issue I created two functions to solve issue in my project, for Encoding URL:
function encodeData(s:String):String{
return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}
For Decoding URL:
function decodeData(s:String):String{
try{
return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
}catch (e:Error) {
}
return "";
}
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
Let's take two questions, example string "2014-04-08 12:30"
How can I obtain a LocalDateTime instance from the given string?
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
// Parsing or conversion
final LocalDateTime dt = LocalDateTime.parse("2014-04-08 12:30", formatter)
dt
should allow you to all date-time related operations
How can I then convert the LocalDateTime instance back to a string with the same format?
final String date = dt.format(formatter)
Well, you can always "give up" :)
function b(val){
return (val==null || val===false);
}
Add vertical-align: middle;
to the td
element that contains the button
<td style="vertical-align:middle;"> <--add this to center vertically
<a href="#" class="btn btn-primary">
<i class="icon-check icon-white"></i>
</a>
</td>
HTML Code
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" class="send_upload" value="upload" />
jQuery Code using bind method
$(document).ready(function() {
$('#upload').bind("click",function()
{ if(!$('#uploadImage').val()){
alert("empty");
return false;} }); });
My app uses a ListView in portraint mode which is simply switches to Gallery in landscape mode. Both of them use one BaseAdapter. This looks like shown below.
setContentView(R.layout.somelayout);
orientation = getResources().getConfiguration().orientation;
if ( orientation == Configuration.ORIENTATION_LANDSCAPE )
{
Gallery gallery = (Gallery)findViewById( R.id.somegallery );
gallery.setAdapter( someAdapter );
gallery.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view,
int position, long id ) {
onClick( position );
}
});
}
else
{
setListAdapter( someAdapter );
getListView().setOnScrollListener(this);
}
To handle scrolling events I've inherited my own widget from Gallery and override onFling(). Here's the layout.xml:
<view
class="package$somegallery"
android:id="@+id/somegallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</view>
and code:
public static class somegallery extends Gallery
{
private Context mCtx;
public somegallery(Context context, AttributeSet attrs)
{
super(context, attrs);
mCtx = context;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
( (CurrentActivity)mCtx ).onScroll();
return super.onFling(e1, e2, velocityX, velocityY);
}
}
Obviously, the standard library provided operator does not know what to do with your user defined type mystruct
. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator <<
to take your user defined data type.
Recommend using an npm package such as https://github.com/davetemplin/async-file, as compared to custom functions. For example:
import * as fs from 'async-file';
await fs.rename('/tmp/hello', '/tmp/world');
await fs.appendFile('message.txt', 'data to append');
await fs.access('/etc/passd', fs.constants.R_OK | fs.constants.W_OK);
var stats = await fs.stat('/tmp/hello', '/tmp/world');
Other answers are outdated
Try using matplotlib.pyplot.ticklabel_format
:
import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
This applies scientific notation (i.e. a x 10^b
) to your x-axis tickmarks
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
The three ways are:
//NSArray
NSArray *arrData = @[@1,@2,@3,@4];
// 1.Classical
for (int i=0; i< [arrData count]; i++){
NSLog(@"[%d]:%@",i,arrData[i]);
}
// 2.Fast iteration
for (id element in arrData){
NSLog(@"%@",element);
}
// 3.Blocks
[arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"[%lu]:%@",idx,obj);
// Set stop to YES in case you want to break the iteration
}];
You will have to be careful binding the UI to your custom collection -- the Default CollectionView class only supports single notification of items.
if you use jquery you can do like this. from this site Placeholder with Jquery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
these are the alternate links
You can use
$_FILES['filename']['error'];
If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done
1 : if file size is over limit .... You can find other options by googling
you can simply write the following command in the terminal of your linux system and get the java path :- echo $JAVA_HOME
In addition to this answer, note that in Node.js if you access JSON with the array syntax []
all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:
And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?
The documentation is misleading.
I have the following code running in production
DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
SET @sql = 'SELECT UserID FROM UserTable'
*/
INSERT INTO @table
EXEC(@sql)
SELECT * FROM @table
You're applying your class to the <a>
elements, which aren't siblings because they're each enclosed in an <li>
element. You need to move up the tree to the parent <li>
and find the ` elements in the siblings at that level.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().find('a').removeClass('current');
});
See this updated fiddle
I found squashing more useful than filter-branch
. I did the following:
git reset
--soft HEAD~3
. git commit -m
"New message for the combined commit"
Special case (from user @lituo): If above doesn't work, then you may have this case. Commit 1 included the large file and Commit 1's push failed due to large file error. Commit 2 removed the large file by git rm --cached [file_name]
but Commit 2's push still failed. You can follow the same steps above but instead of using HEAD~3
, use HEAD~2
.
git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.
You can find it inside the /config folder.
When you eject you get a message like:
Adding /config/webpack.config.dev.js to the project
Adding /config/webpack.config.prod.js to the project
You can use git hooks for that. Just create a hook that pushes changed to the other repo after an update.
Of course you might get merge conflicts so you have to figure how to deal with them.
You must define the class before creating an instance of the class. Move the invocation of Something
to the end of the script.
You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:
Here's the extension method way of doing it.
public static class Extensions
{
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(input, "");
}
}
If you would like to output array within string using puts
, you will get the same result as if you were using print
:
puts "#{[0, 1, nil]}":
[0, 1, nil]
But if not withing a quoted string then yes. The only difference is between new line when we use puts
.
Cache-Control: no-cache, no-store
These two header values can be combined to get the required effect on both IE and Firefox
Modify MainActivity
like this,
@Override
protected String getMainComponentName() {
return "Bananas"; // here
}
whenever you need to use the ScrollView as parent, And you also use the scroll movement method with TextView.
And When you portrait to landscape your device that time occur some issue. (like) entire page is scrollable but scroll movement method can't work.
if you still need to use ScrollView as parent or scroll movement method then you also use below desc.
If you do not have any problems then you use EditText instead of TextView
see below :
<EditText
android:id="@+id/description_text_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:editable="false"
android:cursorVisible="false"
android:maxLines="6"/>
Here, the EditText behaves like TextView
And your issue will be resolved
Here is how we can get last inserted id in Laravel 4
public function store()
{
$input = Input::all();
$validation = Validator::make($input, user::$rules);
if ($validation->passes())
{
$user= $this->user->create(array(
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
));
$lastInsertedId= $user->id; //get last inserted record's user id value
$userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
$user->update($userId); //update newly created record by storing the value of last inserted id
return Redirect::route('users.index');
}
return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
}
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character. And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
For a pure JS solution (no CSS classes), just set the transition
to 'none'
. To restore the transition as specified in the CSS, set the transition
to an empty string.
// Remove the transition
elem.style.transition = 'none';
// Restore the transition
elem.style.transition = '';
If you're using vendor prefixes, you'll need to set those too.
elem.style.webkitTransition = 'none'
Something simple like this can be done using subqueries in the select
clause:
select ((select sum(hours) from resource) +
(select sum(hours) from projects-time)
) as totalHours
For such a simple query as this, such a subselect is reasonable.
In some databases, you might have to add from dual
for the query to compile.
If you want to output each individually:
select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
If you want both and the sum, a subquery is handy:
select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
(select sum(hours) from projects-time) as ProjectHours
) t
A graphical overview (summary in a nutshell)
Since static classes are sealed, they cannot be inherited (except from Object), so the keyword protected is invalid on static classes.
For the defaults if you put no access modifier in front, see here:
Default visibility for C# classes and members (fields, methods, etc.)?
Non-nested
enum public
non-nested classes / structs internal
interfaces internal
delegates in namespace internal
class/struct member(s) private
delegates nested in class/struct private
Nested:
nested enum public
nested interface public
nested class private
nested struct private
Also, there is the sealed-keyword, which makes a class not-inheritable.
Also, in VB.NET, the keywords are sometimes different, so here a cheat-sheet:
WITH TEMP (DIA, SIGUIENTE_DIA ) AS
(SELECT
1,
CAST(@FECHAINI AS DATE)
FROM
DUAL
UNION ALL
SELECT
DIA,
DATEADD(DAY, DIA, SIGUIENTE_DIA)
FROM
TEMP
WHERE
DIA < DATEDIFF(DAY, @FECHAINI, @FECHAFIN)
AND DATEADD(DAY, 1, SIGUIENTE_DIA) <= CAST(@FECHAFIN AS DATE)
)
SELECT
SIGUIENTE_DIA AS CALENDARIO
FROM
TEMP
ORDER BY
SIGUIENTE_DIA
The detail is on the table DUAL but if your exchange this table for a dummy table this works.
Just remove this line from build.gradle(Project folder)
apply plugin: 'com.google.gms.google-services'
Now rebuild the application. works fine Happy coding
The following is what I did... But I'm pretty new to pandas and really Python in general, so no promises.
df = pd.DataFrame([[1, 2], [3, 4], [5,6]], columns=list('AB'))
newCol = [3,5,7]
newName = 'C'
values = np.insert(df.values,df.shape[1],newCol,axis=1)
header = df.columns.values.tolist()
header.append(newName)
df = pd.DataFrame(values,columns=header)
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
I can't believe the accepted answer has so many upvotes -- it's a horrible method.
Here's the correct way to do it, with date_trunc:
SELECT date_trunc('month', txn_date) AS txn_month, sum(amount) as monthly_sum
FROM yourtable
GROUP BY txn_month
It's bad practice but you might be forgiven if you use
GROUP BY 1
in a very simple query.
You can also use
GROUP BY date_trunc('month', txn_date)
if you don't want to select the date.
Yes, there is a difference. Html.ActionLink
generates an <a href=".."></a>
tag whereas Url.Action
returns only an url.
For example:
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
generates:
<a href="/somecontroller/someaction/123">link text</a>
and Url.Action("someaction", "somecontroller", new { id = "123" })
generates:
/somecontroller/someaction/123
There is also Html.Action which executes a child controller action.
may need to change the SCHEMA not only table
ALTER SCHEMA `<database name>` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);
(mariaDB 10)
Hope this will work for you!
You can use library(qpcR)
for combining two matrix with unequal size.
resultant_matrix <- qpcR:::cbind.na(matrix1, matrix2)
NOTE:- The resultant matrix will be of size of matrix2.
I'm actually very surprised that no one has given this solution:
Take a look at Stetho.
I've used Stetho on several occasions for different purposes (one of them being database inspection). On the actual website, they also talk about features for network inspection and looking through the view hierarchy.
It only requires a little setup: 1 gradle dependency addition (which you can comment out for production builds), a few lines of code to instantiate Stetho, and a Chrome browser (because it uses Chrome devtools for everything).
Update: You can now use Stetho to view Realm files (if you're using Realm instead of an SQLite DB): https://github.com/uPhyca/stetho-realm
Update #2: You can now use Stetho to view Couchbase documents: https://github.com/RobotPajamas/Stetho-Couchbase
Update #3: Facebook is focusing efforts on adding all Stetho features into its new tool, Flipper. Flipper already has many of the features that Stetho has. So, now may be a good time to make the switch. https://fbflipper.com/docs/stetho.html
The best approach from the response of Khemraj:
App class
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Declaration in the manifest
<application
android:name=".App"
...>
</application>
Constants class
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Using
textView.text = Localizations.info
Just a hunch, but check out this article on Django template loading. In particular, make sure you have django.template.loaders.app_directories.Loader
in your TEMPLATE_LOADERS list.
You can use -
$isTouch = isset($variable);
It will return true
if the $variable
is defined. if the variable is not defined it will return false
.
Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
If you want to check for false
, 0
etc You can then use empty()
-
$isTouch = empty($variable);
empty()
works for -
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
$(this).value
is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val()
.
Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:
Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."
He then implements an action filter that maps the JSON to C# objects with code shown.
public List<ItemCustom2> GetBrandListByCat(int id)
{
var OBJ = (from a in db.Items
join b in db.Brands on a.BrandId equals b.Id into abc1
where (a.ItemCategoryId == id)
from b in abc1.DefaultIfEmpty()
select new
{
ItemCategoryId = a.ItemCategoryId,
Brand_Name = b.Name,
Brand_Id = b.Id,
Brand_Pic = b.Pic,
}).Distinct();
List<ItemCustom2> ob = new List<ItemCustom2>();
foreach (var item in OBJ)
{
ItemCustom2 abc = new ItemCustom2();
abc.CategoryId = item.ItemCategoryId;
abc.BrandId = item.Brand_Id;
abc.BrandName = item.Brand_Name;
abc.BrandPic = item.Brand_Pic;
ob.Add(abc);
}
return ob;
}
Assuming you want to list grants on all objects a particular user has received:
select * from all_tab_privs_recd where grantee = 'your user'
This will not return objects owned by the user. If you need those, use all_tab_privs
view instead.
if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.
$('#shares').keyup(function(){
payment = 0;
calcTotal();
gtotal = ($('#shares').val() * 1) + payment;
gtotal = gtotal.toFixed(2);
$('#shares').val('');
$("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
});
You can try onload event as well;
var createIframe = function (src) {
var self = this;
$('<iframe>', {
src: src,
id: 'iframeId',
frameborder: 1,
scrolling: 'no',
onload: function () {
self.isIframeLoaded = true;
console.log('loaded!');
}
}).appendTo('#iframeContainer');
};
Try this:
<script>
$("a").click(function(event) {
event.preventDefault();
});
</script>
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
It most likely means that IIS Management Console was not installed, and modern Windows administrator/IT pro should be able to quickly check this by issuing this command:
Get-WindowsFeature *Web*
And if it is missing just quickly add this via the following command:
Add-WindowsFeature Web-Mgmt-Console
GUI options mentioned above are also valid (see answer from @Joe Wu) but PowerShell it is best way to do IT for IT Pro or let's put it as "if you have to do this slightly more often than once a year" :)
In your giant elif
chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:
...
elif x == 90:
return 6
else:
raise ValueError(x)
If you can live with 3. and 3.0 appearing as "3.0", a very simple approach that right-strips zeros from float representations:
print("%s"%3.140)
(thanks @ellimilial for pointing out the exceptions)
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
From Auth0.com
Token-Based Authentication, relies on a signed token that is sent to the server on each request.
What are the benefits of using a token-based approach?
Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.
CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.
CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).
Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.
For those who, like me, came from Google for the keyword "upload file colab":
from google.colab import files
uploaded = files.upload()
I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!
Good alternatives are the String.split and StringUtils.join methods.
Explode :
String[] exploded="Hello World".split(" ");
Implode :
String imploded=StringUtils.join(new String[] {"Hello", "World"}, " ");
Keep in mind though that StringUtils is in an external library.
If you start out with:
let array = [
{name: "malcom", dogType: "four-legged"},
{name: "peabody", dogType: "three-legged"},
{name: "pablo", dogType: "two-legged"}
];
And you want a set of, say, names, you would do:
let namesSet = new Set(array.map(item => item.name));
This is due to the wp_terms
, wp_termmeta
and wp_term_taxonomy
tables, which had all their ID's not set to AUTO_INCREMENT
To do this go to phpmyadmin, click on the concern database, wp_terms
table, click on structure Tab, at right side you will see a tab named A_I(AUTO_INCREMENT)
, check it and save (You are only doing this for the first option, in the case wp_term
you are only doing it for term_id
).
Do the same for wp_termmeta
and wp_term_taxonomy
that will fix the issue.
If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:
$(document).ready(function() {
$("[id^=content]").hover(function() {
$(this).addClass('transition');
}, function() {
$(this).removeClass('transition');
});
});
Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.
Use \n
for a line break and \t
if you want to insert a tab.
You can also use some XML tags for basic formatting: <b>
for bold text, <i>
for italics, and <u>
for underlined text.
Other formatting options are shown in this article on the Android Developers' site:
https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling
If you have control over the structure of the list, the most pythonic thing to do would probably be to change it from:
l=[1,2,3,4]
to:
l=[(1,2),(3,4)]
Then, your loop would be:
for i,j in l:
print i, j
In my case, Visual Leak Detector I was using to track down memory leaks in Visual Studio 2015 was missing the Microsoft manifest file Microsoft.DTfW.DHL.manifest
, see link Building Visual Leak Detector all way down. This file must be in the folder where vld.dll
or vld_x64.dll
is in your configuration, say C:\Program Files (x86)\Visual Leak Detector\bin\Win32
, C:\Program Files (x86)\Visual Leak Detector\bin\Win64
, Debug
or x64/Debug
.
Step 1: find what are the items are consuming 3000 port.
lsof -i:3000
step 2 : Find the process named
For Mac
ruby TCP localhost:hbci (LISTEN)
For Ubuntu
ruby TCP *:3000 (LISTEN)
Step 3: Find the PID of the process and kill it.
kill -9 PID
I've resorted to
df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index
lately. That gets both null and empty-string cells in one go.
The web.xml file should be listed right below the last line in your screenshot and resides in WebContent/WEB-INF
. If it is missing you might have missed to check the "Generate web.xml deployment descriptor" option on the third page of the Dynamic web project wizard.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
In Case of password also we need to pass one more parameter
redis-cli -h host -p port -a password
If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options
for your host or to put these lines in their virtual host configuration file.
In my case i did following code for compare 2 dates may it will help you ...
var date1 = "2010-10-20";_x000D_
var date2 = "2010-10-20";_x000D_
var time1 = moment(date1).format('YYYY-MM-DD');_x000D_
var time2 = moment(date2).format('YYYY-MM-DD');_x000D_
if(time2 > time1){_x000D_
console.log('date2 is Greter than date1');_x000D_
}else if(time2 > time1){_x000D_
console.log('date2 is Less than date1');_x000D_
}else{_x000D_
console.log('Both date are same');_x000D_
}
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
Use show/hide method as below
$("div").show();//To Show
$("div").hide();//To Hide
CSS can do that with background-size: cover;
But to be more detailed and support more browsers...
Use aspect ratio like this:
aspectRatio = $bg.width() / $bg.height();
For those of you still unable to fix the problem after using the above mentioned solutions. Try this
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
That should do the trick, cheers!
Taken from Retrieving File information | Android developers
private String queryName(ContentResolver resolver, Uri uri) {
Cursor returnCursor =
resolver.query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
Some answers don't work with large numbers.
Convert integer to the hex representation, then convert it to bytes:
def int_to_bytes(number):
hrepr = hex(number).replace('0x', '')
if len(hrepr) % 2 == 1:
hrepr = '0' + hrepr
return bytes.fromhex(hrepr)
Result:
>>> int_to_bytes(2**256 - 1)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
});
<form id="form1" name="form1">
Field 1: <input id="field1" type="text" class="required">
<input id="btn" type="submit" value="Validate">
</form>
You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.
This works great when you want to load a series from a csv file
x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))
<class 'pandas.core.series.Series'>
0 110.96
1 119.40
2 135.89
3 152.32
4 192.91
5 177.20
6 181.16
7 177.30
8 200.13
9 235.41
Name: x, dtype: float64
You need to change permission for your database folder: properties -> security tab -> edit... -> add... -> username "NT Service\MSSQL$SQLEXPRESS" or "NT Service\MSSQLSERVER". Close the windows, open Advanced..., double click the user and set as follows: Type: Allow Applies to: This folder, subfolder and files Basic permissions: all Make sure the owner is set too.
I find the easiest way to use timeit is from the command line:
Given test.py:
def InsertionSort(): ...
def TimSort(): ...
run timeit like this:
% python -mtimeit -s'import test' 'test.InsertionSort()'
% python -mtimeit -s'import test' 'test.TimSort()'
Here's a solution which again is not a CSS only solution. It is similar to avrahamcool's solution in that it uses a few lines of jQuery, but instead of changing heights and moving the header along, all it does is changing the width of tbody
based on how far its parent table
is scrolled along to the right.
An added bonus with this solution is that it works with a semantically valid HTML table.
It works great on all recent browser versions (IE10, Chrome, FF) and that's it, the scrolling functionality breaks on older versions.
But then the fact that you are using a semantically valid HTML table will save the day and ensure the table is still displayed properly, it's only the scrolling functionality that won't work on older browsers.
Here's a jsFiddle for demonstration purposes.
CSS
table {
width: 300px;
overflow-x: scroll;
display: block;
}
thead, tbody {
display: block;
}
tbody {
overflow-y: scroll;
overflow-x: hidden;
height: 140px;
}
td, th {
min-width: 100px;
}
JS
$("table").on("scroll", function () {
$("table > *").width($("table").width() + $("table").scrollLeft());
});
I needed a version which degrades nicely in IE9 (no scrolling, just a normal table). Posting the fiddle here as it is an improved version. All you need to do is set a height on the tr
.
Additional CSS to make this solution degrade nicely in IE9
tr {
height: 25px; /* This could be any value, it just needs to be set. */
}
Here's a jsFiddle demonstrating the nicely degrading in IE9 version of this solution.
Edit: Updated fiddle links to link to a version of the fiddle which contains fixes for issues mentioned in the comments. Just adding a snippet with the latest and greatest version while I'm at it:
$('table').on('scroll', function() {_x000D_
$("table > *").width($("table").width() + $("table").scrollLeft());_x000D_
});
_x000D_
html {_x000D_
font-family: verdana;_x000D_
font-size: 10pt;_x000D_
line-height: 25px;_x000D_
}_x000D_
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
width: 300px;_x000D_
overflow-x: scroll;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
thead {_x000D_
background-color: #EFEFEF;_x000D_
}_x000D_
_x000D_
thead,_x000D_
tbody {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
height: 140px;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
min-width: 100px;_x000D_
height: 25px;_x000D_
border: dashed 1px lightblue;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column 1</th>_x000D_
<th>Column 2</th>_x000D_
<th>Column 3</th>_x000D_
<th>Column 4</th>_x000D_
<th>Column 5</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>AAAAAAAAAAAAAAAAAAAAAAAAAA</td>_x000D_
<td>Row 1</td>_x000D_
<td>Row 1</td>_x000D_
<td>Row 1</td>_x000D_
<td>Row 1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 2</td>_x000D_
<td>Row 2</td>_x000D_
<td>Row 2</td>_x000D_
<td>Row 2</td>_x000D_
<td>Row 2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 3</td>_x000D_
<td>Row 3</td>_x000D_
<td>Row 3</td>_x000D_
<td>Row 3</td>_x000D_
<td>Row 3</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 4</td>_x000D_
<td>Row 4</td>_x000D_
<td>Row 4</td>_x000D_
<td>Row 4</td>_x000D_
<td>Row 4</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 5</td>_x000D_
<td>Row 5</td>_x000D_
<td>Row 5</td>_x000D_
<td>Row 5</td>_x000D_
<td>Row 5</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 6</td>_x000D_
<td>Row 6</td>_x000D_
<td>Row 6</td>_x000D_
<td>Row 6</td>_x000D_
<td>Row 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 7</td>_x000D_
<td>Row 7</td>_x000D_
<td>Row 7</td>_x000D_
<td>Row 7</td>_x000D_
<td>Row 7</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 8</td>_x000D_
<td>Row 8</td>_x000D_
<td>Row 8</td>_x000D_
<td>Row 8</td>_x000D_
<td>Row 8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 9</td>_x000D_
<td>Row 9</td>_x000D_
<td>Row 9</td>_x000D_
<td>Row 9</td>_x000D_
<td>Row 9</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Row 10</td>_x000D_
<td>Row 10</td>_x000D_
<td>Row 10</td>_x000D_
<td>Row 10</td>_x000D_
<td>Row 10</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
You can use like this.
when: condition1 == "condition1" or condition2 == "condition2"
Link to official docs: The When Statement.
Also Please refer to this gist: https://gist.github.com/marcusphi/6791404
You can also configure m2e to use HTTP instead of HTTPS
import sys
f = open(sys.argv[1] , 'r')
for line in f.readlines()[::-1]:
print line
You could make two forms with 2 different actions
<form action="login.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<br />
<form action="register.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Register">
</form>
Or do this
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="login">
<input type="submit" value="Login">
</form>
<br />
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="register">
<input type="submit" value="Register">
</form>
Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.
Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure
Several ways to achieve this. Examples are as below
a. return "22".toInteger()
b. if("22".isInteger()) return "22".toInteger()
c. return "22" as Integer()
d. return Integer.parseInt("22")
Hope this helps
I'll be brief but deadly. :) install -d will not work for you. It's simple. Try
$ npm install -g express
You can declare it as nil with the following:
var assoc : [String:String]
Then nice thing is you've already typeset (notice I used var and not let, think of these as mutable and immutable). Then you can fill it later:
assoc = ["key1" : "things", "key2" : "stuff"]
join
methodThe join
method is built exactly for these types of situations. You can join any number of DataFrames together with it. The calling DataFrame joins with the index of the collection of passed DataFrames. To work with multiple DataFrames, you must put the joining columns in the index.
The code would look something like this:
filenames = ['fn1', 'fn2', 'fn3', 'fn4',....]
dfs = [pd.read_csv(filename, index_col=index_col) for filename in filenames)]
dfs[0].join(dfs[1:])
With @zero's data, you could do this:
df1 = pd.DataFrame(np.array([
['a', 5, 9],
['b', 4, 61],
['c', 24, 9]]),
columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
['a', 5, 19],
['b', 14, 16],
['c', 4, 9]]),
columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
['a', 15, 49],
['b', 4, 36],
['c', 14, 9]]),
columns=['name', 'attr31', 'attr32'])
dfs = [df1, df2, df3]
dfs = [df.set_index('name') for df in dfs]
dfs[0].join(dfs[1:])
attr11 attr12 attr21 attr22 attr31 attr32
name
a 5 9 5 19 15 49
b 4 61 14 16 4 36
c 24 9 4 9 14 9
You can use PropertyConfigurator
to load your log4j.properties wherever it is located in the disk.
Example:
Logger logger = Logger.getLogger(this.getClass());
String log4JPropertyFile = "C:/this/is/my/config/path/log4j.properties";
Properties p = new Properties();
try {
p.load(new FileInputStream(log4JPropertyFile));
PropertyConfigurator.configure(p);
logger.info("Wow! I'm configured!");
} catch (IOException e) {
//DAMN! I'm not....
}
If you have an XML Log4J configuration, use DOMConfigurator instead.
For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:
hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }
hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}
This works for me:
Java
File file = new File(photoPath);
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
new String[]{file.getName()},null);
Kotlin
val file = File(photoPath)
file.delete()
MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
arrayOf(file.getName()), null)
This is how I solved the problem The menu closes a few seconds after mouse out (that if hover didn't fire),
//Set timer switch
$setM_swith=0;
$(function(){
$(".navbar-nav li a").click(function(event) {
if (!$(this).parent().hasClass('dropdown'))
$(".navbar-collapse").collapse('hide');
});
$(".navbar-collapse").mouseleave(function(){
$setM_swith=1;
setTimeout(function(){
if($setM_swith==1) {
$(".navbar-collapse").collapse('hide');
$setM_swith=0;}
}, 3000);
});
$(".navbar-collapse").mouseover(function() {
$setM_swith=0;
});
});
You're calling write_file with arguments like this:
write_file(foo, bar)
But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.
Use the following code:
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "Hello, errors!" );
Then watch the file:
tail -f /tmp/php-error.log
Or update php.ini
as described in this blog entry from 2008.
I hope the following will work for you.
<select class="form-control"
ng-model="selectedOption"
ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>
For me, I usually use DataContext
together in order to bind two-depth property such as this question.
<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />
Or, I prefer to use ElementName
because it achieves bindings only with view controls.
<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />
You are writing code that predominantly uses single quote strings.
echo 'A $variable_literal that I have'.PHP_EOL.'looks better than'.PHP_EOL;
echo 'this other $one'."\n";
In an ideal case, you would like to test for all three values, null, "" or empty(field doesn't exist in the record)
You can do the following.
db.users.find({$and: [{"name" : {$nin: ["", null]}}, {"name" : {$exists: true}}]})
You may also get this error if you have a name clash of a view and a module. I've got the error when i distribute my view files under views folder, /views/view1.py, /views/view2.py
and imported some model named table.py in view2.py which happened to be a name of a view in view1.py. So naming the view functions as v_table(request,id)
helped.
I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
for this small example:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem
You could just use
DataGridView1.CurrentRow.Cells["ColumnName"].Value
Set the data-badge
attribute to inline
<button type="submit" data-sitekey="your_site_key" data-callback="onSubmit" data-badge="inline" />
And add the following CSS
.grecaptcha-badge {
display: none;
}
Pattern is wrong
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");
Date currentdate;
currentdate=sdf.parse(date);
System.out.println(currentdate);
plot(t)
is in this case the same as
plot(t[[1]], t[[2]])
As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1
:
> length(t)
[1] 4
> length(1)
[1] 1
In your second example you plot a list with elements named x
and y
, both vectors of length 2,
so plot
plots these two vectors.
Edit:
If you want to plot lines use
plot(t, type="l")
The best way to secure phpMyAdmin is the combination of all these 4:
1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)
Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:
# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):
sudo nano /etc/apache2/conf-available/phpmyadmin.conf
/etc/phpmyadmin/apache.conf
Change: phpmyadmin URL by this line:
Alias /newphpmyadminname /usr/share/phpmyadmin
Add: AllowOverride All
<Directory /usr/share/phpmyadmin>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride Limit
...
sudo systemctl restart apache2
sudo nano /usr/share/phpmyadmin/.htaccess
deny from all
allow from 127.0.0.1
alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
alias myip="echo ${SSH_CONNECTION%% *}"
# Secure Web Access to phpMyAdmin:
Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04
PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add
C:\Windows\System32\drivers\etc
Notepad - Run As Administrator - open: hosts
127.0.0.1 pma.yourdomain.com
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)
# Check to make sure you are on SSH Tunnel
1. Windows - CMD:
ping pma.yourdomain.com
ping www.yourdomain.com
# See PuTTY ports:
netstat -ano |find /i "listening"
2. Test live:
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/
If you are able to do these all successfully,
you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.
Get into the habit of checking if a variable is available with isset, e.g.
if (isset($_GET['s']))
{
//do stuff that requires 's'
}
else
{
//do stuff that doesn't need 's'
}
You could disable notice reporting, but dealing them is good hygiene, and can allow you to spot problems you might otherwise miss.
Right now, there is no option to select the parent of an element in CSS (not even CSS3). But with CSS4, the most important news in the current W3C draft is the support for the parent selector.
$ul li:hover{
background: #fff;
}
Using the above, when hovering an list element, the whole unordered list will be highlighted by adding a white background to it.
Official documentation: https://www.w3.org/TR/2011/WD-selectors4-20110929/#overview (last row).
You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.
Try something like this:
declare @query varchar(max);
set @query = 'create database TEST...';
exec (@query);
I have some thoughts on how the best radio button implementation should look like. It can be based on UIButton
class and use it's 'selected' state to indicate one from the group. The UIButton
has native customisation options in IB, so it is convenient to design XIBs.
Also there should be an easy way to group buttons using IB outlet connections:
I have implemented my ideas in this RadioButton class. Works like a charm:
Vertical align Using this bootstrap 4 classes:
parent: d-table
AND
child: d-table-cell & align-middle & text-center
eg:
<div class="tab-icon-holder d-table bg-light">
<div class="d-table-cell align-middle text-center">
<img src="assets/images/devices/Xl.png" height="30rem">
</div>
</div>
and if you want parent be circle:
<div class="tab-icon-holder d-table bg-light rounded-circle">
<div class="d-table-cell align-middle text-center">
<img src="assets/images/devices/Xl.png" height="30rem">
</div>
</div>
which two custom css classes are as follow:
.tab-icon-holder {
width: 3.5rem;
height: 3.5rem;
}
.rounded-circle {
border-radius: 50% !important
}
Final usage can be like for example:
<div class="col-md-5 mx-auto text-center">
<div class="d-flex justify-content-around">
<div class="tab-icon-holder d-table bg-light rounded-circle">
<div class="d-table-cell align-middle text-center">
<img src="assets/images/devices/Xl.png" height="30rem">
</div>
</div>
<div class="tab-icon-holder d-table bg-light rounded-circle">
<div class="d-table-cell align-middle text-center">
<img src="assets/images/devices/Lg.png" height="30rem">
</div>
</div>
...
</div>
</div>
Also in some cases you can use following code:
parent: h-100 d-table mx-auto
AND
child: d-table-cell & align-middle
With a Spring Boot one can do the following:
values[0]=abc
values[1]=def
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConfigurationProperties
public class Configuration {
List<String> values = new ArrayList<>();
public List<String> getValues() {
return values;
}
}
This is needed, without this class or without the values
in class it is not working.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);
// notice #{} is used instead of ${}
@Value("#{configuration.values}")
List<String> values;
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
@Override
public void run(String... args) {
LOG.info("values: {}", values);
}
}
You can use the sp_MSforeachtable stored procedure like so:
USE MyDatabase
EXEC sp_MSforeachtable 'TRUNCATE TABLE ?'
Be warned that this will delete (by truncation) ALL data from all user tables. And in case you can't TRUNCATE due to foreign keys etc. you can run the same as a delete:
USE MyDatabase
EXEC sp_MSforeachtable 'DELETE FROM ?'
This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:
2019-03-12 09:35:43,659 INFO (null) - Application Started
I generally log both the Application_Start and Session_Start, so I see more detail in the next message
2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
log.Info("Application Started");
GlobalContext.Properties["page"] = new GetCurrentPage();
}
protected void Session_Start(object sender, EventArgs e)
{
Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
log.Info(string.Format("Session Started ({0})", Globals._Environment));
}
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
A simple for loop which tests the checked
property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked
further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");
For some frequently used movements and actions, I have defined the following mappings. This saves a keystroke compared to the CTRL+O combination and since I need them frequently, they pay off in the long run.
inoremap <A-$> <C-o>$
inoremap <A-^> <C-o>^
inoremap <A-h> <Left>
inoremap <A-l> <Right>
inoremap <A-O> <C-O>O
inoremap <A-o> <C-o>o
If the two files are not sorted yet, you can use:
comm -12 <(sort a.txt) <(sort b.txt)
and it will work, avoiding the error message comm: file 2 is not in sorted order
when doing comm -12 a.txt b.txt
.
if you want same string output then try below else use without double quotes for proper output
$str = '20130814';
echo date('"F Y"', strtotime($str));
//output : "August 2013"
SELECT t.ID,
t.NAME,
(SELECT t1.SOMECOLUMN
FROM TABLEB t1
WHERE t1.F_ID = T.TABLEA.ID)
FROM TABLEA t;
This will work for selecting from different table using sub query.
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
Apache Commons IO Utils has a FileUtils.writeByteArrayToFile() method. Note that if you're doing any file/IO work then the Apache Commons IO library will do a lot of work for you.
There really aren't any differences.
"
is processed as "
which is the decimal equivalent of &x22;
which is the ISO 8859-1 equivalent of "
.
The only reason you may be against using "
is because it was mistakenly omitted from the HTML 3.2 specification.
Otherwise it all boils down to personal preference.
I had the same problem in Flask.
When I added:
__init__.py
to tests folder, problem disappeared :)
Probably application couldn't recognize folder tests as module
<p> represents a paragraph and <div> represents a 'division', I suppose the main difference is that divs are semantically 'meaningless', where as a <p> is supposed to represent something relating to the text itself.
You wouldn't want to have nested <p>s for example, since that wouldn't make much semantic sense (except in the sense of quotations) Whereas people use nested <div>s for page layout.
According to Wikipedia
In HTML, the span and div elements are used where parts of a document cannot be semantically described by other HTML elements.
I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.
<button type="button">My Button</button>
Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):
The missing value default and invalid value default are the Submit Button state.
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
I think there is an option to setup the windows file association for .py files in the installer. Uncheck it and you should be fine.
If not, you can easily re-associate .py files with the previous version. The simplest way is to right click on a .py file, select "open with" / "choose program". On the dialog that appears, select or browse to the version of python you want to use by default, and check the "always use this program to open this kind of file" checkbox.
It's better if you create a class that has all the query methods, inclusively, in a different package, so instead of typing all the process in every class, you just call the method from that class.
Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.
>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1., 2.],
[ 1., 2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1., 3.],
[ 2., 3.]])
>>> t = np.floor(x)
>>> t
array([[ 1., 2.],
[ 1., 2.]])
>>> a = np.rint(x)
>>> a
array([[ 1., 2.],
[ 1., 3.]])
To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):
a.astype(int)
array([[1, 2],
[1, 3]])
>>> y.astype(int)
array([[1, 2],
[1, 2]])
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
try this:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)
document.write(a);
function Test(a,b)
{
return a > b ? true : false;
}
If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().
If you want to close all windows and terminate the application use System.exit()
You can use @UtilityClass annotation from lombok https://projectlombok.org/features/experimental/UtilityClass
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
You have to use .onload
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
const drawImage = (url) => {
const image = new Image();
image.src = url;
image.onload = () => {
ctx.drawImage(image, 0, 0)
}
}
Here's Why
If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()
I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.
I have done this in the past with update-java-alternatives
:
http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html
Wrapping a <a>
around won't work (unless you set the <div>
to display:inline-block;
or display:block;
to the <a>
) because the div is s a block-level element and the <a>
is not.
<a href="http://www.example.com" style="display:block;">
<div>
content
</div>
</a>
<a href="http://www.example.com">
<div style="display:inline-block;">
content
</div>
</a>
<a href="http://www.example.com">
<span>
content
</span >
</a>
<a href="http://www.example.com">
content
</a>
But maybe you should skip the <div>
and choose a <span>
instead, or just the plain <a>
. And if you really want to make the div clickable, you could attach a javascript redirect with a onclick handler, somethign like:
document.getElementById("myId").setAttribute('onclick', 'location.href = "url"');
but I would recommend against that.
Casting my hat into the ring a couple years later.
Will need to save the beginning center of the image view:
var panBegin: CGPoint.zero
Then update the new center using a transform:
if recognizer.state == .began {
panBegin = imageView!.center
} else if recognizer.state == .ended {
panBegin = CGPoint.zero
} else if recognizer.state == .changed {
let translation = recognizer.translation(in: view)
let panOffsetTransform = CGAffineTransform( translationX: translation.x, y: translation.y)
imageView!.center = panBegin.applying(panOffsetTransform)
}
This problem appeared for me when I was creating folders in the filesystem (not in my solution) and moved some projects around.
Turns out that the package paths are relative from the csproj files. So I had to change the "HintPath" of my references:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
To:
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
Notice the double "..\" in 'HintPath'.
I also had to change my error conditions, for example I had to change:
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
To:
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
Again, notice the double "..\".
The simplest and most fun way (imo) is glob
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
But the standard way is to use the directory functions.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
There are also the SPL DirectoryIterator methods. If you are interested
int *array = new int[n];
It declares a pointer to a dynamic array of type int
and size n
.
A little more detailed answer: new
allocates memory of size equal to sizeof(int) * n
bytes and return the memory which is stored by the variable array
. Also, since the memory is dynamically allocated using new
, you've to deallocate it manually by writing (when you don't need anymore, of course):
delete []array;
Otherwise, your program will leak memory of at least sizeof(int) * n
bytes (possibly more, depending on the allocation strategy used by the implementation).
Use this:
import cv2
cap = cv2.VideoCapture('path to video file')
count = 0
while cap.isOpened():
ret,frame = cap.read()
cv2.imshow('window-name', frame)
cv2.imwrite("frame%d.jpg" % count, frame)
count = count + 1
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows() # destroy all opened windows
man wget: -O file --output-document=file
wget "url" -O /tmp/cron_test/<file>
To demonstrate, consider the following set, which holds different Person objects:
Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));
Person Model Class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//TODO - getters,setters ,overridden toString & compareTo methods
}
for(Person p:people){ System.out.println(p.getName()); }
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:
The default implementation behaves as if:
for (T t : this)
action.accept(t);
Parameters: action - The action to be performed for each element
Throws: NullPointerException - if the specified action is null
Since: 1.8
As everyone else told you, you can convert it directly... UNLESS you meant something like "how can I convert an ASCII Extended character to its UTF-16 or UTF-32 value". This is a TOTALLY different question (one at least as good). And one quite difficult, if I remember correctly, if you are using only "pure" C. Then you could start here: https://stackoverflow.com/questions/114611/what-is-the-best-unicode-library-for-c/114643#114643
(for ASCII Extended I mean one of the many "extensions" to the ASCII set. The 0-127 characters of the base ASCII set are directly convertible to Unicode, while the 128-255 are not.). For example ISO_8859-1 http://en.wikipedia.org/wiki/ISO_8859-1 is an 8 bit extensions to the 7 bit ASCII set, or the (quite famous) codepages 437 and 850.
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.
to send over gmail, you need to use an encrypted connection. this is not possible with telnet alone, but you can use tools like openssl
either connect using the starttls option in openssl to convert the plain connection to encrypted...
openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -ign_eof
or connect to a ssl sockect directly...
openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
EHLO localhost
after that, authenticate to the server using the base64 encoded username/password
AUTH PLAIN AG15ZW1haWxAZ21haWwuY29tAG15cGFzc3dvcmQ=
to get this from the commandline:
echo -ne '\[email protected]\00password' | base64
AHVzZXJAZ21haWwuY29tAHBhc3N3b3Jk
then continue with "mail from:" like in your example
example session:
openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
[... lots of openssl output ...]
220 mx.google.com ESMTP m46sm11546481eeh.9
EHLO localhost
250-mx.google.com at your service, [1.2.3.4]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
AUTH PLAIN AG5pY2UudHJ5QGdtYWlsLmNvbQBub2l0c25vdG15cGFzc3dvcmQ=
235 2.7.0 Accepted
MAIL FROM: <[email protected]>
250 2.1.0 OK m46sm11546481eeh.9
rcpt to: <[email protected]>
250 2.1.5 OK m46sm11546481eeh.9
DATA
354 Go ahead m46sm11546481eeh.9
Subject: it works
yay!
.
250 2.0.0 OK 1339757532 m46sm11546481eeh.9
quit
221 2.0.0 closing connection m46sm11546481eeh.9
read:errno=0
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
If the button tag is inside the div element who contains the modal, you can do something like:
<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>
As of 2018, the accepted answer is out-of-date:
Sweetalert is maintained, and you can solve the original question's issue with use of the content option.
Using $("textarea#ExampleMessage").html('whatever you want to put here');
can be a good way, because .val()
can have problems when you are using data from database.
For example:
A database field named as description
has the following value asjkdfklasdjf sjklñadf
. In this case using .val() to assign value to textarea can be a tedious job.
Another variant on Lunatik's response is to use a local boolean and the change event so that the row can be highlighted upon initializing, but deselected and blocked after a selection change is made by the user:
Private Sub lbx_Change()
If Not bHighlight Then
If Me.lbx.Selected(0) Then Me.lbx.Selected(0) = False
End If
bHighlight = False
End Sub
When the listbox is initialized you then set bHighlight and lbx.Selected(0) = True, which will allow the header-row to initialize selected; afterwards, the first change will deselect and prevent the row from being selected again...
Using --disable-web-security
switch is quite dangerous! Why disable security at all while you can just allow XMLHttpRequest to access files from other files using --allow-file-access-from-files
switch?
Before using these commands be sure to end all running instances of Chrome.
On Windows:
chrome.exe --allow-file-access-from-files
On Mac:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
Discussions of this "feature" of Chrome:
I fixed this problem employing the two procedures of :
In Eclipse->'Project' menu -> 'Java Compiler' -> set 'Compiler compliance level' = 1.6 check on 'Use default compliance settings' Set 'Generated .class compatibility' = 1.6 Set 'Source compatibilty' = 1.6
Then go to 'Windows' menu --> 'Preferences' -->'Java' , expand 'Java' --> 'Compiler' -->Set 'Compiler compliance level' = 1.6
Hint: Source compatibility must be equal to or less than compliance level.
I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.
I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.
Thanks to all above though.
This works for me:
URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));
for ( int i; (i = in.read()) != -1; ) {
out.write(i);
}
in.close();
out.close();
If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.
$data = json_decode($json, TRUE);
Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.
When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.
As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:
import React from "react";
function JobCard(props) {
const { logo } = props;
return (
<div className="jobCards">
<img src={require(`../assets/images/${logo}`)} alt="" />
</div>
)
}
The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.
Have you already tried like
var open_link = window.open('','_blank');
open_link.location="somepage.html";
In PHP, a variable or array element which has never been set is different from one whose value is null
; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST
does not have any element at the key "username"
, so the interpreter aborts your program before it ever gets to the nullity test.
Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset
does:
if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"]
to pass as an argument to the function isset()
. However, isset()
is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.
It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE
level). If you change the error_reporting
level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null
. But that's considered bad practice, especially for production code.
Side note: PHP does string interpolation, so the echo
statements in the if
block can be combined into one:
echo "$user is your username";
Your LMSInitialize
function is declared inside Scorm_API_12
function. So it can be seen only in Scorm_API_12
function's scope.
If you want to use this function like API.LMSInitialize("")
, declare Scorm_API_12
function like this:
function Scorm_API_12() {
var Initialized = false;
this.LMSInitialize = function(param) {
errorCode = "0";
if (param == "") {
if (!Initialized) {
Initialized = true;
errorCode = "0";
return "true";
} else {
errorCode = "101";
}
} else {
errorCode = "201";
}
return "false";
}
// some more functions, omitted.
}
var API = new Scorm_API_12();
This is entirely untested but it should do what you need.
Update : here's a jsfiddle to look at. Seems to be working. link
You would past it into a js file and reference it after your jquery reference. You would then call it like this..
$("textarea").characterCounter(200);
A brief explanation of what is going on..
On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.
The plugin should handle pasting into the target too.
; (function ($) {
$.fn.characterCounter = function (limit) {
return this.filter("textarea, input:text").each(function () {
var $this = $(this),
checkCharacters = function (event) {
if ($this.val().length > limit) {
// Trim the string as paste would allow you to make it
// more than the limit.
$this.val($this.val().substring(0, limit))
// Cancel the original event
event.preventDefault();
event.stopPropagation();
}
};
$this.keyup(function (event) {
// Keys "enumeration"
var keys = {
BACKSPACE: 8,
TAB: 9,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
// which normalizes keycode and charcode.
switch (event.which) {
case keys.UP:
case keys.DOWN:
case keys.LEFT:
case keys.RIGHT:
case keys.TAB:
break;
default:
checkCharacters(event);
break;
}
});
// Handle cut/paste.
$this.bind("paste cut", function (event) {
// Delay so that paste value is captured.
setTimeout(function () { checkCharacters(event); event = null; }, 150);
});
});
};
} (jQuery));
Someone with more reputation can copy this into the main answer:
Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")
Bootstrap has many facility of classes to easily style elements if HTML. It includes a various of padding and margin classes for modification of the appearance of the element.
.m-0 { margin:0!important; }
.m-1 { margin:.25rem!important; }
.m-2 { margin:.5rem!important; }
.m-3 { margin:1rem!important; }
.m-4 { margin:1.5rem!important; }
.m-5 { margin:3rem!important; }
.mt-0 { margin-top:0!important; }
.mr-0 { margin-right:0!important; }
.mb-0 { margin-bottom:0!important; }
.ml-0 { margin-left:0!important; }
.mx-0 { margin-left:0!immortant;margin-right:0!immortant; }
.my-0 { margin-top:0!important;margin-bottom:0!important; }
.mt-1 { margin-top:.25rem!important; }
.mr-1 { margin-right:.25rem!important; }
.mb-1 { margin-bottom:.25rem!important; }
.ml-1 { margin-left:.25rem!important; }
.mx-1 { margin-left:.25rem!important;margin-right:.25rem!important; }
.my-1 { margin-top:.25rem!important;margin-bottom:.25rem!important; }
.mt-2 { margin-top:.5rem!important; }
.mr-2 { margin-right:.5rem!important; }
.mb-2 { margin-bottom:.5rem!important; }
.ml-2 { margin-left:.5rem!important; }
.mx-2 { margin-right:.5rem!important;margin-left:.5rem!important; }
.my-2 { margin-top:.5rem!important;margin-bottom:.5rem!important; }
.mt-3 { margin-top:1rem!important; }
.mr-3 { margin-right:1rem!important; }
.mb-3 { margin-bottom:1rem!important; }
.ml-3 { margin-left:1rem!important; }
.mx-3 { margin-right:1rem!important;margin-left:1rem!important; }
.my-3 { margin-bottom:1rem!important;margin-top:1rem!important; }
.mt-4 { margin-top:1.5rem!important; }
.mr-4 { margin-right:1.5rem!important; }
.mb-4 { margin-bottom:1.5rem!important; }
.ml-4 { margin-left:1.5rem!important; }
.mx-4 { margin-right:1.5rem!important;margin-left:1.5rem!important; }
.my-4 { margin-top:1.5rem!important;margin-bottom:1.5rem!important; }
.mt-5 { margin-top:3rem!important; }
.mr-5 { margin-right:3rem!important; }
.mb-5 { margin-bottom:3rem!important; }
.ml-5 { margin-left:3rem!important; }
.mx-5 { margin-right:3rem!important;margin-left:3rem!important; }
.my-5 { margin-top:3rem!important;margin-bottom:3rem!important; }
.mt-auto { margin-top:auto!important; }
.mr-auto { margin-right:auto!important; }
.mb-auto { margin-bottom:auto!important; }
.ml-auto { margin-left:auto!important; }
.mx-auto { margin-right:auto!important;margin-left:auto!important; }
.my-auto { margin-bottom:auto!important;margin-top:auto!important; }
.p-0 { padding:0!important; }
.p-1 { padding:.25rem!important; }
.p-2 { padding:.5rem!important; }
.p-3 { padding:1rem!important; }
.p-4 { padding:1.5rem!important; }
.p-5 { padding:3rem!important; }
.pt-0 { padding-top:0!important; }
.pr-0 { padding-right:0!important; }
.pb-0 { padding-bottom:0!important; }
.pl-0 { padding-left:0!important; }
.px-0 { padding-left:0!important;padding-right:0!important; }
.py-0 { padding-top:0!important;padding-bottom:0!important; }
.pt-1 { padding-top:.25rem!important; }
.pr-1 { padding-right:.25rem!important; }
.pb-1 { padding-bottom:.25rem!important; }
.pl-1 { padding-left:.25rem!important; }
.px-1 { padding-left:.25rem!important;padding-right:.25rem!important; }
.py-1 { padding-top:.25rem!important;padding-bottom:.25rem!important; }
.pt-2 { padding-top:.5rem!important; }
.pr-2 { padding-right:.5rem!important; }
.pb-2 { padding-bottom:.5rem!important; }
.pl-2 { padding-left:.5rem!important; }
.px-2 { padding-right:.5rem!important;padding-left:.5rem!important; }
.py-2 { padding-top:.5rem!important;padding-bottom:.5rem!important; }
.pt-3 { padding-top:1rem!important; }
.pr-3 { padding-right:1rem!important; }
.pb-3 { padding-bottom:1rem!important; }
.pl-3 { padding-left:1rem!important; }
.py-3 { padding-bottom:1rem!important;padding-top:1rem!important; }
.px-3 { padding-right:1rem!important;padding-left:1rem!important; }
.pt-4 { padding-top:1.5rem!important; }
.pr-4 { padding-right:1.5rem!important; }
.pb-4 { padding-bottom:1.5rem!important; }
.pl-4 { padding-left:1.5rem!important; }
.px-4 { padding-right:1.5rem!important;padding-left:1.5rem!important; }
.py-4 { padding-top:1.5rem!important;padding-bottom:1.5rem!important; }
.pt-5 { padding-top:3rem!important; }
.pr-5 { padding-right:3rem!important; }
.pb-5 { padding-bottom:3rem!important; }
.pl-5 { padding-left:3rem!important; }
.px-5 { padding-right:3rem!important;padding-left:3rem!important; }
.py-5 { padding-top:3rem!important;padding-bottom:3rem!important; }
Date()
With this you call a function called Date()
. It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36
as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString)
uses one of these formats:
As @Roko mentioned you can do this in multiple ways.
1.Using the jQuery first-child selector - SnoopCode
$(document).ready(function(){
$(".alldivs onediv:first-child").css("background-color","yellow");
}
Using jQuery eq Selector - SnoopCode
$( "body" ).find( "onediv" ).eq(1).addClass( "red" );
Using jQuery Id Selector - SnoopCode
$(document).ready(function(){
$("#div1").css("background-color: red;");
});
onblur
is the opposite of onfocus
.
Demo: http://jsfiddle.net/u1s62Lj8/1/
You need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)
<html>
<head>
// stylesheets here
<link rel="stylesheet" href=""/>
</head>
<body>
//your html code here
// js scripts here
// note jquery tag has to go before boostrap
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>
As an extension of lonesomeday's answer, you can also use
$('#playMovie1').click(function(){
$('#movie1')[0].play();
});
Notice that there is no get() or eq() jQuery function called. DOM's array used to call play() function. It's a shortcut to keep in mind.
I just saw this test:
bool getFileExists(const TCHAR *file)
{
return (GetFileAttributes(file) != 0xFFFFFFFF);
}
If you're passing literals in code, what's stopping you from simply declaring it ahead of time?
byte b = 0; //Set to desired value.
f(b);