All of the answers provided so far assume that you know something about the text to be replaced which makes sense, since that's what the OP asked. I'm providing an answer that assumes you know nothing about the text to be replaced and that there may be a separate line in the file with the same or similar content that you do not want to be replaced. Furthermore, I'm assuming you know the line number of the line to be replaced.
The following examples demonstrate the removing or changing of text by specific line numbers:
# replace line 17 with some replacement text and make changes in file (-i switch)
# the "-i" switch indicates that we want to change the file. Leave it out if you'd
# just like to see the potential changes output to the terminal window.
# "17s" indicates that we're searching line 17
# ".*" indicates that we want to change the text of the entire line
# "REPLACEMENT-TEXT" is the new text to put on that line
# "PATH-TO-FILE" tells us what file to operate on
sed -i '17s/.*/REPLACEMENT-TEXT/' PATH-TO-FILE
# replace specific text on line 3
sed -i '3s/TEXT-TO-REPLACE/REPLACEMENT-TEXT/'
If you are able to run a script, here is what I did for a similar situation:
Using a dictionary/hashMap (associative array) and variables for the sed
command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern
will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt'
) in a specific directory (source_dir
).
All the changes are written in the logfile
in the destin_dir
#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'
echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "
declare -A pairs=(
['WHAT1']='FOR1'
['OTHER_string_to replace']='string replaced'
)
for i in "${!pairs[@]}"; do
j=${pairs[$i]}
echo "[$i]=$j"
replace_what=$i
replace_for=$j
echo " "
echo "Replace: $replace_what for: $replace_for"
find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g"
find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done
echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile
First, the pairs array is declared, each pair is a replacement string, then WHAT1
will be replaced for FOR1
and OTHER_string_to replace
will be replaced for string replaced
in the file File.txt
. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i
and the second as replace_for=$j
. The find
command searches in the directory the filename (that may contain a wildcard) and the sed -i
command replaces in the same file(s) what was previously defined. Finally I added a grep
redirected to the logfile to log the changes made in the file(s).
This worked for me in GNU Bash 4.3
sed 4.2.2
and based upon VasyaNovikov's answer for Loop over tuples in bash.
You don't need to use sed
to do a substitution when in actual fact, you just want to insert a tab in front of the line. Substitution for this case is an expensive operation as compared to just printing it out, especially when you are working with big files. Its easier to read too as its not regex.
eg using awk
awk '{print "\t"$0}' $filename > temp && mv temp $filename
$ echo "bar embarassment"|awk '{for(o=1;o<=NF;o++)if($o=="bar")$o="no bar"}1'
no bar embarassment
Give up and use Perl
Since sed
does not cut it, let's just throw the towel and use Perl, at least it is LSB while grep
GNU extensions are not :-)
Print the entire matching part, no matching groups or lookbehind needed:
cat <<EOS | perl -lane 'print m/\d+/g'
a1 b2
a34 b56
EOS
Output:
12
3456
Single match per line, often structured data fields:
cat <<EOS | perl -lape 's/.*?a(\d+).*/$1/g'
a1 b2
a34 b56
EOS
Output:
1
34
With lookbehind:
cat <<EOS | perl -lane 'print m/(?<=a)(\d+)/'
a1 b2
a34 b56
EOS
Multiple fields:
cat <<EOS | perl -lape 's/.*?a(\d+).*?b(\d+).*/$1 $2/g'
a1 c0 b2 c0
a34 c0 b56 c0
EOS
Output:
1 2
34 56
Multiple matches per line, often unstructured data:
cat <<EOS | perl -lape 's/.*?a(\d+)|.*/$1 /g'
a1 b2
a34 b56 a78 b90
EOS
Output:
1
34 78
With lookbehind:
cat EOS<< | perl -lane 'print m/(?<=a)(\d+)/g'
a1 b2
a34 b56 a78 b90
EOS
Output:
1
3478
sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' index.html
This does a global in-place substitution on the file index.html. Quoting the string prevents problems with whitespace in the query and replacement.
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:
Parameter Expansion
...
${parameter#word}
Remove Smallest Prefix Pattern.
Theword
is expanded to produce a pattern. The parameter expansion then results inparameter
, with the smallest portion of the prefix matched by the pattern deleted.
In other words, you can write
$var="${var#*:}"
which will remove anything matching *:
from $var
(i.e. everything up to and including the first :
). If you want to match up to the last :
, then you could use ##
in place of #
.
This is all assuming that the part to remove does not contain :
(true for IPv4 addresses, but not for IPv6 addresses)
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
sed -i s/$/:80/ file.txt
sed
stream editor
-i
in-place (edit file in place)s
substitution command/replacement_from_reg_exp/replacement_to_text/
statement$
matches the end of line (replacement_from_reg_exp):80
text you want to add at the end of every line (replacement_to_text)file.txt
the file nameThis might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
A POSIX compliant one using the s
command:
sed '/CLIENTSCRIPT="foo"/s/.*/&\
CLIENTSCRIPT2="hello"/' file
For me works the next command:
find /path/to/dir -name "file.txt" | xargs sed -i 's/string_to_replace/new_string/g'
if string contains slash 'path/to/dir' it can be replace with another character to separate, like '@' instead '/'.
For example: 's@string/to/replace@new/string@g'
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
don't have to use grep either
an example:
sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file
More portable to use ed; some systems don't support \n in sed
printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
/bin/ed $filename
Not related to question but in case if someone is passing the string as an argument to bash script this might help.
Use:
./bash_script.sh "path\to\file"
Instead of:
./bash_script.sh path\to\file
For your reference.
Since there are also macOS folks reading this one (as I did), the following code worked for me (on 10.14)
egrep -rl '<pattern>' <dir> | xargs -I@ sed -i '' 's/<arg1>/<arg2>/g' @
All other answers using -i
and -e
do not work on macOS.
I had to use [\\]
or [/]
to be able to make this work, FYI.
awk '!/[\\]/' file > temp && mv temp file
and
awk '!/[/]/' file > temp && mv temp file
I was using awk to remove backlashes and forward slashes from a list.
If replacing the string by Variable, the solution doesn't work. The sed command need to be in double quotes instead on single quote.
#sed -e "s/#replacevarServiceName#/$varServiceName/g" -e "s/#replacevarImageTag#/$varImageTag/g" deployment.yaml
You can simply use the following command:-
tail -NUMBER_OF_LINES FILE_NAME
e.g tail -100 test.log
In case, if you want the output of the above in a separate file then you can pipes as follows:-
tail -NUMBER_OF_LINES FILE_NAME > OUTPUT_FILE_NAME
e.g tail -100 test.log > output.log
I had a similar problem, but was working with a windows file and need to keep those CRLF -- my solution on linux:
sed 's/\r//g' orig | awk '{if (NR>1) printf("\r\n"); printf("%s",$0)}' > tweaked
grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"
> (Get-content file.txt) | Foreach-Object {$_ -replace "^SourceRegexp$", "DestinationString"} | Set-Content file.txt
This is behaviour of
sed -i 's/^SourceRegexp$/DestinationString/g' file.txt
XMLStarlet or another XPath engine is the correct tool for this job.
For instance, with data.xml
containing the following:
<root>
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
</root>
...you can extract only the first title with the following:
xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml
Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster & Jobs
to Brewster & Jobs
), and so forth.
grep /Pattern/ | tail -n 2 | head -n 1
Tail first 2 and then head last one to get exactly first line after match.
sed 's/[^"]*"\([^"]*\).*/\1/'
does the job.
explanation of the part inside ' '
basically s/search for this/replace with this/ but we're telling him to replace the whole line with just a piece of it we found earlier.
If you have a long file with many multi-line ocurrences, it is useful to first print number lines:
cat -n file | sed -n '/Here/,/String/p'
POSIX sed
(and for example OS X's sed
, the sed
below) require i
to be followed by a backslash and a newline. Also at least OS X's sed
does not include a newline after the inserted text:
$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3
To replace a line, you can use the c
(change) or s
(substitute) commands with a numeric address:
$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3
Alternatives using awk
:
$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3
awk
interprets backslashes in variables passed with -v
but not in variables passed using ENVIRON
:
$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3
Both ENVIRON
and -v
are defined by POSIX.
You can use %
sed -i "s%http://www.fubar.com%URL_FUBAR%g"
sed '/^cdef$/r'<(
echo "line1"
echo "line2"
echo "line3"
echo "line4"
) -i -- input.txt
Using sed
:
sed -n -e '/^abc$/,/^mno$/{ /^abc$/d; /^mno$/d; p; }'
The -n
option means do not print by default.
The pattern looks for lines containing just abc
to just mno
, and then executes the actions in the { ... }
. The first action deletes the abc
line; the second the mno
line; and the p
prints the remaining lines. You can relax the regexes as required. Any lines outside the range of abc
..mno
are simply not printed.
From sed1line:
# print line number 52
sed -n '52p' # method 1
sed '52!d' # method 2
sed '52q;d' # method 3, efficient on large files
From awk1line:
# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}' # more efficient on large files
The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.
For instance:
echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7
Will result in output of:
2 3.4
-d sets the delimiter
-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7
.
tr
can be more concise for removing characters than sed
or awk
, especially when you want to remove different characters from a string.
Removing double quotes:
echo '"Hi"' | tr -d \"
# Produces Hi without quotes
Removing different kinds of brackets:
echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets
-d
stands for "delete".
All the tricks are almost the same, but I like this one:
find <mydir> -type f -exec sed -i 's/<string1>/<string2>/g' {} +
find <mydir>
: look up in the directory.
-type f
:
File is of type: regular file
-exec command {} +
:
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.
Assigning $1
works but it will leave a leading space: awk '{first = $1; $1 = ""; print $0, first; }'
You can also find the number of columns in NF
and use that in a loop.
All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.
However, Perl's regex works the same on any machine with Perl installed:
perl -pe 's/\s+/\n/g' file.txt
If you want to save the output:
perl -pe 's/\s+/\n/g' file.txt > newfile.txt
If you want only unique occurrences of words:
perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt
Pure POSIX shell and sponge
:
suffix=foobar
while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file |
sponge file
xargs
and printf
:
suffix=foobar
xargs -L 1 printf "%s${suffix}\n" < file | sponge file
Using join
:
suffix=foobar
join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
Shell tools using paste
, yes
, head
& wc
:
suffix=foobar
paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file
Note that paste
inserts a Tab char before $suffix
.
Of course sponge
can be replaced with a temp file, afterwards mv
'd over the original filename, as with some other answers...
A more-general solution (allows for more than one follow-up line to be joined) as a shell script. This adds a line between each, because I needed visibility, but that is easily remedied. This example is where the "key" line ended in : and no other lines did.
#!/bin/bash
#
# join "The rest of the story" when the first line of each story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#
PATTERN='*:';
LINEOUT=""
while read line; do
case $line in
$PATTERN)
echo ""
echo $LINEOUT
LINEOUT="$line"
;;
"")
LINEOUT=""
echo ""
;;
*) LINEOUT="$LINEOUT $line"
;;
esac
done
You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.
In this case, you can do
perl -pe 's/(regex)/\n$1/'
-pe
puts perl into a "execute and print" loop, much like sed's normal mode of operation.
'
quotes everything else so the shell won't interfere
()
surrounding the regex is a grouping operator. $1
on the right side of the substitution prints out whatever was matched inside these parens.
Finally, \n
is a newline.
Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like
\(\d\d\d\)\d\d\d-\d\d\d\d
\(
or \)
matches a literal paren, and \d
matches a digit.
Better:
\(\d{3}\)\d{3}-\d{4}
I imagine you can figure out what the numbers in braces are doing.
Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.
perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'
A couple final thoughts.
using -ne
instead of -pe
acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/
is a regex match):
perl -ne 'if (m/foobar/) {print}'
If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l
. Not useful for the OP, who was working with newlines, though.
Bonus tip - if you have the pcre package installed, it comes with pcregrep
, which uses full perl-compatible regexes.
You can delete a particular single line with its line number by
sed -i '33d' file
This will delete the line on 33 line number and save the updated file.
if you are expecting them in a certain order, you can just use diff
diff file1 file2 | grep ">"
Though I am late to this post, just updating my findings. This answer is only for Mac OS X.
$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern
In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.
$ sed 's/new/\
> /g' m1.json > m2.json
Worked! (in Mac OS X 10.9.3)
Inside vim
, you want to type when in normal (command) mode:
:%s/ /,/g
On the terminal prompt, you can use sed
to perform this on a file:
sed -i 's/\ /,/g' input_file
Note: the -i
option to sed
means "in-place edit", as in that it will modify the input file.
If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed
, the -i
option expects an extension
argument so your command is actually parsed as the extension
argument and the file path is interpreted as the command code.
Try adding the -e
argument explicitly and giving ''
as argument to -i
:
find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;
See this.
I think this post by Jeff Attwood addresses your question perfectly. It takes you through the differences between newlines on Dos, Mac and Unix, and then explains the history of CR (Carriage return) and LF (Line feed).
Cut first two characters from string:
$ string="1234567890"; echo "${string:2}"
34567890
I appreciate the tips I found on this site.
But, on my Windows 10, I had to use double quotes for this to work ...
sed -i "s/[\d128-\d255]//g" FILENAME
Noticed these things ...
For FILENAME the entire path\name needs to be quoted
This didn't work -- %TEMP%\"FILENAME"
This did -- %TEMP%\FILENAME"
sed leaves behind temp files in the current directory, named sed*
Perl one-liner similar to @jonas's awk solution:
perl -ne 'print if ! $x{$_}++' file
This variation removes trailing whitespace before comparing:
perl -lne 's/\s*$//; print if ! $x{$_}++' file
This variation edits the file in-place:
perl -i -ne 'print if ! $x{$_}++' file
This variation edits the file in-place, and makes a backup file.bak
perl -i.bak -ne 'print if ! $x{$_}++' file
You should add the g
modifier so that sed performs a global substitution of the contents of the pattern buffer:
echo dog dog dos | sed -e 's:dog:log:g'
For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6
The official documentation for GNU sed
is available at http://www.gnu.org/software/sed/manual/
ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook /tmp/foo.yml -vvv
Tasks with STDOUT will then have a section:
STDOUT:
What ever was in STDOUT
This might work for you (GNU sed):
sed 'y/:/\n/' file
or perhaps:
sed y/:/$"\n"/ file
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
The answer already given of using find and sed
find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;
is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g'
instead of the sed
command.
For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:
rpl -R foo bar .
It's not available by default on most Linux distros but is quick to install (apt-get install rpl
or similar).
However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:
Check the README for examples.
If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.
another sed solution is to always append it on the last line and delete a pre existing one.
sed -e '$a\' -e '<your-entry>' -e "/<your-entry-properly-escaped>/d"
"properly-escaped" means to put a regex that matches your entry, i.e. to escape all regex controls from your actual entry, i.e. to put a backslash in front of ^$/*?+().
this might fail on the last line of your file or if there's no dangling newline, I'm not sure, but that could be dealt with by some nifty branching...
No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).
But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.
For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.
Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.
You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.
Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.
It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.
another way, not using regex, is to use fields/delimiter method eg
string="http://www.suepearson.co.uk/product/174/71/3816/"
echo $string | awk -F"/" '{print $1,$2,$3}' OFS="/"
you can directly edit your file with
sed -i '/^#/ d'
If you want also delete comment lines that start with some whitespace use
sed -i '/^\s*#/ d'
Usually, you want to keep the first line of your script, if it is a sha-bang, so sed
should not delete lines starting with #!
. also it should delete lines, that just contain only a hash but no text. put it all together:
sed -i '/^\s*\(#[^!].*\|#$\)/d'
To be conform with all sed variants you need to add a backup extension to the -i
option:
sed -i.bak '/^\s*#/ d' $file
rm -Rf $file.bak
sed 's/^.\{,5\}//' file.dat
worked like a charm for me
Here is an example of an AWK I used a while ago. It is an AWK that prints new AWKS. AWK and SED being similar it may be a good template.
ls | awk '{ print "awk " "'"'"'" " {print $1,$2,$3} " "'"'"'" " " $1 ".old_ext > " $1 ".new_ext" }' > for_the_birds
It looks excessive, but somehow that combination of quotes works to keep the ' printed as literals. Then if I remember correctly the vaiables are just surrounded with quotes like this: "$1". Try it, let me know how it works with SED.
I came up with this, where n is the number of lines you want to delete:
count=`wc -l file`
lines=`expr "$count" - n`
head -n "$lines" file > temp.txt
mv temp.txt file
rm -f temp.txt
It's a little roundabout, but I think it's easy to follow.
There is a straightforward way using xargs:
> echo '"quoted"' | xargs
quoted
xargs uses echo as the default command if no command is provided and strips quotes from the input. See e.g. here.
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
You can use:
sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>
Example:
sed -i -e 's/Hello/Bye/' file.txt
This works flawless in Mac.
I have taken Vlad's idea and changed it a little bit. Instead of
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
Which yields
sed: couldn't edit /dev/null: not a regular file
I'm doing in 3 different connections to the remote server
touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme
Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well
1) What is the difference between awk and sed ?
Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.
2) What kind of application are best use cases for sed and awk tools ?
Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.
Given this test file (test.txt)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
the following command will replace the first line to "newline text"
$ sed '1 c\
> newline text' test.txt
Result:
newline text
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
more information can be found here
http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/
Assuming all data is formatted like your example, use 'cut' to get the first column only.
cat $file | cut -d ' ' -f 1
or to get the first 10 chars.
cat $file | cut -c 1-10
Additional comment. Yes this works:
sed 's/\"//g' infile.txt > outfile.txt
(however with batch gnu sed, will just print to screen)
In batch scripting (GNU SED), this was needed:
sed 's/\x22//g' infile.txt > outfile.txt
In order to replace all newlines with spaces using awk, without reading the whole file into memory:
awk '{printf "%s ", $0}' inputfile
If you want a final newline:
awk '{printf "%s ", $0} END {printf "\n"}' inputfile
You can use a character other than space:
awk '{printf "%s|", $0} END {printf "\n"}' inputfile
I am missing the awk
solution:
awk 'NF' file
Which would return:
xxxxxx
yyyyyy
zzzzzz
How does this work? Since NF
stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk
perform its default action: print the current line.
With GNU awk for inplace editing, \s/\S
, and gensub()
to delete
1) the FIRST field:
awk -i inplace '{sub(/^\S+\s*/,"")}1' file
or
awk -i inplace '{$0=gensub(/^\S+\s*/,"",1)}1' file
2) the LAST field:
awk -i inplace '{sub(/\s*\S+$/,"")}1' file
or
awk -i inplace '{$0=gensub(/\s*\S+$/,"",1)}1' file
3) the Nth field where N=3:
awk -i inplace '{$0=gensub(/\s*\S+/,"",3)}1' file
Without GNU awk you need a match()
+substr()
combo or multiple sub()
s + vars to remove a middle field. See also Print all but the first three columns.
Some options:
tr
tr -d '\15\32' < windows.txt > unix.txt
OR
tr -d '\r' < windows.txt > unix.txt
perl
perl -p -e 's/\r$//' < windows.txt > unix.txt
sed
sed 's/^M$//' windows.txt > unix.txt
OR
sed 's/\r$//' windows.txt > unix.txt
To obtain ^M
, you have to type CTRL-V
and then CTRL-M
.
echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt
The first tac
pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac
wraps it once again so the inserted line is at the beginning and the original file is in its original order.
Try this instead:
echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'
But note, if there is two pattern on one line, it will prints the 2nd.
Using what others mentioned, I wanted this to be a quick & dandy function in my bash shell.
Create a file: ~/.functions
Add to it the contents:
getline() {
line=$1
sed $line'q;d' $2
}
Then add this to your ~/.bash_profile
:
source ~/.functions
Now when you open a new bash window, you can just call the function as so:
getline 441 myfile.txt
This works for me you guys can try it out
INPUT='ubuntu:x:1000:1000:Ubuntu:/home/ubuntu:/bin/bash'
SUBSTRING=$(echo $INPUT| cut -d: -f1)
echo $SUBSTRING
I believe on OS X when you use -i an extension for the backup files is required. Try:
sed -i .bak 's/hello/gbye/g' *
Using GNU sed
the extension is optional.
If pattern match, copy next line into the pattern buffer, delete a return, then quit -- side effect is to print.
sed '/pattern/ { N; s/.*\n//; q }; d'
You have a single quotes conflict, so use:
echo "A,B,C" | sed "s/,/','/g"
If using bash, you can do too (<<<
is a here-string
):
sed "s/,/','/g" <<< "A,B,C"
but not
sed "s/,/','/g" "A,B,C"
because sed
expect file(s) as argument(s)
EDIT:
if you use ksh or any other ones :
echo string | sed ...
awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103
This might work for you (GNU sed):
sed -ri '/\s+$/s///' file
This looks for whitespace at the end of the line and and if present removes it.
A very useful but lesser-known fact about sed is that the familiar s/foo/bar/
command can use any punctuation, not only slashes. A common alternative is s@foo@bar@
, from which it becomes obvious how to solve your problem.
Another easy alternative:
Since $PWD
will usually contain a slash /
, use |
instead of /
for the sed statement:
sed -e "s|xxx|$PWD|"
mklement0's answer is great, but I have some small tweaks.
It seems like a good idea to explicitly specify bash
's encoding when using iconv
. Also, we should prepend a byte-order mark (even though the unicode standard doesn't recommend it) because there can be legitimate confusions between UTF-8 and ASCII without a byte-order mark. Unfortunately, iconv
doesn't prepend a byte-order mark when you explicitly specify an endianness (UTF-16BE
or UTF-16LE
), so we need to use UTF-16
, which uses platform-specific endianness, and then use file --mime-encoding
to discover the true endianness iconv
used.
(I uppercase all my encodings because when you list all of iconv
's supported encodings with iconv -l
they are all uppercase.)
# Find out MY_FILE's encoding
# We'll convert back to this at the end
FILE_ENCODING="$( file --brief --mime-encoding MY_FILE )"
# Find out bash's encoding, with which we should encode
# MY_FILE so sed doesn't fail with
# sed: RE error: illegal byte sequence
BASH_ENCODING="$( locale charmap | tr [:lower:] [:upper:] )"
# Convert to UTF-16 (unknown endianness) so iconv ensures
# we have a byte-order mark
iconv -f "$FILE_ENCODING" -t UTF-16 MY_FILE > MY_FILE.utf16_encoding
# Whether we're using UTF-16BE or UTF-16LE
UTF16_ENCODING="$( file --brief --mime-encoding MY_FILE.utf16_encoding )"
# Now we can use MY_FILE.bash_encoding with sed
iconv -f "$UTF16_ENCODING" -t "$BASH_ENCODING" MY_FILE.utf16_encoding > MY_FILE.bash_encoding
# sed!
sed 's/.*/&/' MY_FILE.bash_encoding > MY_FILE_SEDDED.bash_encoding
# now convert MY_FILE_SEDDED.bash_encoding back to its original encoding
iconv -f "$BASH_ENCODING" -t "$FILE_ENCODING" MY_FILE_SEDDED.bash_encoding > MY_FILE_SEDDED
# Now MY_FILE_SEDDED has been processed by sed, and is in the same encoding as MY_FILE
Try this:
while read line
do
echo -e |wc -m
done <abc.txt
Here are many solutions :
To upercaser with perl, tr, sed and awk
perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'
To lowercase with perl, tr, sed and awk
perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'
Complicated bash to lowercase :
while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done
Complicated bash to uppercase :
while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done
Simple bash to lowercase :
while read v;do echo "${v,,}"; done
Simple bash to uppercase :
while read v;do echo "${v^^}"; done
Note that ${v,} and ${v^} only change the first letter.
You should use it that way :
(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt
You can use AWK:
$ awk '{$1=$1}1' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
$ sed 's|^[[:blank:]]*||g' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
while
/read
loopwhile read -r line
do
echo $line
done <"file"
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
You can also delete a range of lines in a file. For example to delete stored procedures in a SQL file.
sed '/CREATE PROCEDURE.*/,/END ;/d' sqllines.sql
This will remove all lines between CREATE PROCEDURE and END ;.
I have cleaned up many sql files withe this sed command.
I have a script in my .bashrc that works under OSX and Linux (bash only !)
function trim_trailing_space() {
if [[ $# -eq 0 ]]; then
echo "$FUNCNAME will trim (in place) trailing spaces in the given file (remove unwanted spaces at end of lines)"
echo "Usage :"
echo "$FUNCNAME file"
return
fi
local file=$1
unamestr=$(uname)
if [[ $unamestr == 'Darwin' ]]; then
#specific case for Mac OSX
sed -E -i '' 's/[[:space:]]*$//' $file
else
sed -i 's/[[:space:]]*$//' $file
fi
}
to which I add:
SRC_FILES_EXTENSIONS="js|ts|cpp|c|h|hpp|php|py|sh|cs|sql|json|ini|xml|conf"
function find_source_files() {
if [[ $# -eq 0 ]]; then
echo "$FUNCNAME will list sources files (having extensions $SRC_FILES_EXTENSIONS)"
echo "Usage :"
echo "$FUNCNAME folder"
return
fi
local folder=$1
unamestr=$(uname)
if [[ $unamestr == 'Darwin' ]]; then
#specific case for Mac OSX
find -E $folder -iregex '.*\.('$SRC_FILES_EXTENSIONS')'
else
#Rhahhh, lovely
local extensions_escaped=$(echo $SRC_FILES_EXTENSIONS | sed s/\|/\\\\\|/g)
#echo "extensions_escaped:$extensions_escaped"
find $folder -iregex '.*\.\('$extensions_escaped'\)$'
fi
}
function trim_trailing_space_all_source_files() {
for f in $(find_source_files .); do trim_trailing_space $f;done
}
Quick and dirty:
head -16428 < file.in | tail -259 > file.out
Probably not the best way to do it but it should work.
BTW: 259 = 16482-16224+1.
based on your input example, this awk line works. (without trailing comma)
awk -vRS="" -vOFS=',' '$1=$1' file
test:
kent$ echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1'
foo,bar,qux,zuu,sdf,sdfasdf
If you would like to use awk
then this would work too
awk -F= '{$2="xxx";print}' OFS="\=" filename
This worked for me.
sed -e 's/\s\+/,/g' input.txt >> output.csv
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.
$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}
Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.
I would recommend everyone look into CSS grids. It has been supported by most browsers now since about 2017. Here is a link to some documentation: https://css-tricks.com/snippets/css/complete-guide-grid/ . It is so much easier to keep your page elements where you want them, especially when it comes to responsiveness. It took me all of 20 minutes to learn how to do it, and I'm a newbie!
<div class="grid-div">
<p class="hello">Hello</p>
<p class="world">World</p>
</div>
//begin css//
.grid-div {
display: grid;
grid-template-columns: 50% 50%;
grid-template-rows: 50% 50%;
}
.hello {
grid-column-start: 2;
grid-row-start: 2;
}
.world {
grid-column-start: 1;
grid-row-start: 2;
}
This code will split the page into 4 equal quadrants, placing the "Hello" in the bottom right, and the "World" in the bottom left without having to change their positioning or playing with margins.
This can be extrapolated into very complex grid layouts with overlapping, infinite grids of all sizes, and even grids nested inside grids, without losing control of your elements every time something changes (MS Word I'm looking at you).
Hope this helps whoever still needs it!
A different answer if you need to save the output of your whole scrollback buffer from an already actively running screen:
Ctrl-a [ g SPACE G $ >.
This will save your whole buffer to /tmp/screen-exchange
You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
What is the resolution of the video? I had a similar problem with IE11 in Win7. The Microsoft H.264 decoder supports only 1920x1088 pixels in Windows 7. See my story: http://lars.st0ne.at/blog/html5+video+in+IE11+-+size+does+matter
There is a good workaround for this, now, by using jsdelivr.net.
Steps:
raw.githubusercontent.com
to cdn.jsdelivr.net
/gh/
before your username.branch
name.@version
(if you do not do this, you will get the latest - which may cause long-term caching)Examples:
http://raw.githubusercontent.com/<username>/<repo>/<branch>/path/to/file.js
Use this URL to get the latest version:
http://cdn.jsdelivr.net/gh/<username>/<repo>/path/to/file.js
Use this URL to get a specific version or commit hash:
http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/path/to/file.js
For production environments, consider targeting a specific tag or commit-hash rather than the branch. Using the latest link may result in long-term caching of the file, causing your link to not be updated as you push new versions. Linking to a file by commit-hash or tag makes the link unique to version.
Why is this needed?
In 2013, GitHub started using X-Content-Type-Options: nosniff
, which instructs more modern browsers to enforce strict MIME type checking. It then returns the raw files in a MIME type returned by the server, preventing the browser from using the file as-intended (if the browser honors the setting).
For background on this topic, please refer to this discussion thread.
You can use Generic Webhook Trigger Plugin for this.
With a variable like changed_files
and expression $.commits[*].['modified','added','removed'][*]
.
You can have a filter text like $changed_files
and filter regexp like "folder/subfolder/[^"]+?"
if folder/subfolder
is the folder that should trigger builds.
<Button Content="Click" Width="200" Height="50">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGreen" TargetName="Border" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
For beginner like me who are not used to Regular Expression, this workaround solution worked:
var field = "Good_Luck_Buddy";
var newString = field.slice( field.indexOf("_")+1 );
slice() method extracts a part of a string and returns a new string and indexOf() method returns the position of the first found occurrence of a specified value in a string.
if ( ($name eq "tom" and $password eq "123!")
or ($name eq "frank" and $password eq "321!")) {
print "You have gained access.";
}
else {
print "Access denied!";
}
There's more than one way
First, shortest but Inefficient way
Network State Permission only needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then this method,
public boolean activeNetwork () {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
As seen in answers ConnectivityManager
is a solution, I just added it within a method this is a simplified method all use
ConnectivityManager
returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability
Second, Efficient way
Network State and Internet Permissions needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Then this class,
public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
public CheckInternetAsyncTask(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0)
return true;
} catch (IOException e) {
Log.e("TAG", "Error checking internet connection", e);
return false;
}
} else {
Log.d("TAG", "No network available!");
return false;
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
if(result){
// do ur code
}
}
}
Call CheckInternetAsyncTask
new CheckInternetAsyncTask(getApplicationContext()).execute();
Some Explanations :-
you have to check Internet on AsyncTask
, otherwise it can throw android.os.NetworkOnMainThreadException
in some cases
ConnectivityManager
used to check the network access if true sends request (Ping)
Request send to http://clients3.google.com/generate_204
, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient than http://www.google.com
, read this. if you have website it's preferred to put you website instead of google, only if you use it within the app
Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used
function setValToAssessment(id)
{
$.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
{
var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm');
$.each(response,function(key,value){
$("<input type='text' value='"+value+"' >")
.attr("id", key)
.attr("name", key)
.appendTo("form");
});
$('#hiddenForm').appendTo('body').submit();
// window.location.href = "<?=URL.$param->module?>/assessment";
});
}
Since this setting is not an attribute
It is an attribute.
Some attributes are defined as boolean, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled", you include only the bold part. In HTML 4, you should include only the bold part as the full version is marked as a feature with limited support (although that is less true now then when the spec was written).
As of HTML 5, the rules have changed and now you include only the name and not the value. This makes no practical difference because the name and the value are the same.
The DOM property is also called disabled
and is a boolean that takes true
or false
.
foo.disabled = true;
In theory you can also foo.setAttribute('disabled', 'disabled');
and foo.removeAttribute("disabled")
, but I wouldn't trust this with older versions of Internet Explorer (which are notoriously buggy when it comes to setAttribute
).
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
First, if you are able to locate your
bootstrap.css file
and
bootstrap.min.js file
in your computer, then what you just do is
First download your favorite theme i.e. from http://bootswatch.com/
Copy the downloaded bootstrap.css and bootstrap.min.js files
Then in your computer locate the existing files and replace them with the new downloaded files.
NOTE: ensure your downloaded files are renamed to what is in your folder
i.e.
Then you are good to go.
sometimes result may not display immediately. your may need to run the css on your browser as a way of refreshing
The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.
.groupby
on the 'method'
column, and create a dict
of DataFrames
with unique 'method'
values as the keys, with a dict-comprehension
.
.groupby
returns a groupby
object, that contains information about the groups, where g
is the unique value in 'method'
for each group, and d
is the DataFrame
for that group.value
of each key
in df_dict
, will be a DataFrame
, which can be accessed in the standard way, df_dict['key']
.list
of DataFrames
, which can be done with a list-comprehension
df_list = [d for _, d in df.groupby('method')]
import pandas as pd
import seaborn as sns # for test dataset
# load data for example
df = sns.load_dataset('planets')
# display(df.head())
method number orbital_period mass distance year
0 Radial Velocity 1 269.300 7.10 77.40 2006
1 Radial Velocity 1 874.774 2.21 56.95 2008
2 Radial Velocity 1 763.000 2.60 19.84 2011
3 Radial Velocity 1 326.030 19.40 110.62 2007
4 Radial Velocity 1 516.220 10.50 119.47 2009
# Using a dict-comprehension, the unique 'method' value will be the key
df_dict = {g: d for g, d in df.groupby('method')}
print(df_dict.keys())
[out]:
dict_keys(['Astrometry', 'Eclipse Timing Variations', 'Imaging', 'Microlensing', 'Orbital Brightness Modulation', 'Pulsar Timing', 'Pulsation Timing Variations', 'Radial Velocity', 'Transit', 'Transit Timing Variations'])
# or a specific name for the key, using enumerate (e.g. df1, df2, etc.)
df_dict = {f'df{i}': d for i, (g, d) in enumerate(df.groupby('method'))}
print(df_dict.keys())
[out]:
dict_keys(['df0', 'df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7', 'df8', 'df9'])
df_dict['df1].head(3)
or df_dict['Astrometry'].head(3)
method number orbital_period mass distance year
113 Astrometry 1 246.36 NaN 20.77 2013
537 Astrometry 1 1016.00 NaN 14.98 2010
df_dict['df2].head(3)
or df_dict['Eclipse Timing Variations'].head(3)
method number orbital_period mass distance year
32 Eclipse Timing Variations 1 10220.0 6.05 NaN 2009
37 Eclipse Timing Variations 2 5767.0 NaN 130.72 2008
38 Eclipse Timing Variations 2 3321.0 NaN 130.72 2008
df_dict['df3].head(3)
or df_dict['Imaging'].head(3)
method number orbital_period mass distance year
29 Imaging 1 NaN NaN 45.52 2005
30 Imaging 1 NaN NaN 165.00 2007
31 Imaging 1 NaN NaN 140.00 2004
DataFrames
using pandas: Boolean Indexing.loc
is not required.DataFrames
.dict
, list
, generator
, etc.), as shown above.df1 = df[df.method == 'Astrometry']
df2 = df[df.method == 'Eclipse Timing Variations']
This blog shows how to update the registry so the Android SDK can find your Java SDK on a 64-bit machine.
http://codearetoy.wordpress.com/2010/12/23/jdk-not-found-on-installing-android-sdk/
Rob Heiser suggested checking out your java version by using 'java -version'.
That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).
http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path
java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.
I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).
Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.
You can try this example out. A simple C# progaram to convert string to double
class Calculations{
protected double length;
protected double height;
protected double width;
public void get_data(){
this.length = Convert.ToDouble(Console.ReadLine());
this.width = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());
}
}
I think pressing Q should work.
When you pass a pointer by a non-const
reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.
To fix this error, either declare x
constant
// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
*x = 1000;
}
or make a variable to which you assign a pointer to nKByte
before calling test
:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
If you are using eclipse click on corresponding jar file. Goto ->META-INF-> open file spring.schemas
you will see the lines something like below.
http://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.1.xsd
copy after = and configure beans something like below.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/rabbit classpath:org/springframework/amqp/rabbit/config/spring-rabbit-1.1.xsd
http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-3.1.xsd
http://www.springframework.org/schema/context classpath:org/springframework/context/config/spring-context-3.1.xsd
http://www.springframework.org/schema/util classpath:org/springframework/beans/factory/xml/spring-util-3.1.xsd">
I faced the same issue cause I had the RecyclerView in another layout and not on activity_main.xml.
By searching on some sites I got something and felt like sharing here
Add Id to Include tag in Activity_main.xml
<include id="includedRecyclerLayout"
....
</include>
call this layout before Searching view by ID in MainActivity.java
`ConstraintLayout includedLayout = findViewById(R.id.inckudedRecyclerLayout);
RecyclerViewrecyclerview=includedLayout.findViewById(R.id.RECYCLER_VIEW_ID)`;
If you want all groups known to the system, I would recommend using getent group
instead of parsing /etc/group
:
getent group
The reason is that on networked systems, groups may not only read from /etc/group
file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).
If you want just the group names you can use:
getent group | cut -d: -f1
In VIM, take a look at the following to see different alternatives for what you might have done:
:help opening-window
For instance:
Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...
You have empty $entry_database
variable. As you see in error: ListEmail, Title FROM WHERE ID
bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:
SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]
which in your way should become:
SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'
In kruskal Algorithm we have number of edges and number of vertices on a given graph but on each edge we have some value or weight on behalf of which we can prepare a new graph which must be not cyclic or not close from any side For Example
graph like this _____________ | | | | | | |__________| | Give name to any vertex a,b,c,d,e,f .
First of all, avoid scanf()
. Using it is not worth the pain.
See: Why does everyone say not to use scanf? What should I use instead?
Using a whitespace character in scanf()
would ignore any number of whitespace characters left in the input stream, what if you need to read more inputs? Consider:
#include <stdio.h>
int main(void)
{
char ch1, ch2;
scanf("%c", &ch1); /* Leaves the newline in the input */
scanf(" %c", &ch2); /* The leading whitespace ensures it's the
previous newline is ignored */
printf("ch1: %c, ch2: %c\n", ch1, ch2);
/* All good so far */
char ch3;
scanf("%c", &ch3); /* Doesn't read input due to the same problem */
printf("ch3: %c\n", ch3);
return 0;
}
While the 3rd scanf() can be fixed in the same way using a leading whitespace, it's not always going to that simple as above.
Another major problem is, scanf()
will not discard any input in the input stream if it doesn't match the format. For example, if you input abc
for an int
such as: scanf("%d", &int_var);
then abc
will have to read and discarded. Consider:
#include <stdio.h>
int main(void)
{
int i;
while(1) {
if (scanf("%d", &i) != 1) { /* Input "abc" */
printf("Invalid input. Try again\n");
} else {
break;
}
}
printf("Int read: %d\n", i);
return 0;
}
Another common problem is mixing scanf()
and fgets()
. Consider:
#include <stdio.h>
int main(void)
{
int age;
char name[256];
printf("Input your age:");
scanf("%d", &age); /* Input 10 */
printf("Input your full name [firstname lastname]");
fgets(name, sizeof name, stdin); /* Doesn't read! */
return 0;
}
The call to fgets()
doesn't wait for input because the newline left by the previous scanf() call is read and fgets() terminates input reading when it encounters a newline.
There are many other similar problems associated with scanf()
. That's why it's generally recommended to avoid it.
So, what's the alternative? Use fgets()
function instead in the following fashion to read a single character:
#include <stdio.h>
int main(void)
{
char line[256];
char ch;
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
return 0;
}
One detail to be aware of when using fgets()
will read in the newline character if there's enough room in the inut buffer. If it's not desirable then you can remove it:
char line[256];
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */
Looks like moment.js is the most popular and with active development:
moment("2010-01-01T05:06:07", moment.ISO_8601);
You will find the application folder at:
/data/data/"your package name"
you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.
None of the answers worked for me. If you are running on Ubuntu, you can try:
With python3:
sudo apt-get install python3 python-dev python3-dev \
build-essential libssl-dev libffi-dev \
libxml2-dev libxslt1-dev zlib1g-dev \
python-pip
With Python 2:
sudo apt-get install python-dev \
build-essential libssl-dev libffi-dev \
libxml2-dev libxslt1-dev zlib1g-dev \
python-pip
Regarding the remote option for modals, from the docs:
If a remote URL is provided, content will be loaded via jQuery's load method and injected into the root of the modal element.
That means your remote file should provide the complete modal structure, not just what you want to display on the body.
In v3.1 the above behavior was changed and now the remote content is loaded into .modal-content
See this Demo fiddle
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
Update:
This solution works and just a call to 'FB.logout()' doesn't work because browser wants a user interaction to actually call this function, so that it knows - it is a user not a script.
<a href="#" onclick="FB.logout();">Logout</a>
Check if the value is a string literal or String object:
function isString(o) {
return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}
Unit test:
function assertTrue(value, message) {
if (!value) {
alert("Assertion error: " + message);
}
}
function assertFalse(value, message)
{
assertTrue(!value, message);
}
assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");
Checking for a number is similar:
function isNumber(o) {
return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
The Ternary operator is just written as a boolean expression followed by a questionmark and then two further expressions separated by a colon.
The first thing that I can see that you have got wrong is that your first expression isn't returning a boolean or anything sensible that could be converted to a boolean. Your first expression is always going to return a jQuery object that has no sensible interpretation as a boolean and what it does convert to is probably an unchanging interpretation. You are always best off returning something that has a well known boolean interpretation, if nothign else for the sake of readability.
The second thing is that you are putting a semicolon after each of your expressions which is wrong. In effect this is saying "end of construct" and so is breaking your ternary operator.
In this situation though you probably can do this a more easy way. If you use classes and the toggleClass method then you can easily get it to switch a class on and off and then you can put your styles in that class definition (Kudos to @yoavmatchulsky for suggesting use of classes up there in comments).
A fiddle of this is found here: http://jsfiddle.net/chrisvenus/wSMnV/ (based on the original)
Instead of Str(RequestID)
, try convert(varchar(38), RequestID)
public class Itemfound{
public static void main(String args[]){
if( Arrays.asList("a","b","c").contains("a"){
System.out.println("It is here");
}
}
}
This is what you looking for. The contains() method simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
I had the same problem due to ghost processes that didn't show up when using top in bash. This prevented the JVM to spawn more threads.
For me, it resolved when listing all java processes with jps (just execute jps
in your shell) and killed them separately using the kill -9 pid
bash command for each ghost process.
This might help in some scenarios.
If this is for Linux, I've been using the function "gettimeofday", which returns a struct that gives the seconds and microseconds since the Epoch. You can then use timersub to subtract the two to get the difference in time, and convert it to whatever precision of time you want. However, you specify nanoseconds, and it looks like the function clock_gettime() is what you're looking for. It puts the time in terms of seconds and nanoseconds into the structure you pass into it.
Here is all you need:
new HtmlWebpackPlugin({
favicon: "./src/favicon.gif"
})
That is definitely after adding "favicon.gif" to the folder "src".
This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">
. This is safer than just importing with copyWebpackPLugin
We'd like to think that "net stop " will stop the service. Sadly, reality isn't that black and white. If the service takes a long time to stop, the command will return before the service has stopped. You won't know, though, unless you check errorlevel.
The solution seems to be to loop round looking for the state of the service until it is stopped, with a pause each time round the loop.
But then again...
I'm seeing the first service take a long time to stop, then the "net stop" for a subsequent service just appears to do nothing. Look at the service in the services manager, and its state is still "Started" - no change to "Stopping". Yet I can stop this second service manually using the SCM, and it stops in 3 or 4 seconds.
While the above solutions do work, there is a very simple solution shall we say in "layman's" terms. Someone still learning python and string's can use the other answers but they don't really understand how they work or what each part of the code is doing without a full explanation by the poster as opposed to "this works". The following executes the swapping of every second character in a string and is easy for beginners to understand how it works.
It is simply iterating through the string (any length) by two's (starting from 0 and finding every second character) and then creating a new string (swapped_pair) by adding the current index + 1 (second character) and then the actual index (first character), e.g., index 1 is put at index 0 and then index 0 is put at index 1 and this repeats through iteration of string.
Also added code to ensure string is of even length as it only works for even length.
DrSanjay Bhakkad post above is also a good one that works for even or odd strings and is basically doing the same function as below.
string = "abcdefghijklmnopqrstuvwxyz123"
# use this prior to below iteration if string needs to be even but is possibly odd
if len(string) % 2 != 0:
string = string[:-1]
# iteration to swap every second character in string
swapped_pair = ""
for i in range(0, len(string), 2):
swapped_pair += (string[i + 1] + string[i])
# use this after above iteration for any even or odd length of strings
if len(swapped_pair) % 2 != 0:
swapped_adj += swapped_pair[-1]
print(swapped_pair)
badcfehgjilknmporqtsvuxwzy21 # output if the "needs to be even" code used
badcfehgjilknmporqtsvuxwzy213 # output if the "even or odd" code used
String message = URLEncoder.encode("my message", "UTF-8");
try {
// instantiate the URL object with the target URL of the resource to
// request
URL url = new URL("http://www.example.com/comment");
// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
connection.setDoOutput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");
// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write("message=" + message);
// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
The first 3 answers to your questions are listed as inline comments, beside each method, in the example HTTP POST above.
From getOutputStream:
Returns an output stream that writes to this connection.
Basically, I think you have a good understanding of how this works, so let me just reiterate in layman's terms. getOutputStream
basically opens a connection stream, with the intention of writing data to the server. In the above code example "message" could be a comment that we're sending to the server that represents a comment left on a post. When you see getOutputStream
, you're opening the connection stream for writing, but you don't actually write any data until you call writer.write("message=" + message);
.
From getInputStream():
Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.
getInputStream
does the opposite. Like getOutputStream
, it also opens a connection stream, but the intent is to read data from the server, not write to it. If the connection or stream-opening fails, you'll see a SocketTimeoutException
.
How about the getInputStream? Since I'm only able to get the response at getInputStream, then does it mean that I didn't send any request at getOutputStream yet but simply establishes a connection?
Keep in mind that sending a request and sending data are two different operations. When you invoke getOutputStream or getInputStream url.openConnection()
, you send a request to the server to establish a connection. There is a handshake that occurs where the server sends back an acknowledgement to you that the connection is established. It is then at that point in time that you're prepared to send or receive data. Thus, you do not need to call getOutputStream to establish a connection open a stream, unless your purpose for making the request is to send data.
In layman's terms, making a getInputStream
request is the equivalent of making a phone call to your friend's house to say "Hey, is it okay if I come over and borrow that pair of vice grips?" and your friend establishes the handshake by saying, "Sure! Come and get it". Then, at that point, the connection is made, you walk to your friend's house, knock on the door, request the vice grips, and walk back to your house.
Using a similar example for getOutputStream
would involve calling your friend and saying "Hey, I have that money I owe you, can I send it to you"? Your friend, needing money and sick inside that you kept it for so long, says "Sure, come on over you cheap bastard". So you walk to your friend's house and "POST" the money to him. He then kicks you out and you walk back to your house.
Now, continuing with the layman's example, let's look at some Exceptions. If you called your friend and he wasn't home, that could be a 500 error. If you called and got a disconnected number message because your friend is tired of you borrowing money all the time, that's a 404 page not found. If your phone is dead because you didn't pay the bill, that could be an IOException. (NOTE: This section may not be 100% correct. It's intended to give you a general idea of what's happening in layman's terms.)
Question #5:
Yes, you are correct that openConnection simply creates a new connection object but does not establish it. The connection is established when you call either getInputStream or getOutputStream.
openConnection
creates a new connection object. From the URL.openConnection javadocs:
A new connection is opened every time by calling the openConnection method of the protocol handler for this URL.
The connection is established when you call openConnection, and the InputStream, OutputStream, or both, are called when you instantiate them.
Question #6:
To measure the overhead, I generally wrap some very simple timing code around the entire connection block, like so:
long start = System.currentTimeMillis();
log.info("Time so far = " + new Long(System.currentTimeMillis() - start) );
// run the above example code here
log.info("Total time to send/receive data = " + new Long(System.currentTimeMillis() - start) );
I'm sure there are more advanced methods for measuring the request time and overhead, but this generally is sufficient for my needs.
For information on closing connections, which you didn't ask about, see In Java when does a URL connection close?.
It's possible, but it depends on the power output of the beacon you're receiving, other rf sources nearby, obstacles and other environmental factors. Best thing to do is try it out in the environment you're interested in.
var arr3 = new arraylist();
for(int i=0, j=0, k=0; i<arr1.size()+arr2.size(); i++){
if(i&1)
arr3.add(arr1[j++]);
else
arr3.add(arr2[k++]);
}
as you say, "the names and numbers beside each other".
Easy in MySQL:
UPDATE users AS U1, users AS U2
SET U1.name_one = U2.name_colX
WHERE U2.user_id = U1.user_id
I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.
.directive('hoverClass', function () {
return {
restrict: 'A',
scope: {
hoverClass: '@'
},
link: function (scope, element) {
element.on('mouseenter', function() {
element.addClass(scope.hoverClass);
});
element.on('mouseleave', function() {
element.removeClass(scope.hoverClass);
});
}
};
})
then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:
<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
index="{{$index}}"><i class="{{item.icon}}"
box="course-{{$index}}"></i></li>
This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work
<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
data-ng-controller ="CourseItemController"
data-ng-class="{ selected: isSelected }">
providing of course that the li's are infact children of the parent div
That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like
400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update
More info in free InfoQ Explores: REST book.
You can use hh
to tell printf
that the argument is an unsigned char. Use 0
to get zero padding and 2
to set the width to 2. x
or X
for lower/uppercase hex characters.
uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"
Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf
link again. Specifically:
Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.
The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header
<cinttypes>
(C++) or<inttypes.h>
(C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).
As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.
Edit 2: ("when-to-admit-you're-wrong" edition):
If you read the actual C11 standard on page 311 (329 of the PDF) you find:
hh: Specifies that a following
d
,i
,o
,u
,x
, orX
conversion specifier applies to asigned char
orunsigned char
argument (the argument will have been promoted according to the integer promotions, but its value shall be converted tosigned char
orunsigned char
before printing); or that a followingn
conversion specifier applies to a pointer to asigned char
argument.
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
using this post
Open Firefox / chrome
open page the video
Play Video
click F12
on keyboard -> network
in Filter URLs
ts
copy link of ts
remove index and ts extension from link
for example:
http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
will be copied as
http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000
insert in below script under LINK
#!/bin/bash
# insert here urls
LINK=(
'http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000' # replace this with your url
)
mkdir my-videos
cd mkdir my-videos
CNT=0
for URL in ${LINK[@]}
do
# create folder for streaming media
CNT=$((CNT + 1))
mkdir $CNT
cd $CNT
(
DIR="${URL##*/}"
# download all videos
wget $URL'_'{0..1200}.ts
# link videos
echo $DIR'_'{0..1200}.ts | tr " " "\n" > tslist
while read line; do cat $line >> $CNT.mp4; done < tslist
rm -rf media* tslist
) &
cd ..
done
wait
EDIT
adding script in python - runs on windows and linux
import urllib.request
import os
import shutil
my_lessons = [
# http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000_454.ts
"http://vid.com/vod/mp4:vod/PRV/Yg0WGN_6.mp4/media_b180000" # replace this with your url
]
lesson_dir = "my_vids"
try:
shutil.rmtree(lesson_dir)
except:
print "ok"
os.makedirs(lesson_dir)
os.chdir(lesson_dir)
for lesson, dwn_link in enumerate(my_lessons):
print ("downloading lesson %d.. " % (lesson), dwn_link)
file_name = '%04d.mp4' % lesson
f = open(file_name, 'ab')
for x in range(0, 1200):
try:
rsp = urllib.request.urlopen(dwn_link + "_%04d.ts" % (x) )
except:
break
file_name = '%d.mp4' % lesson
print "downloading %d.ts" % (x)
f.write(rsp.read())
f.close()
print "done good luck!! ================== "
if the script fails, or downloads empty file, try removing the try wrap to see what fails
IMHO you should pay your attention to Robot.class
Still if you want to move the mouse pointer physically, you need to take different approach using Robot class
Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked.
In all browsers these are in event.screenX
and event.screenY
.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want.
In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.
More details you can get here
Hope this be helpful to you.
not that hard,
if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.
this is the stream url
which returns a JSON like that:
{
"Streams": [
{
"StreamId": 3244651,
"Reliability": 92,
"Bandwidth": 64,
"HasPlaylist": false,
"MediaType": "MP3",
"Url": "http://mp3hdfm32.hala.jo:8132",
"Type": "Live"
}
]
}
i believe that's the url you need: http://mp3hdfm32.hala.jo:8132
Leave off the quotes
$cmd &
$othercmd &
eg:
nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash
cmd="ls -la"
$cmd &
nicholas@nick-win7 /tmp
$ ./test
nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root 0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx 1 nicholas None 35 2010-09-10 20:44 test
-rwxr-xr-x 1 nicholas None 41 2010-09-10 20:43 test~
My problem was fideloper proxy
version.
when i upgraded laravel 5.5 to 5.8 this happened
just sharing if anybody get help
change you composer json fideloper version:
"fideloper/proxy": "^4.0",
After that you need to run update composer that's it.
composer update
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
You can't set the precision of a double (or Double) to a specified number of decimal digits, because floating-point values don't have decimal digits. They have binary digits.
You will have to convert into a decimal radix, either via BigDecimal
or DecimalFormat
, depending on what you want to do with the value later.
See also my answer to this question for a refutation of the inevitable *100/100 answers.
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
You can use the following example.
String date = "2011-08-12T20:17:46.384Z";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
More detailed answer to help the newbies of VueJS:
And the code itself:
<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
mode: 'history',
routes: []
});
var vm = new Vue({
router,
el: '#app',
mounted: function() {
q = this.$route.query.q
console.log(q)
},
});
I agree with Mike, though I'm a Vim die-hard. I've been using GEdit quite frequently lately when I'm doing lightweight Ruby scripting. The standard editor (plus Ruby code snippets) is extremely usable and polished, and can provide a nice reprieve from full-strength, always-on programming editors.
Try setting this before you print:
setvbuf (stdout, NULL, _IONBF, 0);
Yep, in Windows 7 64 bit you have C:\Program Files
and C:\Program Files (x86)
. You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin
to environment variable PATH.
print(string ("Yo!"));
You need to make a (temporary) std::string
object out of it.
There is DatePicker in WPF Tool Kit, but I have not seen DateTime Picker in WPF ToolKit. So I don't know what kind of DateTimePicker control John is talking about.
According to official documentation: Creating REST Controllers with the @RestController annotation
@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
It seems that it's best to use @RestController
for clarity, but you can also combine it with ResponseEntity
for flexibility when needed (According to official tutorial and the code here and my question to confirm that).
For example:
@RestController
public class MyController {
@GetMapping(path = "/test")
@ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");
return user;
}
}
is the same as:
@RestController
public class MyController {
@GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");
HttpHeaders responseHeaders = new HttpHeaders();
// ...
return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
}
}
This way, you can define ResponseEntity
only when needed.
Update
You can use this:
return ResponseEntity.ok().headers(responseHeaders).body(user);
Try quoting the argument list:
Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"
You can also provide the argument list as an array (comma separated args) but using a string is usually easier.
I'm incredibly lazy. I just did a search hoping to find a shortcut to this problem but didn't get an answer so I knocked this up.
~/bin/IGNORE_ALL
#!/bin/bash
# Usage: IGNORE_ALL <commit message>
git status --porcelain | grep '^??' | cut -f2 -d' ' >> .gitignore
git commit -m "$*" .gitignore
EG: IGNORE_ALL added stat ignores
This will just append all the ignore files to your .gitignore and commit. note you might want to add annotations to the file afterwards.
disabling PHP-FPM fixed my issue.
This is solution:
@item.Published.Value.ToString("dd. MM. yyyy")
Before ToString() use Value.
Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:
def check_authorization(f):
def wrapper(*args):
print args[0].url
return f(*args)
return wrapper
class Client(object):
def __init__(self, url):
self.url = url
@check_authorization
def get(self):
print 'get'
>>> Client('http://www.google.com').get()
http://www.google.com
get
The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr
if you don't want to hardcode the attribute name:
def check_authorization(attribute):
def _check_authorization(f):
def wrapper(self, *args):
print getattr(self, attribute)
return f(self, *args)
return wrapper
return _check_authorization
For a single dimension array, you use the Length
property:
int size = theArray.Length;
For multiple dimension arrays the Length
property returns the total number of items in the array. You can use the GetLength
method to get the size of one of the dimensions:
int size0 = theArray.GetLength(0);
I had the same issue using the request module to proxy POST request from somewhere else and it was because I left the host property in the header (I was copying the header from the original request).
There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse
for more details. In this case, you probably want:
git diff HEAD@{1}
The @{1}
means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD
on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.
I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do
git diff HEAD@{1} filename
This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
This answers a different question:
If trying to figure out if an OBJECT (not class) has a property,
OBJECT.GetType().GetProperty("PROPERTY") != null
returns true if (but not only if) the property exists.
In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
helped me here.
Edit: Nowadays, it's probably smart to use the nameof
operator instead of the stringified property name.
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
@with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
tomaterial = models.ForeignKey(Material, related_name = 'tomaterial')
frommaterial = models.ForeignKey(Material, related_name = 'frommaterial')
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
So when you will have to access this data you only can use related name
bom = material.tomaterial.all().order_by('-creation_time')
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)
I believe running from Eclipse, if you're using "myconf.properties" as the relative path, You file structure should look somehting like this
ProjectRoot
src
bin
myconf.properties
Eclipse will look for the the file in the project root dir if no other dirs are specified in the file path
The problem is not the range, the problem is how the end of slice is calculated.
with a fixed number 10
the simple for
loop is ok but with a calculated size
like bfl.Size()
you get a function-call on every iteration. A simple range
over int32
would help because this evaluate the bfl.Size()
only once.
type BFLT PerfServer
func (this *BFLT) Call() {
bfl := MqBufferLCreateTLS(0)
for this.ReadItemExists() {
bfl.AppendU(this.ReadU())
}
this.SendSTART()
// size := bfl.Size()
for i := int32(0); i < bfl.Size() /* size */; i++ {
this.SendU(bfl.IndexGet(i))
}
this.SendRETURN()
}
The following steps worked for me:
The Safari built in dev tool is great. I have to admit that Firebug on Firefox is my long time favorite, but I think that the Safari tool do a great job too!
A web service differs from a web site in that a web service provides information consumable by software rather than humans. As a result, we are usually talking about exposed JSON, XML, or SOAP services.
Web services are a key component in "mashups". Mashups are when information from many websites is automatically aggregated into a new and useful service. For example, there are sites that aggregate Google Maps with information about police reports to give you a graphical representation of crime in your area. Another type of mashup would be to take real stock data provided by another site and combine it with a fake trading application to create a stock-market "game".
Web services are also used to provide news (see RSS), latest items added to a site, information on new products, podcasts, and other great features that make the modern web turn.
Hope this helps!
An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.
Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.
Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.
The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe
Chet and Daniel are both from Google.
Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4
Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q
A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.
You might check out this tutorial for working with it.
Use the System.Runtime.InteropServices.Marshal
class:
String SecureStringToString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(valuePtr);
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32)
:
void HandleSecureString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
for (int i=0; i < value.Length; i++) {
short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
// handle unicodeChar
}
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
select CASE
WHEN TRY_CONVERT(bigint,Mtrl_Nbr) = 0
THEN ''
ELSE substring(Mtrl_Nbr, patindex('%[^0]%',Mtrl_Nbr), 18)
END
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
In Notepad++ to replace, hit Ctrl+H to open the Replace menu.
Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines
value="4"
value="403"
value="200"
value="201"
value="116"
value="15"
using the .*"\d+"
pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses (
and )
, like that: .*"(\d+)"
. So now in your replacement you can simply write $1
, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)"
, $1
will return the string value
and $2
will return the number.
So by using:
Find: .*"(\d+)"
Replace: $1
It will return you
4
403
200
201
116
15
Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)"
would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)
This should do it:
<style>
body {
background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root
can run smoothly.
If you want to reassign an element in an array, you can do the following:
var blah = ['Jan', 'Fed', 'Apr'];
console.log(blah);
function reassign(array, index, newValue) {
array[index] = newValue;
return array;
}
reassign(blah, [2], 'Mar');
Did anybody find CodeLens (the reference counter) problems with startup performance?
Disable CodeLens (menu Tools → Options → text editor → All languages → CodeLens)
Disable Git Source Control too (menu Tools* → Options → Source control)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)
should works
There are much nicer ways to do it.
Install nuget via chocolatey - much nicer. Install chocolatey: https://chocolatey.org/, then run
cinst Nuget.CommandLine
in your command prompt. This will install nuget and setup environment paths, so nuget is always available.
For Oracle 11g this may not work as you may receive an error like below
Error report:
SQL Error: ORA-00026: missing or invalid session ID
00026. 00000 - "missing or invalid session ID"
*Cause: Missing or invalid session ID string for ALTER SYSTEM KILL SESSION.
*Action: Retry with a valid session ID.
To rectify this, use below code to identify the sessions
SQL> select inst_id,sid,serial# from gv$session
or v$session
NOTE : v$session do not have inst_id field
and Kill them using
alter system kill session 'sid,serial,@inst_id' IMMEDIATE;
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
Try this one -
DECLARE @i FLOAT = 6.677756
SELECT
ROUND(@i, 2)
, FORMAT(@i, 'N2')
, CAST(@i AS DECIMAL(18,2))
, SUBSTRING(PARSENAME(CAST(@i AS VARCHAR(10)), 1), PATINDEX('%.%', CAST(@i AS VARCHAR(10))) - 1, 2)
, FLOOR((@i - FLOOR(@i)) * 100)
Output:
----------------------
6,68
6.68
6.68
67
67
Here I am adding my JSfiddle example for stopPropagation vs stopImmediatePropagation. JSFIDDLE
let stopProp = document.getElementById('stopPropagation');_x000D_
let stopImmediate = document.getElementById('stopImmediatebtn');_x000D_
let defaultbtn = document.getElementById("defalut-btn");_x000D_
_x000D_
_x000D_
stopProp.addEventListener("click", function(event){_x000D_
event.stopPropagation();_x000D_
console.log('stopPropagation..')_x000D_
_x000D_
})_x000D_
stopProp.addEventListener("click", function(event){_x000D_
console.log('AnotherClick')_x000D_
_x000D_
})_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
event.stopImmediatePropagation();_x000D_
console.log('stopimmediate')_x000D_
})_x000D_
_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
console.log('ImmediateStop Another event wont work')_x000D_
})_x000D_
_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
alert("Default Clik");_x000D_
})_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
console.log("Second event defined will also work same time...")_x000D_
})
_x000D_
div{_x000D_
margin: 10px;_x000D_
}
_x000D_
<p>_x000D_
The simple example for event.stopPropagation and stopImmediatePropagation?_x000D_
Please open console to view the results and click both button._x000D_
</p>_x000D_
<div >_x000D_
<button id="stopPropagation">_x000D_
stopPropagation-Button_x000D_
</button>_x000D_
</div>_x000D_
<div id="grand-div">_x000D_
<div class="new" id="parent-div">_x000D_
<button id="stopImmediatebtn">_x000D_
StopImmediate_x000D_
</button>_x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<button id="defalut-btn">_x000D_
Normat Button_x000D_
</button>_x000D_
</div>
_x000D_
Long answer: it is possible!
In xampp directory comment line apache/conf/httpd.conf:458
#Include "conf/extra/httpd-perl.conf"
In xampp directory do next replaces in files:
from
"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*
to
set XAMPPPHPDIR=C:\xampp\php
"%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*
from
"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*
to
set XAMPPPHPDIR=C:\xampp\php
"%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*
from
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php"
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"
to
IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\"
IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"
from
%~dp0php.exe %~dp0pharcommand.phar %*
to
"%~dp0php.exe" "%~dp0pharcommand.phar" %*
Enjoy new XAMPP with PHP 5.3
Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2
You can make use of location service available in @angular/common and via this below code you can get the location or current URL
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) {
router.events.subscribe((val) => {
if(location.path() != ''){
this.route = location.path();
} else {
this.route = 'Home'
}
});
}
ngOnInit() {
}
}
here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts
Your code looks good, did you forget to install PostFix on your server?
sudo apt-get install postfix
It worked for me ;)
Cheers
Just remove the .value
, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index]
, the .value
would be getting the value
property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value
would also be undefined
.
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine()
method before each call to nextLine()
, make sure the correct encoding is passed to the Scanner
constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
After testing most of the switches this worked for me:
xcopy C:\folder1 C:\folder2\folder1 /t /e /i /y
This will copy the folder folder1
into the folder folder2
. So the directory tree would look like:
C:
Folder1
Folder2
Folder1
Here is the command-line approach to answer this question:
gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"
This will open the port 9090
for the instances that you name. Omitting --source-tags
and --source-ranges
will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create
command manual
The previous answers are great, but Google recommends using the newer gcloud
commands instead of the gcutil
commands.
PS:
To get an idea of Google's firewall rules, run gcloud compute firewall-rules list
and view all your firewall rules
This works for me :
CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
ALTER TABLE [dbo].[TableName]
DROP CONSTRAINT FK_TableName_TableName2
As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.
Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class
(or rather, a subclass of Class
) corresponding to it. (When you say class Foo
, you're really declaring a constant Foo
and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.
The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.
In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.
Input elements have a property called disabled
. When the form submits, just run some code like this:
var myInput = document.getElementById('myInput');
myInput.disabled = true;
You can auto redirect by HTTP Status Code 301 or 302.
For PHP:
<?php
Header("HTTP/1.1 301 Moved Permanently");
Header("Location: http://www.redirect-url.com");
?>
I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior).
But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.
**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :
Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.
Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.
Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.
When the post-link
function is called, all previous steps have taken place - binding, transclusion, etc.
This is typically a place to further manipulate the rendered DOM.
Replacing all zeroes to NA:
df[df == 0] <- NA
Explanation
1. It is not NULL
what you should want to replace zeroes with. As it says in ?'NULL'
,
NULL represents the null object in R
which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that
data.frame(x = c(1, NULL, 2))
# x
# 1 1
# 2 2
That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA'
we see that
NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.
Importantly, NA
is of length 1 so that R reserves some space for it. E.g.,
data.frame(x = c(1, NA, 2))
# x
# 1 1
# 2 NA
# 3 2
Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL
values).
Now you could replace zeroes by NULL
in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var
, cov
, or cor
, that is actually equivalent to first replacing zeroes with NA
and setting the value of use
as "complete.obs"
. Typically, however, this is unsatisfactory as it leads to extra information loss.
2. Instead of running some sort of loop, in the solution I use df == 0
vectorization. df == 0
returns (try it) a matrix of the same size as df
, with the entries TRUE
and FALSE
. Further, we are also allowed to pass this matrix to the subsetting [...]
(see ?'['
). Lastly, while the result of df[df == 0]
is perfectly intuitive, it may seem strange that df[df == 0] <- NA
gives the desired effect. The assignment operator <-
is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'
.
1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.
Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
You could also tell MySQL to execute the commands in the given file, like so:
mysql --user=root --password=sa casemanager < CaseManager.sql
Try changing your code to this:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
I got the answer.
Here is the code:
SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Debug your CSS for Ghost CSS Elements.
Use this bookmark to debug your CSS: https://blog.wernull.com/2013/04/debug-ghost-css-elements-causing-unwanted-scrolling/
Or add the CSS directly yourself:
* {
background: #000 !important;
color: #0f0 !important;
outline: solid #f00 1px !important;
}
In my case a Facebook Like Button caused the problem.
A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.
Having said that, the Sysinternals tools are great for this.
In my case I had to enable virtualization in the BIOS setting.
And after all above steps, it finally works :-)
out
or ref
(since that changes the reference, not the object). A programmer therefore knows that if string x = "abc"
at the start of a method, and that doesn't change in the body of the method, then x == "abc"
at the end of the method."abc" == "ab" + "c"
. While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).Christmas.AddMonths(1)
produces a new DateTime
rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.return this
. Since the copy can't be changed anyway, pretending something is its own copy is safe.In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).
It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).
Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.
You can make your pattern case insensitive by doing:
Pattern p = Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
I did the following:
npm install -g
[email protected]
c:/users/[username]/AppData/Roaming/npm-cache
npm cache clean --force
npm install
.There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.
HTML:
<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="myButton" />
</form>
JavaScript:
$(document).ready(function() {
$('#myButton').click(function() {
foo($('#formValueId').val());
});
});
If one is wanting to iterate through an array (Array
or more generally any SequenceType
) in reverse. You have a few additional options.
First you can reverse()
the array and loop through it as normal. However I prefer to use enumerate()
much of the time since it outputs a tuple containing the object and it's index.
The one thing to note here is that it is important to call these in the right order:
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray's reverseEnumerator
)
walks the array backward but outputs ascending indexes.
It means the file containing main
doesn't have access to the player
structure definition (i.e. doesn't know what it looks like).
Try including it in header.h
or make a constructor-like function that allocates it if it's to be an opaque object.
If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:
struct player *
init_player(...)
{
struct player *p = calloc(1, sizeof *p);
/* ... */
return p;
}
However if the implementation shouldn't be hidden - i.e. main
should legally say p->canPlay = 1
it would be better to put the definition of the structure in header.h
.
First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer()
.
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
Use NameValuedCollection.
Good starting point is here. Straight from the link.
System.Collections.Specialized.NameValueCollection myCollection
= new System.Collections.Specialized.NameValueCollection();
myCollection.Add(“Arcane”, “http://arcanecode.com”);
myCollection.Add(“PWOP”, “http://dotnetrocks.com”);
myCollection.Add(“PWOP”, “http://dnrtv.com”);
myCollection.Add(“PWOP”, “http://www.hanselminutes.com”);
myCollection.Add(“TWIT”, “http://www.twit.tv”);
myCollection.Add(“TWIT”, “http://www.twit.tv/SN”);
You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:
public void SomeMethod()
{
StartCoroutine(SomeCoroutine());
}
private IEnumerator SomeCoroutine()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds (3);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds (3);
TextUI.text = ("The lowest number you can pick is " + min);
}
You can retrieve the date by using the getDate function:
$("#datepicker").datepicker( 'getDate' );
The value is returned as a JavaScript Date object.
If you want to use this value when the user selects a date, you can use the onSelect event:
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
}
});
The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.
See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.
Looks like the mysql server is not started.
Look to the official documentation of MySQL how you can start a service under windows.
Install the server as a service using this command: C:> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --install
For me, none of the solutions work. I had to download the XCode from the App store. It's too big around 12 GB. After installing it works like a charm.
Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...
In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.
This happens because LatLngBounds()
does not take two arbitrary points as parameters, but SW and NE points
use the .extend()
method on an empty bounds object
var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);
Demo at http://jsfiddle.net/gaby/22qte/
Shell variables have no type, so the simplest way is to use the return type test
command:
if [ $var -eq $var 2> /dev/null ]; then ...
(Or else parse it with a regexp)
It is also possible to place the MySQL data directory in a tmpfs in thus speeding up the database write and read calls. It might not be the most efficient way to do this but sometimes you can't just change the storage engine.
Here is my fstab entry for my MySQL data directory
none /opt/mysql/server-5.6/data tmpfs defaults,size=1000M,uid=999,gid=1000,mode=0700 0 0
You may also want to take a look at the innodb_flush_log_at_trx_commit=2 setting. Maybe this will speedup your MySQL sufficently.
innodb_flush_log_at_trx_commit changes the mysql disk flush behaviour. When set to 2 it will only flush the buffer every second. By default each insert will cause a flush and thus cause more IO load.
not() is a function in xpath (as opposed to an operator), so
//a[not(contains(@id, 'xx'))]
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
You can also use the following format
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
You can stack changes this way:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day
and <timestamp>
, you can just pass in the timestamp as the second parameter of strtotime
.
git show
is more a plumbing command than git log
, and has the same formatting options:
git show -s --format=%B SHA1
In Additional
Thread thread = new Thread(delegate() { download(i); });
thread.Start();
Exported variables such as $HOME
and $PATH
are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.
$ env | grep '^variable='
$ # No environment variable called variable
$ variable=Hello # Create local (non-exported) variable with value
$ env | grep '^variable='
$ # Still no environment variable called variable
$ export variable # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$
For more information, see the entry for the export
builtin in the GNU Bash manual, and also the sections on command execution environment and environment.
Note that non-exported variables will be available to subshells run via ( ... )
and similar notations because those subshells are direct clones of the main shell:
$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$
The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.
Some information about subshells can be found under command grouping and command execution environment in the Bash manual.
The below answer is in reference to the latest ng-bootstrap
Install
npm install --save @ng-bootstrap/ng-bootstrap
app.module.ts
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
...
],
imports: [
...
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Component Controller
import { TemplateRef, ViewChild } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-app-registration',
templateUrl: './app-registration.component.html',
styleUrls: ['./app-registration.component.css']
})
export class AppRegistrationComponent implements OnInit {
@ViewChild('editModal') editModal : TemplateRef<any>; // Note: TemplateRef
constructor(private modalService: NgbModal) { }
openModal(){
this.modalService.open(this.editModal);
}
}
Component HTML
<ng-template #editModal let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Edit Form</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="dateOfBirth">Date of birth</label>
<div class="input-group">
<input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"></button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close()">Save</button>
</div>
</ng-template>
The above suggestion of Ctrl
+Shift
+-
code folds all code blocks recursively. I only wanted to fold the methods for my classes.
Code
> Folding
> Expand all to level
> 1
I managed to achieve this by using the menu option Code > Folding > Expand all to level > 1
.
I re-assigned it to Ctrl
+NumPad-1
which gives me a quick way to collapse my classes down to their methods.
This works at the 'block level' of the file and assumes that you have classes defined at the top level of your file, which works for code such as PHP but not for JavaScript (nested closures etc.)
Following solution is better than bootbox.js, because
digimango.messagebox.js:
const dialogTemplate = '\_x000D_
<div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
<div class ="modal-dialog">\_x000D_
<div class ="modal-content">\_x000D_
<div class ="modal-body">\_x000D_
<p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
<p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
</div>\_x000D_
<div class ="modal-footer">\_x000D_
<button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
<button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
var iDiv = document.createElement('div');_x000D_
iDiv.id = 'digimango_MessageBoxContainer';_x000D_
document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
$("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
}_x000D_
_x000D_
var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
if (options == null) {_x000D_
okButtonName = 'OK';_x000D_
cancelButtonName = null;_x000D_
showTextBox = null;_x000D_
textBoxDefaultText = null;_x000D_
} else {_x000D_
okButtonName = options.okButtonName;_x000D_
cancelButtonName = options.cancelButtonName;_x000D_
showTextBox = options.showTextBox;_x000D_
textBoxDefaultText = options.textBoxDefaultText;_x000D_
}_x000D_
_x000D_
if (showTextBox == true) {_x000D_
if (textBoxDefaultText == null)_x000D_
$('#digimango_messageBoxTextArea').val('');_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
$('#digimango_messageBoxTextArea').show();_x000D_
}_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
if (okButtonName != null)_x000D_
$('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
else_x000D_
$('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
if (cancelButtonName == null)_x000D_
$('#digimango_messageBoxCancelButton').hide();_x000D_
else {_x000D_
$('#digimango_messageBoxCancelButton').show();_x000D_
$('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
}_x000D_
_x000D_
$('#digimango_messageBoxOkButton').unbind('click');_x000D_
$('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
$('#digimango_messageBoxCancelButton').unbind('click');_x000D_
$('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
if (significance == 'error')_x000D_
content.attr('class', 'text-danger');_x000D_
else if (significance == 'warning')_x000D_
content.attr('class', 'text-warning');_x000D_
else_x000D_
content.attr('class', 'text-success');_x000D_
_x000D_
content.html(msg);_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$("#digimango_messageBox").modal();_x000D_
_x000D_
digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
// JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
// thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
// clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
// how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
// not execute the last line in this function._x000D_
if (typeof (event.data.callback) != 'undefined')_x000D_
event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
To use digimango.messagebox.js:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title>A useful generic message box</title>_x000D_
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
<script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
function testAlert() {_x000D_
messageBox('Something went wrong!', 'error');_x000D_
}_x000D_
_x000D_
function testAlertWithCallback() {_x000D_
messageBox('Something went wrong!', 'error', null, function () {_x000D_
messageBox('OK clicked.');_x000D_
});_x000D_
}_x000D_
_x000D_
function testConfirm() {_x000D_
messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
});_x000D_
}_x000D_
_x000D_
function testPrompt() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
function testPromptWithDefault() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
<a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
<a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
<a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
<a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Also, their "device dashboard" stats at:
http://developer.android.com/about/dashboards/index.html#Screens
can be pretty helpful. They are current and derived from Android Market visits.
You can write DateTime? newdate = null;
Add these lines of code in your htaccess file. I hope it will solve your problem.
<IfModule mod_php5.c>
php_value max_execution_time 259200
</IfModule>
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
You can't do this, because case
labels are actually just entry points into the containing block.
This is most clearly illustrated by Duff's device. Here's some code from Wikipedia:
strcpy(char *to, char *from, size_t count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);
}
}
Notice how the case
labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a case
label is the same as using goto
, so you aren't allowed to jump over a local variable with a constructor.
As several other posters have indicated, you need to put in a block of your own:
switch (...) {
case FOO: {
MyObject x(...);
...
break;
}
...
}
Copied from Web Applications:
=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")
No, you can not.
You can call a function
from a stored procedure
and debug a stored procedure
(this will step into the function
)
The documentation says:
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,
> $("form").validate() is called first.
Did you do that? The error message kind of indicates that you didn't.
You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval
type directly:
struct timeval GetTimeStamp() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv;
}
The second, and for me less desirable, choice is to build a uint64_t out of a timeval
:
uint64_t GetTimeStamp() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}
Changing to format: 'dd/mm/yyyy'
didn't work for me, and changing that to dateFormat: 'dd/mm/yyyy'
added year multiple times, The finest one for me was,
dateFormat: 'dd/mm/yy'
Try below:
try:
raise ValueError("Original message. ")
except Exception as err:
message = 'My custom error message. '
# Change the order below to "(message + str(err),)" if custom message is needed first.
err.args = (str(err) + message,)
raise
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
1 try:
----> 2 raise ValueError("Original message")
3 except Exception as err:
4 message = 'My custom error message.'
5 err.args = (str(err) + ". " + message,)
ValueError: Original message. My custom error message.
If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html
.
Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries
Then following codes does the job perfectly (No need of beautifulsoup and fancy html):
import pandas as pd
import requests
url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()
Below is a code snippet I used to fetch zipped csv file, please have a look:
Python 2:
from StringIO import StringIO
from zipfile import ZipFile
from urllib import urlopen
resp = urlopen("http://www.test.com/file.zip")
zipfile = ZipFile(StringIO(resp.read()))
for line in zipfile.open(file).readlines():
print line
Python 3:
from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
# or: requests.get(url).content
resp = urlopen("http://www.test.com/file.zip")
zipfile = ZipFile(BytesIO(resp.read()))
for line in zipfile.open(file).readlines():
print(line.decode('utf-8'))
Here file
is a string. To get the actual string that you want to pass, you can use zipfile.namelist()
. For instance,
resp = urlopen('http://mlg.ucd.ie/files/datasets/bbc.zip')
zipfile = ZipFile(BytesIO(resp.read()))
zipfile.namelist()
# ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']
DELETE TB1, TB2
FROM customer_details
LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
WHERE TB1.cust_id = $id
The best (and only) method is to set correct HTTP headers, specifically these ones: "Expires", "Last-Modified", and "Cache-Control". How to do it depends on the server software you use.
In Improving performance… look for "Optimization on server side" for general considerations and relevant links and for "Client-side cache" for the Apache-specific advice.
If you are a fan of nginx (or nginx in plain English) like I am, you can easily configure it too:
location /images {
...
expires 4h;
}
In the example above any file from /images/ will be cached on the client for 4 hours.
Now when you know right words to look for (HTTP headers "Expires", "Last-Modified", and "Cache-Control"), just peruse the documentation of the web server you use.
SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
rank,
null,
null,
null,
null,
COLUMN + " DESC",
null);
In MacOS, Mysql's executable file is located in /usr/local/mysql/bin/mysql
and you can easily login to it with the following command:
/usr/local/mysql/bin/mysql -u USERNAME -p
But this is a very long command and very boring, so you can add mysql path to Os's Environment variable and access to it much easier.
For macOS Catalina
and later
Starting with macOS Catalina, Mac devices use zsh
as the default login shell and interactive shell and you have to update .zprofile
file in your home directory.
echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofile
source ~/.zprofile
mysql -u USERNAME -p
For macOS Mojave
and earlier
Although you can always switch to zsh
, bash
is the default shell in macOS Mojave and earlier and with bash
you have to update .bash_profile
file.
echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.bash_profile
source ~/.bash_profile
mysql -u USERNAME -p
3306
and change it to 3307
Using find
:
find . -maxdepth 1 -type f
Using the -maxdepth 1
option ensures that you only look in the current directory (or, if you replace the .
with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.
If you are using JPA with EclipseLink, you'll have to set the @PrivateOwned annotation.
Documentation: Eclipse Wiki - Using EclipseLink JPA Extensions - Chapter 1.4 How to Use the @PrivateOwned Annotation
http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:
<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>my_config.properties</value></property>
<property name="properties">
<props>
<prop key="entry.1">123</prop>
</props>
</property>
</bean>
You could create a trigger to delete the referenced rows in before deleting the job.
DELIMITER $$
CREATE TRIGGER before_jobs_delete
BEFORE DELETE ON jobs
FOR EACH ROW
BEGIN
delete from advertisers where advertiser_id=OLD.advertiser_id;
END$$
DELIMITER ;
JSONObject obj=(JSONObject)JSONValue.parse(content);
JSONArray arr=(JSONArray)obj.get("units");
System.out.println(arr.get(1)); //this will print {"id":42,...sities ..}
@cyberz is right but explain it reverse
Nested classes are cool for hiding implementation details.
List:
class List
{
public:
List(): head(nullptr), tail(nullptr) {}
private:
class Node
{
public:
int data;
Node* next;
Node* prev;
};
private:
Node* head;
Node* tail;
};
Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.
Look at std::list
or std::map
they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list
.
2019's answer as this is still actively seen today
You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.
original hack from 2015 that still works in some situations
You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.
If you cannot pull it out of the div for some reason, you should change the position style with this css:
.full-width-div {
position: absolute;
width: 100%;
left: 0;
}
Instead of absolute, you could also use fixed, but then it will not move as you scroll.
Combination of Dasha's and MMT solutions:
Ext.getCmp('yourGridId').getView().ds.reload();
Bootstrap.yml is used to fetch config from the server. It can be for a Spring cloud application or for others. Typically it looks like:
spring:
application:
name: "app-name"
cloud:
config:
uri: ${config.server:http://some-server-where-config-resides}
When we start the application it tries to connect to the given server and read the configuration based on spring profile mentioned in run/debug configuration.
If the server is unreachable application might even be unable to proceed further. However, if configurations matching the profile are present locally the server configs get overridden.
Good approach:
Maintain a separate profile for local and run the app using different profiles.
This is not possible now, but there is a work around. You can engage with the user in the public realm and ask them to send you private messages, but you can't send private messages back, only public ones. Of course, this all depends on if the user gives you the correct permissions.
If you have given permission to access a person's friends, you can then theoretically post on that users wall with references to each one of the friends, asking them to publicly interact with you and then potentially privately message you.
Get Friends
#if authenticated
https://graph.facebook.com/me/friends
http://developers.facebook.com/docs/reference/api/user/
Post in the Public Domain
http://developers.facebook.com/docs/reference/api/status/
Get Messages sent to that user (if given permission)
http://developers.facebook.com/docs/reference/api/message/
C# - serialData is ReceivedEventHandler
in TextBox
.
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));
Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.
Serial:
Serial.print(rnd);
Serial.( '\n' ); //carriage return
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
Give each input
a name
attribute. Only the clicked input
's name
attribute will be sent to the server.
<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">
And then
<?php
if (isset($_POST['publish'])) {
# Publish-button was clicked
}
elseif (isset($_POST['save'])) {
# Save-button was clicked
}
?>
Edit: Changed value
attributes to alt
. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]
?
Edit: Since this keeps getting upvotes I went ahead and changed the weird alt
/value
code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image]
.
To build on Ilya's answer try the following query:
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name
(this one works without modification with an MDB)
ACCDB users may need to do something like this
SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~")
AND ((Left([Name],4))<>"MSys")
AND ((MSysObjects.Type) In (1,4,6))
AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name
As there is an extra table is included that appears to be a system table of some sort.
The is
operator in Python probably doesn't do what you expect. Instead of this:
if numpy.array_equal(tmp,universe_array) is True:
break
I would write it like this:
if numpy.array_equal(tmp,universe_array):
break
The is
operator tests object identity, which is something quite different from equality.
See the docs: https://getbootstrap.com/docs/4.0/utilities/display/
In order to hide the content on mobile and display on the bigger devices you have to use the following classes:
d-none d-sm-block
The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.
I suggest to read about that before migration:
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
As of React 16.3 React.createRef
can be used, (use ref.current
to access)
var ref = React.createRef()
var parent = (
<div>
<Child ref={ref} />
<button onClick={e=>console.log(ref.current)}
</div>
);
React.renderComponent(parent, document.body)
Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail
and firstOrFail
methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
If it's a maven project, go to file>import>maven project >existing maven project, then browse for the folder that contains the project, select folder then click finish. That worked for me
In the current documentation we can specify a build.json with the keystore:
{
"android": {
"debug": {
"keystore": "..\android.keystore",
"storePassword": "android",
"alias": "mykey1",
"password" : "password",
"keystoreType": ""
},
"release": {
"keystore": "..\android.keystore",
"storePassword": "",
"alias": "mykey2",
"password" : "password",
"keystoreType": ""
}
}
}
And then, execute the commando with --buildConfig argumente, this way:
cordova run android --buildConfig
My Attempt ( JsFiddle)
Javascript
$(document).ready(function () {
$('#buttons input[type=button]').on('click', function () {
var qty = $(this).data('quantity');
var price = $('#totalPrice').text();
$('#count').val(price * qty);
});
});
Html
Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
<input id='qty2' type="button" data-quantity='2' value="2
Qty">
<input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4
Qty">
</div>
<br>Total
<input type="text" id="count" value="1">
The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application
if you are trying to execute mysql query withouth defining connectionstring, you will get this error.
Probably you forgat to define connection string before execution. have you check this out? (sorry for bad english)
You are modifying the list book_shop.values()[i]
, which is not getting updated in the dictionary. Whenever you call the values()
method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
I suppose that Chrome's behavior is more consistent with the CSS specification (though it's less intuitive). According to Flexbox specification, the default stretch
value of align-self
property changes only the used value of the element's "cross size property" (height
, in this case). And, as I understand the CSS 2.1 specification, the percentage heights are calculated from the specified value of the parent's height
, not its used value. The specified value of the parent's height
isn't affected by any flex properties and is still auto
.
Setting an explicit height: 100%
makes it formally possible to calculate the percentage height of the child, just like setting height: 100%
to html
makes it possible to calculate the percentage height of body
in CSS 2.1.
You need to put the last()
indexing on the nodelist result, rather than as part of the selection criteria. Try:
(//element[@name='D'])[last()]
The way you describe is the way I've always done it. Since it's totally generic, you can always break that functionality out into a mixin class and inherit it in classes where you want that functionality.
class CommonEqualityMixin(object):
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
class Foo(CommonEqualityMixin):
def __init__(self, item):
self.item = item