Programs & Examples On #Sh

sh is the standard Unix shell since Version 7 Unix. POSIX has standardized shell behavior based on the Bourne Shell, and portable shell scripts should conform to the standardized syntax. Use this tag for questions that apply to Bourne/POSIX-style shells. For shell scripts with errors, please check them in http://shellcheck.net before posting here.

Difference between sh and bash

Other answers generally pointed out the difference between Bash and a POSIX shell standard. However, when writing portable shell scripts and being used to Bash syntax, a list of typical bashisms and corresponding pure POSIX solutions is very handy. Such list has been compiled when Ubuntu switched from Bash to Dash as default system shell and can be found here: https://wiki.ubuntu.com/DashAsBinSh

Moreover, there is a great tool called checkbashisms that checks for bashisms in your script and comes handy when you want to make sure that your script is portable.

What does the line "#!/bin/sh" mean in a UNIX shell script?

When you try to execute a program in unix (one with the executable bit set), the operating system will look at the first few bytes of the file. These form the so-called "magic number", which can be used to decide the format of the program and how to execute it.

#! corresponds to the magic number 0x2321 (look it up in an ascii table). When the system sees that the magic number, it knows that it is dealing with a text script and reads until the next \n (there is a limit, but it escapes me atm). Having identified the interpreter (the first argument after the shebang) it will call the interpreter.

Other files also have magic numbers. Try looking at a bitmap (.BMP) file via less and you will see the first two characters are BM. This magic number denotes that the file is indeed a bitmap.

How can I declare and use Boolean variables in a shell script?

Use arithmetic expressions.

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true

Output:

true
not false

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

I just assigned a variable, but echo $variable shows something else

In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

echo "$var"

This gives the expected value in all the examples given. Always quote variable references!


Why?

When a variable is unquoted, it will:

  1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

    Before: /* Foobar is free software */

    After: /*, Foobar, is, free, software, */

  2. Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

    Before: /*

    After: /bin, /boot, /dev, /etc, /home, ...

  3. Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

    /bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
    

    instead of the variable's value.

When the variable is quoted it will:

  1. Be substituted for its value.
  2. There is no step 2.

This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

How to comment out particular lines in a shell script

You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):

:10,20 s/^/#

with 10 and 20 being the start and end line numbers of the lines you want to comment out

and to undo when you are complete:

:10,20 s/^#//

Compare a string using sh shell

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test says that you use -z to match for empty strings.

How to check if a string contains a substring in Bash

You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:

string='My long string'
if [[ $string == *"My long"* ]]; then
  echo "It's there!"
fi

Note that spaces in the needle string need to be placed between double quotes, and the * wildcards should be outside. Also note that a simple comparison operator is used (i.e. ==), not the regex operator =~.

What does $@ mean in a shell script?

These are the command line arguments where:

$@ = stores all the arguments in a list of string
$* = stores all the arguments as a single string
$# = stores the number of arguments

"echo -n" prints "-n"

There are multiple versions of the echo command, with different behaviors. Apparently the shell used for your script uses a version that doesn't recognize -n.

The printf command has much more consistent behavior. echo is fine for simple things like echo hello, but I suggest using printf for anything more complicated.

What system are you on, and what shell does your script use?

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

How to run .sh on Windows Command Prompt?

you can use also cmder

Cmder is a software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start

Screenshot

cmder.net

Count occurrences of a char in a string using Bash

awk works well if you your server has it

var="text,text,text,text" 
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

How can I remove the extension of a filename in a shell script?

Answers provided previously have problems with paths containing dots. Some examples:

/xyz.dir/file.ext
./file.ext
/a.b.c/x.ddd.txt

I prefer to use |sed -e 's/\.[^./]*$//'. For example:

$ echo "/xyz.dir/file.ext" | sed -e 's/\.[^./]*$//'
/xyz.dir/file
$ echo "./file.ext" | sed -e 's/\.[^./]*$//'
./file
$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^./]*$//'
/a.b.c/x.ddd

Note: If you want to remove multiple extensions (as in the last example), use |sed -e 's/\.[^/]*$//':

$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^/]*$//'
/a.b.c/x

However, this method will fail in "dot-files" with no extension:

$ echo "/a.b.c/.profile" | sed -e 's/\.[^./]*$//'
/a.b.c/

To cover also such cases, you can use:

$ echo "/a.b.c/.profile" | sed -re 's/(^.*[^/])\.[^./]*$/\1/'
/a.b.c/.profile

How to copy and edit files in Android shell?

Also if the goal is only to access the files on the phone. There is a File Explorer that is accessible from the Eclipse DDMS perspective. It lets you copy file from and to the device. So you can always get the file, modify it and put it back on the device. Of course it enables to access only the files that are not read protected.

If you don't see the File Explorer, from the DDMS perspective, go in "Window" -> "Show View" -> "File Explorer".

How to do a logical OR operation for integer comparison in shell scripting?

And in Bash

 line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
 vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
 echo "-------->"${line1}
    if [ -z $line1 ] && [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
   fi

OR in Bash

line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef|  grep wowzaDataSync | grep -v grep  | awk '{print $2}'`
echo "-------->"${line1}
   if [ -z $line1 ] || [ ! -z $vpid ]
    then
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Process Is Working Fine"
    else
            echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` :: 
            "Prcess Hanging Due To Exception With PID :"${pid}
  fi

What's a .sh file?

What is a file with extension .sh?

It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form

#!/path/to/interpreter

they will use that particular interpreter. Your file has the first line:

#!/bin/bash

and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.

Depending upon the interpreter you will have different language in which the file is written.

Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).

If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.

How to execute a shell script

Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.

You will need to make the file executable. Let's assume that you have downloaded your file as file.sh, you can then run in your terminal:

chmod +x file.sh

chmod is a command for changing file's permissions, +x sets execute permissions (in this case for everybody) and finally you have your file name.

You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:

File permissions in XUbuntu

If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:

bash file.sh

The shell should be the same as in the first line of your script.

How safe is it?

You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.

Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).

Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".

Shell script current directory?

You could do this yourself by checking the output from pwd when running it. This will print the directory you are currently in. Not the script.

If your script does not switch directories, it'll print the directory you ran it from.

Check if a file exists with wildcard in shell script

The bash code I use

if ls /syslog/*.log > /dev/null 2>&1; then 
   echo "Log files are present in /syslog/; 
fi

Thanks!

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How to run a cron job inside a docker container?

You can copy your crontab into an image, in order for the container launched from said image to run the job.

See "Run a cron job with Docker" from Julien Boulay in his Ekito/docker-cron:

Let’s create a new file called "hello-cron" to describe our job.

* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# An empty line is required at the end of this file for a valid cron file.

If you are wondering what is 2>&1, Ayman Hourieh explains.

The following Dockerfile describes all the steps to build your image

FROM ubuntu:latest
MAINTAINER [email protected]

RUN apt-get update && apt-get -y install cron

# Copy hello-cron file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron
 
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron

# Apply cron job
RUN crontab /etc/cron.d/hello-cron
 
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
 
# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

(see Gaafar's comment and How do I make apt-get install less noisy?:
apt-get -y install -qq --force-yes cron can work too)

As noted by Nathan Lloyd in the comments:

Quick note about a gotcha:
If you're adding a script file and telling cron to run it, remember to
RUN chmod 0744 /the_script
Cron fails silently if you forget.


OR, make sure your job itself redirect directly to stdout/stderr instead of a log file, as described in hugoShaka's answer:

 * * * * * root echo hello > /proc/1/fd/1 2>/proc/1/fd/2

Replace the last Dockerfile line with

CMD ["cron", "-f"]

See also (about cron -f, which is to say cron "foreground") "docker ubuntu cron -f is not working"


Build and run it:

sudo docker build --rm -t ekito/cron-example .
sudo docker run -t -i ekito/cron-example

Be patient, wait for 2 minutes and your commandline should display:

Hello world
Hello world

Eric adds in the comments:

Do note that tail may not display the correct file if it is created during image build.
If that is the case, you need to create or touch the file during container runtime in order for tail to pick up the correct file.

See "Output of tail -f at the end of a docker CMD is not showing".

What does set -e mean in a bash script?

I found this post while trying to figure out what the exit status was for a script that was aborted due to a set -e. The answer didn't appear obvious to me; hence this answer. Basically, set -e aborts the execution of a command (e.g. a shell script) and returns the exit status code of the command that failed (i.e. the inner script, not the outer script).

For example, suppose I have the shell script outer-test.sh:

#!/bin/sh
set -e
./inner-test.sh
exit 62;

The code for inner-test.sh is:

#!/bin/sh
exit 26;

When I run outer-script.sh from the command line, my outer script terminates with the exit code of the inner script:

$ ./outer-test.sh
$ echo $?
26

Shell Script Syntax Error: Unexpected End of File

It can also be caused by piping out of a pair of curly braces on a line.

This fails:

{ /usr/local/bin/mycommand ; outputstatus=$? } >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more

while this is allowed:

{
   /usr/local/bin/mycommand
   outputstatus=$?
} >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more

How to echo shell commands as they are executed

shuckc's answer for echoing select lines has a few downsides: you end up with the following set +x command being echoed as well, and you lose the ability to test the exit code with $? since it gets overwritten by the set +x.

Another option is to run the command in a subshell:

echo "getting URL..."
( set -x ; curl -s --fail $URL -o $OUTFILE )

if [ $? -eq 0 ] ; then
    echo "curl failed"
    exit 1
fi

which will give you output like:

getting URL...
+ curl -s --fail http://example.com/missing -o /tmp/example
curl failed

This does incur the overhead of creating a new subshell for the command, though.

How to cat <<EOF >> a file containing code?

This should work, I just tested it out and it worked as expected: no expansion, substitution, or what-have-you took place.

cat <<< '
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
  curr=$((curr+406));
  echo $curr  > /sys/class/backlight/intel_backlight/brightness;
fi' > file # use overwrite mode so that you don't keep on appending the same script to that file over and over again, unless that's what you want. 

Using the following also works.

cat <<< ' > file
 ... code ...'

Also, it's worth noting that when using heredocs, such as << EOF, substitution and variable expansion and the like takes place. So doing something like this:

cat << EOF > file
cd "$HOME"
echo "$PWD" # echo the current path
EOF

will always result in the expansion of the variables $HOME and $PWD. So if your home directory is /home/foobar and the current path is /home/foobar/bin, file will look like this:

cd "/home/foobar"
echo "/home/foobar/bin"

instead of the expected:

cd "$HOME"
echo "$PWD"

Remove redundant paths from $PATH variable

  1. Just echo $PATH
  2. copy details into a text editor
  3. remove unwanted entries
  4. PATH= # pass new list of entries

Printing PDFs from Windows Command Line

First response - wanted to finally give back to a helpful community...

Wanted to add this to the responses for people still looking for simple a solution. I'm using a free product by Foxit Software - FoxItReader.
Here is the link to the version that works with the silent print - newer versions the silent print feature is still not working. FoxitReader623.815_Setup

FOR %%f IN (*.pdf) DO ("C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe" /t %%f "SPST-SMPICK" %%f & del %%f) 

I simply created a command to loop through the directory and for each pdf file (FOR %%f IN *.pdf) open the reader silently (/t) get the next PDF (%%f) and send it to the print queue (SPST-SMPICK), then delete each PDF after I send it to the print queue (del%%f). Shashank showed an example of moving the files to another directory if that what you need to do

FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)

How to extract the first two characters of a string in shell scripting?

You can use printf:

$ original='USCAGoleta9311734.5021-120.1287855805'
$ printf '%-.2s' "$original"
US

source command not found in sh shell

Bourne shell (sh) uses PATH to locate in source <file>. If the file you are trying to source is not in your path, you get the error 'file not found'.

Try:

source ./<filename>

How to use curl in a shell script?

Firstly, your example is looking quite correct and works well on my machine. You may go another way.

curl $CURLARGS $RVMHTTP > ./install.sh

All output now storing in ./install.sh file, which you can edit and execute.

A variable modified inside a while loop is not remembered

Hmmm... I would almost swear that this worked for the original Bourne shell, but don't have access to a running copy just now to check.

There is, however, a very trivial workaround to the problem.

Change the first line of the script from:

#!/bin/bash

to

#!/bin/ksh

Et voila! A read at the end of a pipeline works just fine, assuming you have the Korn shell installed.

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

How can I get the behavior of GNU's readlink -f on a Mac?

  1. Install homebrew
  2. Run "brew install coreutils"
  3. Run "greadlink -f path"

greadlink is the gnu readlink that implements -f. You can use macports or others as well, I prefer homebrew.

How to get a password from a shell script without echoing

The -s option of read is not defined in the POSIX standard. See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. I wanted something that would work for any POSIX shell, so I wrote a little function that uses stty to disable echo.

#!/bin/sh

# Read secret string
read_secret()
{
    # Disable echo.
    stty -echo

    # Set up trap to ensure echo is enabled before exiting if the script
    # is terminated while echo is disabled.
    trap 'stty echo' EXIT

    # Read secret.
    read "$@"

    # Enable echo.
    stty echo
    trap - EXIT

    # Print a newline because the newline entered by the user after
    # entering the passcode is not echoed. This ensures that the
    # next line of output begins at a new line.
    echo
}

This function behaves quite similar to the read command. Here is a simple usage of read followed by similar usage of read_secret. The input to read_secret appears empty because it was not echoed to the terminal.

[susam@cube ~]$ read a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c

Here is another that uses the -r option to preserve the backslashes in the input. This works because the read_secret function defined above passes all arguments it receives to the read command.

[susam@cube ~]$ read -r a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret -r a b c

[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c

Finally, here is an example that shows how to use the read_secret function to read a password in a POSIX compliant manner.

printf "Password: "
read_secret password
# Do something with $password here ...

Get specific line from text file using just shell script

sed:

sed '5!d' file

awk:

awk 'NR==5' file

How to execute mongo commands through shell scripts?

There is an official documentation page about this as well.

Examples from that page include:

mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

How do I limit the number of results returned from grep?

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

How can I have a newline in a string in sh?

I'm no bash expert, but this one worked for me:

STR1="Hello"
STR2="World"
NEWSTR=$(cat << EOF
$STR1

$STR2
EOF
)
echo "$NEWSTR"

I found this easier to formatting the texts.

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.

Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.

As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.

What is the most "pythonic" way to iterate over a list in chunks?

The more-itertools package has chunked method which does exactly that:

import more_itertools
for s in more_itertools.chunked(range(9), 4):
    print(s)

Prints

[0, 1, 2, 3]
[4, 5, 6, 7]
[8]

chunked returns the items in a list. If you'd prefer iterables, use ichunked.

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

How to use filesaver.js

Here is a guide to JSZIP to create ZIP files by JavaScript. To download files you need to have filesaver.js, You can include those libraries by:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js"  type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>

Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.

<script type="text/javascript">
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");
    zip.generateAsync({type:"blob"})
    .then(function(content) {
        // see FileSaver.js
        saveAs(content, "file.zip");
    });
</script>

Now let's get in to deeper. Create an instance of JSZip.

var zip = new JSZip();

Add a file with a Hello World text:

zip.file("hello.txt", "Hello World\n");

Download the filie with name archive.zip

zip.generateAsync({type:"blob"}).then(function(zip) {
    saveAs(zip, "archive.zip");
});

Read More from here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library

Convert this string to datetime

The Problem is with your code formatting,

inorder to use strtotime() You should replace '06/Oct/2011:19:00:02' with 06/10/2011 19:00:02 and date('d/M/Y:H:i:s', $date); with date('d/M/Y H:i:s', $date);. Note the spaces in between.

So the final code looks like this

$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);

How to get featured image of a product in woocommerce

I got the solution . I tried this .

<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' );?>

    <img src="<?php  echo $image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">

What does enumerate() mean?

I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
    letter = list_of_letters[i]
    print (i, letter)

The output is:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0
for n in list_of_letters:
    print (i, n)
    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
    print (i, letter)

SQL query to find third highest salary in company

SELECT DISTINCT MAX(salary) AS max
FROM STAFF
WHERE salary IN
(SELECT salary 
 FROM STAFF
 WHERE salary<(SELECT MAX(salary) AS maxima 
 FROM STAFF
 WHERE salary<
 (SELECT MAX(salary) AS maxima
  FROM STAFF))
GROUP BY salary);

I have tried other ways they are not right. This one works.

Stash only one file out of multiple files that have changed with Git?

Since Git 2.13 (Q2 2017), you can stash individual files, with git stash push:

git stash push [-m <message>] [--] [<pathspec>...]

When pathspec is given to 'git stash push', the new stash records the modified states only for the files that match the pathspec See "Stash changes to specific files" for more.

Simplified example:

 git stash push path/to/file

The test case for this feature shows a few more options off:

test_expect_success 'stash with multiple pathspec arguments' '
    >foo &&
    >bar &&
    >extra &&
    git add foo bar extra &&

    git stash push -- foo bar &&   

    test_path_is_missing bar &&
    test_path_is_missing foo &&
    test_path_is_file extra &&

    git stash pop &&
    test_path_is_file foo &&
    test_path_is_file bar &&
    test_path_is_file extra

The original answer (below, June 2010) was about manually selecting what you want to stash.

Casebash comments:

This (the stash --patch original solution) is nice, but often I've modified a lot of files so using patch is annoying

bukzor's answer (upvoted, November 2011) suggests a more practical solution, based on
git add + git stash --keep-index.
Go see and upvote his answer, which should be the official one (instead of mine).

About that option, chhh points out an alternative workflow in the comments:

you should "git reset --soft" after such a stash to get your clear staging back:
In order to get to the original state - which is a clear staging area and with only some select un-staged modifications, one could softly reset the index to get (without committing anything like you - bukzor - did).


(Original answer June 2010: manual stash)

Yet, git stash save --patch could allows you to achieve the partial stashing you are after:

With --patch, you can interactively select hunks from in the diff between HEAD and the working tree to be stashed.
The stash entry is constructed such that its index state is the same as the index state of your repository, and its worktree contains only the changes you selected interactively. The selected changes are then rolled back from your worktree.

However that will save the full index (which may not be what you want since it might include other files already indexed), and a partial worktree (which could look like the one you want to stash).

git stash --patch --no-keep-index

might be a better fit.


If --patch doesn't work, a manual process might:

For one or several files, an intermediate solution would be to:

  • copy them outside the Git repo
    (Actually, eleotlecram proposes an interesting alternative)
  • git stash
  • copy them back
  • git stash # this time, only the files you want are stashed
  • git stash pop stash@{1} # re-apply all your files modifications
  • git checkout -- afile # reset the file to the HEAD content, before any local modifications

At the end of that rather cumbersome process, you will have only one or several files stashed.

What does numpy.random.seed(0) do?

numpy.random.seed(0)
numpy.random.randint(10, size=5)

This produces the following output: array([5, 0, 3, 3, 7]) Again,if we run the same code we will get the same result.

Now if we change the seed value 0 to 1 or others:

numpy.random.seed(1)
numpy.random.randint(10, size=5)

This produces the following output: array([5 8 9 5 0]) but now the output not the same like above.

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

How to add label in chart.js for pie chart

For those using newer versions Chart.js, you can set a label by setting the callback for tooltips.callbacks.label in options.

Example of this would be:

var chartOptions = {
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                return 'label';
            }
        }
    }
}

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

Multiple try codes in one block

Extract (refactor) your statements. And use the magic of and and or to decide when to short-circuit.

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

Getting the ID of the element that fired an event

This works on a higher z-index than the event parameter mentioned in above answers:

$("#mydiv li").click(function(){

    ClickedElement = this.id;
    alert(ClickedElement);
});

This way you will always get the id of the (in this example li) element. Also when clicked on a child element of the parent..

Cache busting via params

<script type="text/javascript">
// front end cache bust

var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];   
for (i=0; i < cacheBust.length; i++){
     var el = document.createElement('script');
     el.src = cacheBust[i]+"?v=" + Math.random();
     document.getElementsByTagName('head')[0].appendChild(el);
}
</script> 

What's the difference between SHA and AES encryption?

SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.

You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.

AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.

UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.

In AngularJS, what's the difference between ng-pristine and ng-dirty?

pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>_x000D_
<form ng-app="" name="myForm">_x000D_
  <input name="email" ng-model="data.email">_x000D_
  <div class="info" ng-show="myForm.email.$pristine">_x000D_
    Email is virgine._x000D_
  </div>_x000D_
  <div class="error" ng-show="myForm.email.$dirty">_x000D_
    E-mail is dirty_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.

How do I find out which keystore was used to sign an app?

First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).

Then issue this command:

keytool -printcert -file ANDROID_.RSA

You will get certificate fingerprints like this:

     MD5:  B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
     SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
     Signature algorithm name: SHA1withRSA

Then use the keytool again to print out all the aliases of your signing keystore:

keytool -list -keystore my-signing-key.keystore

You will get a list of aliases and their certificate fingerprint:

android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB

Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.

Keytool is part of Java, so make sure your PATH has Java installation dir in it.

`col-xs-*` not working in Bootstrap 4

you could do this, if you want to use the old syntax (or don't want to rewrite every template)

@for $i from 1 through $grid-columns {
  @include media-breakpoint-up(xs) {
    .col-xs-#{$i} {
      @include make-col-ready();
      @include make-col($i);
    }
  }
}

Using Docker-Compose, how to execute multiple commands

Another idea:

If, as in this case, you build the container just place a startup script in it and run this with command. Or mount the startup script as volume.

The difference between "require(x)" and "import x"

Let me give an example for Including express module with require & import

-require

var express = require('express');

-import

import * as  express from 'express';

So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,

var app = express(); 

So we use 'require' with 'CommonJS' and 'import' with 'ES6'.

For more info on 'require' & 'import', read through below links.

require - Requiring modules in Node.js: Everything you need to know

import - An Update on ES6 Modules in Node.js

Change the row color in DataGridView based on the quantity of a cell value

I fixed my error. just removed "Value" from this line:

If drv.Item("Quantity").Value < 5  Then

So it will look like

If drv.Item("Quantity") < 5 Then

npm install errors with Error: ENOENT, chmod

I encountered similar behavior after upgrading to npm 6.1.0. It seemed to work once, but then I got into a state with this error while trying to install a package that was specified by path on the filesystem:

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename

The following things did not fix the problem:

  • rm -rf node_modules
  • npm cache clean (gave npm ERR! As of npm@5, the npm cache self-heals....use 'npm cache verify' instead.)
  • npm cache verify
  • rm -rf ~/.npm

How I fixed the problem:

  • rm package-lock.json

Angularjs on page load call function

<section ng-controller="testController as ctrl" class="test_cls"  data-ng-init="fn_load()">

$scope.fn_load = function () {
  console.log("page load")
};

surface plots in matplotlib

It is not possible to directly make a 3d surface using your data. I would recommend you to build an interpolation model using some tools like pykridge. The process will include three steps:

  1. Train an interpolation model using pykridge
  2. Build a grid from X and Y using meshgrid
  3. Interpolate values for Z

Having created your grid and the corresponding Z values, now you're ready to go with plot_surface. Note that depending on the size of your data, the meshgrid function can run for a while. The workaround is to create evenly spaced samples using np.linspace for X and Y axes, then apply interpolation to infer the necessary Z values. If so, the interpolated values might different from the original Z because X and Y have changed.

linq where list contains any in list

Or like this

class Movie
{
  public string FilmName { get; set; }
  public string Genre { get; set; }
}

...

var listofGenres = new List<string> { "action", "comedy" };

var Movies = new List<Movie> {new Movie {Genre="action", FilmName="Film1"},
                new Movie {Genre="comedy", FilmName="Film2"},
                new Movie {Genre="comedy", FilmName="Film3"},
                new Movie {Genre="tragedy", FilmName="Film4"}};

var movies = Movies.Join(listofGenres, x => x.Genre, y => y, (x, y) => x).ToList();

How do I return multiple values from a function?

In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.

However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

What are all the different ways to create an object in Java?

there is also ClassLoader.loadClass(string) but this is not often used.

and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

In PHP, how can I add an object element to an array?

Something like:

class TestClass {
private $var1;
private $var2;

private function TestClass($var1, $var2){
    $this->var1 = $var1;
    $this->var2 = $var2;
}

public static function create($var1, $var2){
    if (is_numeric($var1)){
        return new TestClass($var1, $var2);
    }
    else return NULL;
}
}

$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");

print_r($myArray);

$myArray = array_filter($myArray, function($e){ return !is_null($e);});

print_r($myArray);

I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.

Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Is there any way to set environment variables in Visual Studio Code?

As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "ddtBatch",
      "request": "launch",
      "mainClass": "com.something.MyApplication",
      "projectName": "MyProject",
      "args": "Hello",
      "vmArgs": "-Dspring.config.location=./application.properties"
    }
  ]
}

Using TortoiseSVN via the command line

In case you have already installed the TortoiseSVN GUI and wondering how to upgrade to command line tools, here are the steps...

  1. Go to Windows Control Panel ? Program and Features (Windows 7+)
  2. Locate TortoiseSVN and click on it.
  3. Select "Change" from the options available.
  4. Refer to this image for further steps.

    TortoiseSVN Command Line Enable

  5. After completion of the command line client tools, open a command prompt and type svn help to check the successful install.

C# refresh DataGridView when updating or inserted on another form

DataGridView.Refresh and And DataGridView.Update are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.

My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.

A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

How to get the user input in Java?

Keyboard entry using Scanner is possible, as others have posted. But in these highly graphic times it is pointless making a calculator without a graphical user interface (GUI).

In modern Java this means using a JavaFX drag-and-drop tool like Scene Builder to lay out a GUI that resembles a calculator's console. Note that using Scene Builder is intuitively easy and demands no additional Java skill for its event handlers that what you already may have.

For user input, you should have a wide TextField at the top of the GUI console.

This is where the user enters the numbers that they want to perform functions on. Below the TextField, you would have an array of function buttons doing basic (i.e. add/subtract/multiply/divide and memory/recall/clear) functions. Once the GUI is lain out, you can then add the 'controller' references that link each button function to its Java implementation, e.g a call to method in your project's controller class.

This video is a bit old but still shows how easy Scene Builder is to use.

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I have also got stuck into this and believe me disabling SELinux is not a good idea.

Please just use below and you are good,

sudo restorecon -R /var/www/mysite

Enjoy..

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Vertically center text in a 100% height div?

have you tried line-height:1em;? I recall that that's the way to get it to center vertically.

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

Swift - How to convert String to Double

I find more readable to add an extension to String as follow:

extension String {
    var doubleValue: Double {
        return (self as NSString).doubleValue
    }
}

and then you just could write your code:

myDouble = myString.doubleValue

How do you put an image file in a json object?

The JSON format can contain only those types of value:

  • string
  • number
  • object
  • array
  • true
  • false
  • null

An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string.

The most common way to achieve that is with what's called base64. Basically, instead of encoding it as 1 and 0s, it uses a range of 64 characters which makes the textual representation of it more compact. So for example the number '64' in binary is represented as 1000000, while in base64 it's simply one character: =.

There are many ways to encode your image in base64 depending on if you want to do it in the browser or not.

Note that if you're developing a web application, it will be way more efficient to store images separately in binary form, and store paths to those images in your JSON or elsewhere. That also allows your client's browser to cache the images.

SQL Server - INNER JOIN WITH DISTINCT

It's not the same doing a select distinct at the beginning because you are wasting all the calculated rows from the result.

select a.FirstName, a.LastName, v.District
from AddTbl a order by Firstname
natural join (select distinct LastName from
            ValTbl v  where a.LastName = v.LastName)

try that.

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

PadLeft function in T-SQL

Something fairly ODBC compliant if needed might be the following:

select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
        + cast (FIELD as varchar(10))
  from TABLE_NAME

This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.

Cast received object to a List<object> or IEnumerable<object>

Have to join the fun...

    private void TestBench()
    {
        // An object to test
        string[] stringEnumerable = new string[] { "Easy", "as", "Pi" };

        ObjectListFromUnknown(stringEnumerable);
    }

    private void ObjectListFromUnknown(object o)
    {
        if (typeof(IEnumerable<object>).IsAssignableFrom(o.GetType()))
        {
            List<object> listO = ((IEnumerable<object>)o).ToList();
            // Test it
            foreach (var v in listO)
            {
                Console.WriteLine(v);
            }
        }
    }

When to use @QueryParam vs @PathParam

You can support both query parameters and path parameters, e.g., in the case of aggregation of resources -- when the collection of sub-resources makes sense on its own.

/departments/{id}/employees
/employees?dept=id

Query parameters can support hierarchical and non-hierarchical subsetting; path parameters are hierarchical only.

Resources can exhibit multiple hierarchies. Support short paths if you will be querying broad sub-collections that cross hierarchical boundaries.

/inventory?make=toyota&model=corolla
/inventory?year=2014

Use query parameters to combine orthogonal hierarchies.

/inventory/makes/toyota/models/corolla?year=2014
/inventory/years/2014?make=toyota&model=corolla
/inventory?make=toyota&model=corolla&year=2014

Use only path parameters in the case of composition -- when a resource doesn't make sense divorced from its parent, and the global collection of all children is not a useful resource in itself.

/words/{id}/definitions
/definitions?word=id   // not useful

Nginx - Customizing 404 page

You use the error_page property in the nginx config.

For example, if you intend to set the 404 error page to /404.html, use

error_page 404 /404.html;

Setting the 500 error page to /500.html is just as easy as:

error_page 500 /500.html;

annotation to make a private method public only for test classes

dp4j has what you need. Essentially all you have to do is add dp4j to your classpath and whenever a method annotated with @Test (JUnit's annotation) calls a method that's private it will work (dp4j will inject the required reflection at compile-time). You may also use dp4j's @TestPrivates annotation to be more explicit.

If you insist on also annotating your private methods you may use Google's @VisibleForTesting annotation.

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I found the answer to this problem here

Just do

mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');

Trim a string in C

There is no standard library function to do this, but it's not too hard to roll your own. There is an existing question on SO about doing this that was answered with source code.

How to check if Receiver is registered in Android?

Personally I use the method of calling unregisterReceiver and swallowing the exception if it's thrown. I agree this is ugly but the best method currently provided.

I've raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added: https://code.google.com/p/android/issues/detail?id=73718

Java socket API: How to tell if a connection has been closed?

As @user207421 say there is no way to know the current state of the connection because of the TCP/IP Protocol Architecture Model. So the server has to notice you before closing the connection or you check it by yourself.
This is a simple example that shows how to know the socket is closed by the server:

sockAdr = new InetSocketAddress(SERVER_HOSTNAME, SERVER_PORT);
socket = new Socket();
timeout = 5000;
socket.connect(sockAdr, timeout);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream());
while ((data = reader.readLine())!=null) 
      log.e(TAG, "received -> " + data);
log.e(TAG, "Socket closed !");

change cursor to finger pointer

Add an href attribute to make it a valid link & return false; in the event handler to prevent it from causing a navigation;

<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>

(Or make displayData() return false and ..="return displayData(..)

Match everything except for specified strings

Depends on the language, but there are generally negative-assertions you can put in like so:

(?!red|green|blue)

(Thanks for the syntax fix, the above is valid Java and Perl, YMMV)

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

How to replace plain URLs with links?

Reg Ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig

function UriphiMe(text) {
      var exp = /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig; 
      return text.replace(exp,"<a href='$1'>$1</a>");
}

Below are some tested string:

  1. Find me on to www.google.com
  2. www
  3. Find me on to www.http://www.com
  4. Follow me on : http://www.nishantwork.wordpress.com
  5. http://www.nishantwork.wordpress.com
  6. Follow me on : http://www.nishantwork.wordpress.com
  7. https://stackoverflow.com/users/430803/nishant

Note: If you don't want to pass www as valid one just use below reg ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig

How to grant permission to users for a directory using command line in Windows?

You can also use ICACLS.

To grant the Users group Full Control to a folder:

>icacls "C:\MyFolder" /grant Users:F

To grant Modify permission to IIS users for C:\MyFolder (if you need your IIS has ability to R/W files into specific folder):

>icacls "C:\MyFolder" /grant IIS_IUSRS:M

If you do ICACLS /? you will be able to see all available options.

Import CSV to mysql table

I wrote some code to do this, i'll put in a few snippets:

$dir = getcwd(); // Get current working directory where this .php script lives
$fileList = scandir($dir); // scan the directory where this .php lives and make array of file names

Then get the CSV headers so you can tell mysql how to import (note: make sure your mysql columns exactly match the csv columns):

//extract headers from .csv for use in import command
$headers = str_replace("\"", "`", array_shift(file($path)));
$headers = str_replace("\n", "", $headers);

Then send your query to the mysql server:

mysqli_query($cons, '
        LOAD DATA LOCAL INFILE "'.$path.'"
            INTO TABLE '.$dbTable.'  
            FIELDS TERMINATED by \',\' ENCLOSED BY \'"\'
            LINES TERMINATED BY \'\n\'
            IGNORE 1 LINES
            ('.$headers.')
            ;
        ')or die(mysql_error());

Delete topic in Kafka 0.8.1.1

First, you run this command to delete your topic:

$ bin/kafka-topics.sh --delete --bootstrap-server localhost:9092 --topic <topic_name>

List active topics to check delete completely:

$ bin/kafka-topics.sh --list --bootstrap-server localhost:9092

TortoiseGit save user authentication / credentials

If you are a windows 10 + TortoiseGit 2.7 user:

  1. for the first time login, simply follow the prompts to enter your credentials and save password.
  2. If you ever need to update your credentials, don't waste your time at the TortoiseGit settings. Instead, windows search>Credential Manager> Windows Credentials > find your git entry > Edit.

Redirect website after certain amount of time

If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.

Here is a very basic approach using setTimeout()

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
    <p>You will be redirected in 3 seconds</p>_x000D_
    <script>_x000D_
        var timer = setTimeout(function() {_x000D_
            window.location='http://example.com'_x000D_
        }, 3000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Passing parameters to addTarget:action:forControlEvents

Target-Action allows three different forms of action selector:

- (void)action
- (void)action:(id)sender
- (void)action:(id)sender forEvent:(UIEvent *)event

Floating point inaccuracy examples

Here is my simple understanding.

Problem: The value 0.45 cannot be accurately be represented by a float and is rounded up to 0.450000018. Why is that?

Answer: An int value of 45 is represented by the binary value 101101. In order to make the value 0.45 it would be accurate if it you could take 45 x 10^-2 (= 45 / 10^2.) But that’s impossible because you must use the base 2 instead of 10.

So the closest to 10^2 = 100 would be 128 = 2^7. The total number of bits you need is 9 : 6 for the value 45 (101101) + 3 bits for the value 7 (111). Then the value 45 x 2^-7 = 0.3515625. Now you have a serious inaccuracy problem. 0.3515625 is not nearly close to 0.45.

How do we improve this inaccuracy? Well we could change the value 45 and 7 to something else.

How about 460 x 2^-10 = 0.44921875. You are now using 9 bits for 460 and 4 bits for 10. Then it’s a bit closer but still not that close. However if your initial desired value was 0.44921875 then you would get an exact match with no approximation.

So the formula for your value would be X = A x 2^B. Where A and B are integer values positive or negative. Obviously the higher the numbers can be the higher would your accuracy become however as you know the number of bits to represent the values A and B are limited. For float you have a total number of 32. Double has 64 and Decimal has 128.

LaTeX package for syntax highlighting of code in various languages

You can use the listings package. It supports many different languages and there are lots of options for customising the output.

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

Finding element's position relative to the document

You can get top and left without traversing DOM like this:

function getCoords(elem) { // crossbrowser version
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

    var clientTop = docEl.clientTop || body.clientTop || 0;
    var clientLeft = docEl.clientLeft || body.clientLeft || 0;

    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
}

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

Get Cell Value from a DataTable in C#

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

Changing capitalization of filenames in Git

This Python snippet will git mv --force all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force.

Modify it to your liking. I just figured I'd share :)

import os
import re

searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)

for root, dirs, files in os.walk(searchDir):
    dirs[:] = [d for d in dirs if d not in exclude]
    for f in files:
        if re.match(r'[A-Z]', f):
            fullPath = os.path.join(root, f)
            fullPathLower = os.path.join(root, f[0].lower() + f[1:])
            command = 'git mv --force ' + fullPath + ' ' + fullPathLower
            print(command)
            os.system(command)

Convert RGB to Black & White in OpenCV

AFAIK, you have to convert it to grayscale and then threshold it to binary.

1. Read the image as a grayscale image If you're reading the RGB image from disk, then you can directly read it as a grayscale image, like this:

// C
IplImage* im_gray = cvLoadImage("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

// C++ (OpenCV 2.0)
Mat im_gray = imread("image.jpg",CV_LOAD_IMAGE_GRAYSCALE);

2. Convert an RGB image im_rgb into a grayscale image: Otherwise, you'll have to convert the previously obtained RGB image into a grayscale image

// C
IplImage *im_rgb  = cvLoadImage("image.jpg");
IplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);
cvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);

// C++
Mat im_rgb  = imread("image.jpg");
Mat im_gray;
cvtColor(im_rgb,im_gray,CV_RGB2GRAY);

3. Convert to binary You can use adaptive thresholding or fixed-level thresholding to convert your grayscale image to a binary image.

E.g. in C you can do the following (you can also do the same in C++ with Mat and the corresponding functions):

// C
IplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);
cvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

// C++
Mat img_bw = im_gray > 128;

In the above example, 128 is the threshold.

4. Save to disk

// C
cvSaveImage("image_bw.jpg",img_bw);

// C++
imwrite("image_bw.jpg", img_bw);

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

This answer simply applies the type=date attribute to the HTML input element and relies on the browser to supply a date picker. Note that even in 2017, not all browsers provide their own date picker, so you may want to provide a fall back.

All you have to do is add attributes to the property in the view model. Example for variable Ldate:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
Public DateTime Ldate {get;set;}

Assuming you're using MVC 5 and Visual Studio 2013.

link button property to open in new tab?

When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.

try

lbnkVidTtile1.Enabled = true;

I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.

Redirecting to a certain route based on condition

Here's how I did it, in case it helps anyone:

In the config, I set a publicAccess attribute on the few routes that I want open to the public (like login or register):

$routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
    })
    .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        publicAccess: true
    })

then in a run block, I set a listener on the $routeChangeStart event that redirects to '/login' unless the user has access or the route is publicly accessible:

angular.module('myModule').run(function($rootScope, $location, user, $route) {

    var routesOpenToPublic = [];
    angular.forEach($route.routes, function(route, path) {
        // push route onto routesOpenToPublic if it has a truthy publicAccess value
        route.publicAccess && (routesOpenToPublic.push(path));
    });

    $rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
        var closedToPublic = (-1 === routesOpenToPublic.indexOf($location.path()));
        if(closedToPublic && !user.isLoggedIn()) {
            $location.path('/login');
        }
    });
})

You could obviously change the condition from isLoggedIn to anything else... just showing another way to do it.

What is the difference between field, variable, attribute, and property in Java POJOs?

Variables are comprised of fields and non-fields.

Fields can be either:

  1. Static fields or
  2. non-static fields also called instantiations e.g. x = F()

Non-fields can be either:

  1. local variables, the analog of fields but inside a methods rather than outside all of them, or
  2. parameters e.g. y in x = f(y)

In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.

Basic Example (excuse me for my syntax, I am just a beginner)

Class {    
    //fields    

    method1 {              
         //non-fields    

    }    
}

Update Fragment from ViewPager

Accepted answer is not understand, That's why added easy solution. after long struggle find Working solution.

Just notify to your adapter, it's working amazing,

Reference code

 void setAdapter(int position) {
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        // when notify then set manually current position.
        viewPager.setCurrentItem(position);
        pagerAdapter.notifyDataSetChanged();
    }

call this code when you set adapter and when you want to refresh UI.

In Your fragment add this code for refresh

((YourActivityName) getContext()).setAdapter(selectedTabPosition);

Use instanceof for cast context.

This code share only helping purpose who find solution.

Can I get Unix's pthread.h to compile in Windows?

Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.

It comprises of the pthread.h header, libwinpthread.a, libwinpthread.dll.a static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll and libwinpthread_64-1.dll(this, as of 01-06-2016).

You'll need to link to the libwinpthread.a library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.

Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.

The above two seem to be the most well known ways for this.

Hope this helps.

Replace all particular values in a data frame

We can use data.table to get it quickly. First create df without factors,

df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)), stringsAsFactors=F)

Now you can use

setDT(df)
for (jj in 1:ncol(df)) set(df, i = which(df[[jj]]==""), j = jj, v = NA)

and you can convert it back to a data.frame

setDF(df)

If you only want to use data.frame and keep factors it's more difficult, you need to work with

levels(df$value)[levels(df$value)==""] <- NA

where value is the name of every column. You need to insert it in a loop.

Delete many rows from a table using id in Mysql

Something like this might make it a bit easier, you could obviously use a script to generate this, or even excel

DELETE FROM tablename WHERE id IN (
1,
2,
3,
4,
5,
6
);

Generate a UUID on iOS from Swift

Also you can use it lowercase under below

let uuid = NSUUID().UUIDString.lowercaseString
print(uuid)

Output

68b696d7-320b-4402-a412-d9cee10fc6a3

Thank you !

Thread Safe C# Singleton Pattern

You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance()
    {
        return instance;
    }
}

How to do the Recursive SELECT query in MySQL?

Building off of Master DJon

Here is simplified function which provides the added utility of returning depth (in case you want to use logic to include the parent task or search at a specific depth)

DELIMITER $$
FUNCTION `childDepth`(pParentId INT, pId INT) RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
BEGIN
DECLARE depth,curId int;
SET depth = 0;
SET curId = pId;

WHILE curId IS not null AND curId <> pParentId DO
    SELECT ParentId from test where id=curId limit 1 into curId;
    SET depth = depth + 1;
END WHILE;

IF curId IS NULL THEN
    set depth = -1;
END IF;

RETURN depth;
END$$

Usage:

select * from test where childDepth(1, id) <> -1;

How can I merge two MySQL tables?

It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

HTTP Basic: Access denied fatal: Authentication failed

I use VS Code on my mac OS and GitLab for my project. I tried so many ways but it worked simply for me by resetting the remote origin of your project repository with the below command:

cd <local-project-repo-on-machine>
git remote set-url <remote-name> <remote-url>

for ex: git remote set-url origin https://<project-repository>.git

Hope it helps someone.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

What is the difference between BIT and TINYINT in MySQL?

BIT should only allow 0 and 1 (and NULL, if the field is not defined as NOT NULL). TINYINT(1) allows any value that can be stored in a single byte, -128..127 or 0..255 depending on whether or not it's unsigned (the 1 shows that you intend to only use a single digit, but it does not prevent you from storing a larger value).

For versions older than 5.0.3, BIT is interpreted as TINYINT(1), so there's no difference there.

BIT has a "this is a boolean" semantic, and some apps will consider TINYINT(1) the same way (due to the way MySQL used to treat it), so apps may format the column as a check box if they check the type and decide upon a format based on that.

SimpleDateFormat parsing date with 'Z' literal

Since java 8 just use ZonedDateTime.parse("2010-04-05T17:16:00Z")

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

SQLMenace said money is inexact. But you don't multiply/divide money by money! How much is 3 dollars times 50 cents? 150 dollarcents? You multiply/divide money by scalars, which should be decimal.

DECLARE
@mon1 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@num2*@num3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS moneyresult,
@num4 AS numericresult

Results in the correct result:

moneyresult           numericresult
--------------------- ---------------------------------------
2949.8525             2949.8525

money is good as long as you don't need more than 4 decimal digits, and you make sure your scalars - which do not represent money - are decimals.

redistributable offline .NET Framework 3.5 installer for Windows 8

Try this command:

Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess

I: partition of your Windows DVD.

How do I include a file over 2 directories back?

Try ../../. You can modify it accordingly as it will take you up back two directories. First reach to root directory then access the required directory.

E.g. You are in root/inc/usr/ap and there is another directory root/2nd/path. You can access the path directory from ap like this: ../../2nd/path first go to root than desired directory. If not working please share.

Fixing Segmentation faults in C++

Sometimes the crash itself isn't the real cause of the problem-- perhaps the memory got smashed at an earlier point but it took a while for the corruption to show itself. Check out valgrind, which has lots of checks for pointer problems (including array bounds checking). It'll tell you where the problem starts, not just the line where the crash occurs.

How to add display:inline-block in a jQuery show() function?

Setting the CSS property after you have used .show() should work. Maybe you are targeting the wrong element on your HTML page.

 $('#foo').css('display', 'inline-block');

But if you are not using any effects of .show(), .hide() why don't you set those CSS properties manually like:

$('#foo').css('display','none'); 
$('#foo').css('display','inline-block');

Accessing variables from other functions without using global variables

You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).

Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):

How to get a variable returned across multiple functions - Javascript/jQuery

How do I handle ImeOptions' done button click?

Try this, it should work for what you need:


editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
       //do here your stuff f
       return true;
    }
    return false;
    } 
});

Android: how to refresh ListView contents?

Only this works for me everytime, note that I don't know if it causes any other complications or performance issues:

private void updateListView(){
        listview.setAdapter(adapter);
    }

How to import a CSS file in a React Component

I would suggest using CSS Modules:

React

import React from 'react';
import styles from './table.css';

export default class Table extends React.Component {
    render () {
        return <div className={styles.table}>
            <div className={styles.row}>
                <div className={styles.cell}>A0</div>
                <div className={styles.cell}>B0</div>
            </div>
        </div>;
    }
}

Rendering the Component:

<div class="table__table___32osj">
    <div class="table__row___2w27N">
        <div class="table__cell___2w27N">A0</div>
        <div class="table__cell___1oVw5">B0</div>
    </div>
</div>

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I had this problem when TortoiseGIT was installed on my machine. After changing the environment variable GIT_SSH from

"c:\Program Files\TortoiseGit\bin\TortoisePlink.exe"

to

"c:\Program Files (x86)\Git\bin\ssh.exe"

and following this tutorial with ssh-keygen and keys:add, it works!

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

For rep reasons, I can't add this as a comment (where it would better go with bennedich's answer), but for Windows command line, here is the correct syntax:

curl -u YOUR_USERNAME https://api.github.com/user/repos -d "{\"name\":\"YOUR_REPO_NAME\"}"

It's the same basic form, but you have to use double quotes (") instead of single, and escape the double quotes sent in the POST parameters (after the -d flag) with backslashes. I also removed the single quotes around my username, but if your username had a space (possible?) it would probably need double quotes.

Combine two or more columns in a dataframe into a new column with a new name

Some examples with NAs and their removal using apply

n = c(2, NA, NA) 
s = c("aa", "bb", NA) 
b = c(TRUE, FALSE, NA) 
c = c(2, 3, 5) 
d = c("aa", NA, "cc") 
e = c(TRUE, NA, TRUE) 
df = data.frame(n, s, b, c, d, e)

paste_noNA <- function(x,sep=", ") {
gsub(", " ,sep, toString(x[!is.na(x) & x!="" & x!="NA"] ) ) }

sep=" "
df$x <- apply( df[ , c(1:6) ] , 1 , paste_noNA , sep=sep)
df

How to submit an HTML form on loading the page?

You can do it by using simple one line JavaScript code and also be careful that if JavaScript is turned off it will not work. The below code will do it's job if JavaScript is turned off.

Turn off JavaScript and run the code on you own file to know it's full function.(If you turn off JavaScript here, the below Code Snippet will not work)

_x000D_
_x000D_
.noscript-error {_x000D_
  color: red;_x000D_
}
_x000D_
<body onload="document.getElementById('payment-form').submit();">_x000D_
_x000D_
  <div align="center">_x000D_
    <h1>_x000D_
      Please Waite... You Will be Redirected Shortly<br/>_x000D_
      Don't Refresh or Press Back _x000D_
    </h1>_x000D_
  </div>_x000D_
_x000D_
  <form method='post' action='acction.php' id='payment-form'>_x000D_
    <input type='hidden' name='field-name' value='field-value'>_x000D_
     <input type='hidden' name='field-name2' value='field-value2'>_x000D_
    <noscript>_x000D_
      <div align="center" class="noscript-error">Sorry, your browser does not support JavaScript!._x000D_
        <br>Kindly submit it manually_x000D_
        <input type='submit' value='Submit Now' />_x000D_
      </div>_x000D_
    </noscript>_x000D_
  </form>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Defining private module functions in python

There may be confusion between class privates and module privates.

A module private starts with one underscore
Such a element is not copied along when using the from <module_name> import * form of the import command; it is however imported if using the import <moudule_name> syntax (see Ben Wilhelm's answer)
Simply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the from a import * syntax.

A class private starts with two underscores (aka dunder i.e. d-ouble under-score)
Such a variable has its name "mangled" to include the classname etc.
It can still be accessed outside of the class logic, through the mangled name.
Although the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes. See Alex Martelli's funny but accurate reference to consenting adults as he describes the convention used in regards to these variables.

>>> class Foo(object):
...    __bar = 99
...    def PrintBar(self):
...        print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar  #direct attempt no go
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar()  # the class itself of course can access it
99
>>> dir(Foo)    # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar  #and get to it by its mangled name !  (but I shouldn't!!!)
99
>>>

how to access master page control from content page

If you are trying to access an html element: this is an HTML Anchor...

My nav bar has items that are not list items (<li>) but rather html anchors (<a>)

See below: (This is the site master)

<nav class="mdl-navigation">
    <a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
    <a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>

Now in your code behind for another page, for mine, it's the login page...

On PageLoad() define this:

HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;

HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;

Now we have accessed the site masters controls, and have made them invisible on the login page.

How to set up a Web API controller for multipart/form-data

check ur WebApiConfig and add this

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

How to properly export an ES6 class in Node 4?

// person.js
'use strict';

module.exports = class Person {
   constructor(firstName, lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }

   display() {
       console.log(this.firstName + " " + this.lastName);
   }
}

 

// index.js
'use strict';

var Person = require('./person.js');

var someone = new Person("First name", "Last name");
someone.display();

"Uncaught Error: [$injector:unpr]" with angular after deployment

This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html',
        controller: function ($scope) {
            $scope.selectThisOption = function () {
                // some code
            };
        }
    };
});

When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html'
        controller: ['$scope', function ($scope) { //<-- difference
            $scope.selectThisOption = function () {
                // some code
            };
        }]
    };
});

IntelliJ: Error:java: error: release version 5 not supported

You should do one more change by either below approaches:


1 Through IntelliJ GUI

As mentioned by 'tataelm':

Project Structure > Project Settings > Modules > Language level: > then change to your preferred language level


2 Edit IntelliJ config file directly

Open the <ProjectName>.iml file (it is created automatically in your project folder if you're using IntelliJ) directly by editing the following line,

From: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5">

To: <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_11">

As your approach is also meaning to edit this file. :)


Approach 1 is actually asking IntelliJ to help edit the .iml file instead of doing by you directly.

Illegal access: this web application instance has been stopped already

Restarting Your Server Can Resolve this problem.

I was getting the same error while Using Dynamic Jasper Reporting , When i deploy my Application for first use to Create Reports, the Report creation works fine, But Once I Do Hot Deployment of some code changes To the Server, I was getting This Error.

Declare an empty two-dimensional array in Javascript?

ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))       

_x000D_
_x000D_
let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
);
_x000D_
_x000D_
_x000D_

Two values from one input in python?

You can't really do it the C way (I think) but a pythonic way of doing this would be (if your 'inputs' have spaces in between them):

raw_answer = raw_input()
answers = raw_answer.split(' ') # list of 'answers'

So you could rewrite your try to:

var1, var2 = raw_input("enter two numbers:").split(' ')

Note that this it somewhat less flexible than using the 'first' solution (for example if you add a space at the end this will already break).

Also be aware that var1 and var2 will still be strings with this method when not cast to int.

How can I generate a random number in a certain range?

So you would want the following:

int random;
int max;
int min;

...somewhere in your code put the method to get the min and max from the user when they click submit and then use them in the following line of code:

random = Random.nextInt(max-min+1)+min;

This will set random to a random number between the user selected min and max. Then you will do:

TextView.setText(random.toString());

How to import/include a CSS file using PHP code and not HTML code?

You can also do the following:

  1. Create a php file in includes folder, name it bootstrap_css.php for example
  2. paste the css code files to file created above

     <?php 
      $minCss=' <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">';
    
     $business = '<link href="bootstrap/css/modern-business.css" rel="stylesheet">';
    
      echo $minCss;
      echo $business;
    ?>
    
  3. in the html header, include the css files as follows

     <?php include_once 'includes/bootstrap_css.php'; ?>
    

see if two files have the same content in python

I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.

There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can

  • Compare file sizes first, discarding all which doesn't match
  • If file sizes match, compare using the biggest hash you can handle, hashing chunks of files to avoid reading the whole big file

Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)

How to install iPhone application in iPhone Simulator

From Xcode v4.3, it is being installed as application. The simulator is available at

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS\ Simulator.app/

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

On jenkins 2.x, with groovy plugin 2.0, running SystemGroovyScript I managed to get to build variables, as below:

def build = this.getProperty('binding').getVariable('build')
def listener = this.getProperty('binding').getVariable('listener')
def env = build.getEnvironment(listener)
println env.MY_VARIABLE

If you are using goovy from file, simple System.getenv('MY_VARIABLE') is sufficient

Curl error: Operation timed out

Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with "Curl error: Operation timed out after .."

Start and stop a timer PHP

Also you can use HRTime package. It has a class StopWatch.

how to refresh my datagridview after I add new data

You can use a binding source to bind to with your datagridview. Set your class or list of data. Set a bindingsource.datasource equal to that. Set the datasource of your datagridview to your bindingsource.

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

You can use functions in pyspark.sql.functions: functions like year, month, etc

refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame

from pyspark.sql.functions import *

newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))

newdf.show()


+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no|    dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497601|
|   2015|       9|     6|      249|      0|     0|        36|1441497603|
|   2015|       9|     6|      249|      0|     1|        36|1441497694|
|   2015|       9|     6|      249|      0|    20|        36|1441498808|
|   2015|       9|     6|      249|      0|    20|        36|1441498811|
|   2015|       9|     6|      249|      0|    20|        36|1441498815|

Detect if a Form Control option button is selected in VBA

You should remove .Value from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.

If you want to run action code when the optionbutton is clicked then don't write an if loop for that.

EXAMPLE:

Sub CommandButton1_Click
    If OptionButton1 = true then
        (action code...)
    End if
End sub

Sub OptionButton1_Click   
    (action code...)
End sub

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

Explode string by one or more spaces or tabs

The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.

# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {  
  # Split the input string into an array
  $parts = preg_split('/\s+/', $str);
  # Get the size of the array of substrings
  $sizeParts = sizeof($parts);
  # Check if the last element of the array is a zero-length string
  if ($sizeParts > 0) {
    $lastPart = $parts[$sizeParts-1];
    if ($lastPart == '') {
      array_pop($parts);
      $sizeParts--;
    }
    # Check if the first element of the array is a zero-length string
    if ($sizeParts > 0) {
      $firstPart = $parts[0];
      if ($firstPart == '') 
        array_shift($parts); 
    }
  }
  return $parts;   
}

setImmediate vs. nextTick

As an illustration

import fs from 'fs';
import http from 'http';

const options = {
  host: 'www.stackoverflow.com',
  port: 80,
  path: '/index.html'
};

describe('deferredExecution', () => {
  it('deferredExecution', (done) => {
    console.log('Start');
    setTimeout(() => console.log('TO1'), 0);
    setImmediate(() => console.log('IM1'));
    process.nextTick(() => console.log('NT1'));
    setImmediate(() => console.log('IM2'));
    process.nextTick(() => console.log('NT2'));
    http.get(options, () => console.log('IO1'));
    fs.readdir(process.cwd(), () => console.log('IO2'));
    setImmediate(() => console.log('IM3'));
    process.nextTick(() => console.log('NT3'));
    setImmediate(() => console.log('IM4'));
    fs.readdir(process.cwd(), () => console.log('IO3'));
    console.log('Done');
    setTimeout(done, 1500);
  });
});

will give the following output

Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1

I hope this can help to understand the difference.

Updated:

Callbacks deferred with process.nextTick() run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.

Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)

How to make for loops in Java increase by increments other than 1

It's just a syntax error. You just have to replace j+3 by j=j+3 or j+=3.

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

Checking during array iteration, if the current element is the last element

I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
    if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                            // just to use this `hasNext()` method to see
                            // if this is the last element
       echo $each;
    }
}

how to fix Cannot call sendRedirect() after the response has been committed?

you have already forwarded the response in catch block:

RequestDispatcher dd = request.getRequestDispatcher("error.jsp");

dd.forward(request, response);

so, you can not again call the :

response.sendRedirect("usertaskpage.jsp");

because it is already forwarded (committed).

So what you can do is: keep a string to assign where you need to forward the response.

    String page = "";
    try {

    } catch (Exception e) {
      page = "error.jsp";
    } finally {
      page = "usertaskpage.jsp";
    }

RequestDispatcher dd=request.getRequestDispatcher(page);
dd.forward(request, response);

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I have found that adding these lines of code to the pom.xml file of the maven project solves similar issues for me:-

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.packagename.MainClassName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How can I plot a confusion matrix?

@bninopaul 's answer is not completely for beginners

here is the code you can "copy and run"

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[13,1,1,0,2,0],
         [3,9,6,0,1,0],
         [0,0,16,2,0,0],
         [0,0,0,13,0,0],
         [0,0,0,0,15,0],
         [0,0,1,0,0,15]]

df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size

plt.show()

result

json call with C#

just continuing what @Mulki made with his code

public string WebRequestinJson(string url, string postData)
{
    string ret = string.Empty;

    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }

    HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
    Stream resStream = resp.GetResponseStream();
    StreamReader reader = new StreamReader(resStream);
    ret = reader.ReadToEnd();

    return ret;
}

SyntaxError: missing ) after argument list

use:

my_function({width:12});

Instead of:

my_function(width:12);

How to reliably open a file in the same directory as a Python script

On Python 3.4, the pathlib module was added, and the following code will reliably open a file in the same directory as the current script:

from pathlib import Path

p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
    print(f.read())

You can also use parent.absolute() to get directory value as a string if needed:

p = Path(__file__)
dir_abs = p.parent.absolute()  # Will return the executable directory absolute path

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

How to throw an exception in C?

If you write code with Happy path design pattern (i.e. for embedded device) you may simulate exception error processing (aka deffering or finally emulation) with operator "goto".

int process(int port)
{
    int rc;
    int fd1;
    int fd2;

    fd1 = open("/dev/...", ...);
    if (fd1 == -1) {
      rc = -1;
      goto out;
    }

    fd2 = open("/dev/...", ...);
    if (fd2 == -1) {
      rc = -1;
      goto out;
    }

    // Do some with fd1 and fd2 for example write(f2, read(fd1))

    rc = 0;

   out:

    //if (rc != 0) {
        (void)close(fd1);
        (void)close(fd2);
    //}

    return rc;
}

It does not actually exception handler but it take you a way to handle error at fucntion exit.

P.S. You should be careful use goto only from same or more deep scopes and never jump variable declaration.

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

The user owner for me is the admin user and the group is _www and works with permissions set to 775 for dir and for files 664

How to make a simple popup box in Visual C#?

Try this:

string text = "My text that I want to display";
MessageBox.Show(text);

Why does this CSS margin-top style not work?

Try using display: inline-block; on the inner div.

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:block;
}
#inner {
    background:#FFCC33;
    margin:50px 50px 50px 50px;
    padding:10px;
    display:inline-block;
}

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

Sum a list of numbers in Python

All answers did show a programmatic and general approach. I suggest a mathematical approach specific for your case. It can be faster in particular for long lists. It works because your list is a list of natural numbers up to n:

Let's assume we have the natural numbers 1, 2, 3, ..., 10:

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You can use the sum function on a list:

>>> print sum(nat_seq)
55

You can also use the formula n*(n+1)/2 where n is the value of the last element in the list (here: nat_seq[-1]), so you avoid iterating over elements:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

To generate the sequence (1+2)/2, (2+3)/2, ..., (9+10)/2 you can use a generator and the formula (2*k-1)/2. (note the dot to make the values floating points). You have to skip the first element when generating the new list:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

Here too, you can use the sum function on that list:

>>> print sum(new_seq)
49.5

But you can also use the formula (((n*2+1)/2)**2-1)/2, so you can avoid iterating over elements:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

How do I extract value from Json

see this code what i am used in my application

String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";

I retrieved like this

JSONObject json = (JSONObject) JSONSerializer.toJSON(data);        
    double coolness = json.getDouble( "coolness" );
    int altitude = json.getInt( "altitude" );
    JSONObject pilot = json.getJSONObject("pilot");
    String firstName = pilot.getString("firstName");
    String lastName = pilot.getString("lastName");

    System.out.println( "Coolness: " + coolness );
    System.out.println( "Altitude: " + altitude );
    System.out.println( "Pilot: " + lastName );

How to use the TextWatcher class in Android?

Supplemental answer

Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.

  • Red: text about to be deleted (replaced)
  • Green: text that was just added (replacing the old red text)

enter image description here

Could not load NIB in bundle

Had this same issue nothing worked, so I figured something weird with derived data.

In xcode 6.3.2 I had to:

In XCode Menu --> Preferences --> Locations Tab --> In Locations Change Derived Data to Relative and then toggle back to Default

Then the nib loaded fine.

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() {
  this.style.backgroundColor = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
};
div.onmouseout = function() {
  this.style.backgroundColor = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';
};

How to vertically align elements in a div?

using display flex, first you need to wrap the container of the item that you want to align.

<div class="outdiv">
      <div class="indiv">
         <span>test1</span>
         <span>test2</span>
      </div>
    </div>

then apply the following css to wrapper div or outdiv in my example

.outdiv {
    display: flex;
    justify-content:center;
    align-items:center;
}

How to use a WSDL file to create a WCF service (not make a call)

You could use svcutil.exe to generate client code. This would include the definition of the service contract and any data contracts and fault contracts required.

Then, simply delete the client code: classes that implement the service contracts. You'll then need to implement them yourself, in your service.

Force encode from US-ASCII to UTF-8 (iconv)

I accidentally encoded a file in UTF-7 and had a similar issue. When I typed file -i name.file I would get charset=us-ascii.

iconv -f us-ascii -t utf-9//translit name.file would not work since I've gathered UTF-7 is a subset of US ASCII, as is UTF-8.

To solve this, I entered

iconv -f UTF-7 -t UTF-8//TRANSLIT name.file -o output.file

I'm not sure how to determine the encoding other than what others have suggested here.

How to completely remove node.js from Windows

In my case, the above alone didn't work. I had installed and uninstalled several versions of nodejs to fix this error: npm in windows Error: EISDIR, read at Error (native) that I kept getting on any npm command I tried to run, including getting the npm version with: npm -v.

So the npm directory was deleted in the nodejs folder and the latest npm version was copied over from the npm dist: and then everything started working.

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

Build fails with "Command failed with a nonzero exit code"

Switching to the legacy build system fixed the issue for me

Get the element triggering an onclick event in jquery?

You can pass the inline handler the this keyword, obtaining the element which fired the event.

like,

onclick="confirmSubmit(this);"

Maximum request length exceeded.

I can add to config web uncompiled

<system.web> 
  <httpRuntime maxRequestLength="1024" executionTimeout="3600" /> 
  <compilation debug="true"/> 
</system.web> 
<security> 
  <requestFiltering> 
    <requestLimits maxAllowedContentLength="1048576"/> 
  </requestFiltering> 
</security>

How to execute a Ruby script in Terminal?

Assuming ruby interpreter is in your PATH (it should be), you simply run

ruby your_file.rb

Open URL in same window and in same tab

If you have your pages inside "frame" then "Window.open('logout.aspx','_self')"

will be redirected inside same frame. So by using

"Window.open('logout.aspx','_top')"

we can load the page as new request.

jquery draggable: how to limit the draggable area?

See excerpt from official documentation for containment option:

containment

Default: false

Constrains dragging to within the bounds of the specified element or region.
Multiple types supported:

  • Selector: The draggable element will be contained to the bounding box of the first element found by the selector. If no element is found, no containment will be set.
  • Element: The draggable element will be contained to the bounding box of this element.
  • String: Possible values: "parent", "document", "window".
  • Array: An array defining a bounding box in the form [ x1, y1, x2, y2 ].

Code examples:
Initialize the draggable with the containment option specified:

$( ".selector" ).draggable({
    containment: "parent" 
}); 

Get or set the containment option, after initialization:

// Getter
var containment = $( ".selector" ).draggable( "option", "containment" );
// Setter
$( ".selector" ).draggable( "option", "containment", "parent" );

Connecting to a network folder with username/password in Powershell

This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:

net use \\server\share /user:<domain\username> <password>

And then do whatever you need to do in PowerShell...

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

Spring Boot REST service exception handling

@RestControllerAdvice is a new feature of Spring Framework 4.3 to handle Exception with RestfulApi by a cross-cutting concern solution:

 package com.khan.vaquar.exception;

import javax.servlet.http.HttpServletRequest;

import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.khan.vaquar.domain.ErrorResponse;

/**
 * Handles exceptions raised through requests to spring controllers.
 **/
@RestControllerAdvice
public class RestExceptionHandler {

    private static final String TOKEN_ID = "tokenId";

    private static final Logger log = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * Handles InstructionExceptions from the rest controller.
     * 
     * @param e IntrusionException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IntrusionException.class)
    public ErrorResponse handleIntrusionException(HttpServletRequest request, IntrusionException e) {       
        log.warn(e.getLogMessage(), e);
        return this.handleValidationException(request, new ValidationException(e.getUserMessage(), e.getLogMessage()));
    }

    /**
     * Handles ValidationExceptions from the rest controller.
     * 
     * @param e ValidationException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = ValidationException.class)
    public ErrorResponse handleValidationException(HttpServletRequest request, ValidationException e) {     
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);

        if (e.getUserMessage().contains("Token ID")) {
            tokenId = "<OMITTED>";
        }

        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(),
                                    e.getUserMessage());
    }

    /**
     * Handles JsonProcessingExceptions from the rest controller.
     * 
     * @param e JsonProcessingException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = JsonProcessingException.class)
    public ErrorResponse handleJsonProcessingException(HttpServletRequest request, JsonProcessingException e) {     
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(),
                                    e.getOriginalMessage());
    }

    /**
     * Handles IllegalArgumentExceptions from the rest controller.
     * 
     * @param e IllegalArgumentException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ErrorResponse handleIllegalArgumentException(HttpServletRequest request, IllegalArgumentException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = UnsupportedOperationException.class)
    public ErrorResponse handleUnsupportedOperationException(HttpServletRequest request, UnsupportedOperationException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    /**
     * Handles MissingServletRequestParameterExceptions from the rest controller.
     * 
     * @param e MissingServletRequestParameterException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public ErrorResponse handleMissingServletRequestParameterException( HttpServletRequest request, 
                                                                        MissingServletRequestParameterException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.BAD_REQUEST.value(), 
                                    e.getClass().getSimpleName(), 
                                    e.getMessage());
    }

    /**
     * Handles NoHandlerFoundExceptions from the rest controller.
     * 
     * @param e NoHandlerFoundException
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ErrorResponse handleNoHandlerFoundException(HttpServletRequest request, NoHandlerFoundException e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.info(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.NOT_FOUND.value(), 
                                    e.getClass().getSimpleName(), 
                                    "The resource " + e.getRequestURL() + " is unavailable");
    }

    /**
     * Handles all remaining exceptions from the rest controller.
     * 
     * This acts as a catch-all for any exceptions not handled by previous exception handlers.
     * 
     * @param e Exception
     * @return error response POJO
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public ErrorResponse handleException(HttpServletRequest request, Exception e) {
        String tokenId = request.getParameter(TOKEN_ID);
        log.error(e.getMessage(), e);
        return new ErrorResponse(   tokenId,
                                    HttpStatus.INTERNAL_SERVER_ERROR.value(), 
                                    e.getClass().getSimpleName(), 
                                    "An internal error occurred");
    }   

}

How to find the width of a div using vanilla JavaScript?

Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.

python - find index position in list based of partial string

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)

html5 audio player - jquery toggle click play/pause?

Here is my solution using jQuery

<script type="text/javascript">
    $('#mtoogle').toggle(
        function () {
            document.getElementById('playTune').pause();
        },
        function () {
            document.getElementById('playTune').play();
        }
    );
</script>

And the working demo

http://demo.ftutorials.com/html5-audio/

How to close activity and go back to previous activity in android

You have to use this in your MainActivity

 Intent intent = new Intent(context , yourActivity);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            context.startActivity(intent);

The flag will start multiple tasks that will keep your MainActivity, when you call finish it will kill the other activity and get you back to the MainActivity

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

Cannot find Microsoft.Office.Interop Visual Studio

With Visual Studio 2015 I have activated it with the following steps.

  1. Programs and Features --> Select Visual Studio > Change
  2. Choose Modify
  3. Windows and Webdevelopment --> Tick "Microsoft Office Developer Tools"
  4. Start Update

It should work now.

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

SQL Server, division returns zero

Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)

PRINT @set1 
PRINT @set2 
SET @weight= @set1 / @set2 *1.00000; 
PRINT @weight

Checking if a textbox is empty in Javascript

onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

_x000D_
_x000D_
function checkTextField(field) {_x000D_
  document.getElementById("error").innerText =_x000D_
    (field.value === "") ? "Field is empty." : "Field is filled.";_x000D_
}
_x000D_
<input type="text" onblur="checkTextField(this);" />_x000D_
<p id="error"></p>
_x000D_
_x000D_
_x000D_

(Or old live demo.)

Transparent background on winforms?

A simple solution to get a transparent background in a windows form is to overwrite the OnPaintBackground method like this:

protected override void OnPaintBackground(PaintEventArgs e)
{
    //empty implementation
}

(Notice that the base.OnpaintBackground(e) is removed from the function)

How to display a readable array - Laravel

dd() dumps the variable and ends the execution of the script (1), so surrounding it with <pre> tags will leave it broken. Just use good ol' var_dump() (or print_r() if you know it's an array)

Route::get('/', function()
{
    echo '<pre>';
    var_dump(User::all());
    echo '</pre>';
    //exit;  <--if you want
});

Update:

I think you could format down what's shown by having Laravel convert the model object to array:

Route::get('/', function()
{
    echo '<pre>';
    $user = User::where('person_id', '=', 1);
    var_dump($user->toArray()); // <---- or toJson()
    echo '</pre>';
    //exit;  <--if you want
});

(1) For the record, this is the implementation of dd():

function dd()
{
    array_map(function($x) { var_dump($x); }, func_get_args()); die;
}

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

Is there shorthand for returning a default value if None in Python?

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

How to check String in response body with mockMvc

Here is an example how to parse JSON response and even how to send a request with a bean in JSON form:

  @Autowired
  protected MockMvc mvc;

  private static final ObjectMapper MAPPER = new ObjectMapper()
    .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .registerModule(new JavaTimeModule());

  public static String requestBody(Object request) {
    try {
      return MAPPER.writeValueAsString(request);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> T parseResponse(MvcResult result, Class<T> responseClass) {
    try {
      String contentAsString = result.getResponse().getContentAsString();
      return MAPPER.readValue(contentAsString, responseClass);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Test
  public void testUpdate() {
    Book book = new Book();
    book.setTitle("1984");
    book.setAuthor("Orwell");
    MvcResult requestResult = mvc.perform(post("http://example.com/book/")
      .contentType(MediaType.APPLICATION_JSON)
      .content(requestBody(book)))
      .andExpect(status().isOk())
      .andReturn();
    UpdateBookResponse updateBookResponse = parseResponse(requestResult, UpdateBookResponse.class);
    assertEquals("1984", updateBookResponse.getTitle());
    assertEquals("Orwell", updateBookResponse.getAuthor());
  }

As you can see here the Book is a request DTO and the UpdateBookResponse is a response object parsed from JSON. You may want to change the Jackson's ObjectMapper configuration.

HTML5 Video tag not working in Safari , iPhone and iPad

Another possible solution for you future searchers: (If your problem is not a mimetype issue.)

For some reason videos would not play on iPad unless i set the controls="true" flag.

Example: This worked for me on iPhone but not iPad.

<video loop autoplay width='100%' height='100%' src='//some_video.mp4' type='video/mp4'></video>

And this now works on both iPad and iPhone:

<video loop autoplay controls="true" width='100%' height='100%' src='//some_video.mp4' type='video/mp4'></video>

How to generate a git patch for a specific commit?

if you just want diff the specified file, you can :

git diff master 766eceb -- connections/ > 000-mysql-connector.patch

How to clean old dependencies from maven repositories?

Given a POM file for a maven project you can remove all its dependencies in the local repository (by default ~/.m2/respository) using the Apache Maven Dependency Plugin.

It includes the dependency:purge-local-repository functionality that removes the project dependencies from the local repository, and optionally re-resolve them.

To clean the local dependencies you just have to used the optional parameter reResolve and set it to false since it is set to true by default.

This command line call should work:

mvn dependency:purge-local-repository -DreResolve=false

How to overwrite the output directory in spark

since df.save(path, source, mode) is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)

use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter

'source' can be ("com.databricks.spark.avro" | "parquet" | "json")

Vue.js img src concatenate variable and text

If it helps, I am using the following to get a gravatar image:

<img
        :src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
        class="rounded-circle"
        :width="size"
    />

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

How do I check if a number is a palindrome?

This is one of the Project Euler problems. When I solved it in Haskell I did exactly what you suggest, convert the number to a String. It's then trivial to check that the string is a pallindrome. If it performs well enough, then why bother making it more complex? Being a pallindrome is a lexical property rather than a mathematical one.

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

Select records from today, this week, this month php mysql

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

how to File.listFiles in alphabetical order?

The listFiles method, with or without a filter does not guarantee any order.

It does, however, return an array, which you can sort with Arrays.sort().

File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
    ...
}

This works because File is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.

If you prefer using Streams:

A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:

Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)

Replace the System.out::println with whatever you want to do with the file names. If you want only filenames that end with "xml" just do:

Files.list(Paths.get(dirName))
    .filter(s -> s.toString().endsWith(".xml"))
    .sorted()
    .forEach(System.out::println)

Again, replace the printing with whichever processing operation you would like.

How to unstage large number of files without deleting the content

2019 update

As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>.

To unstage all the files in your project, run the following from the root of the repository (the command is recursive):

git restore --staged .

If you only want to unstage the files in a directory, navigate to it before running the above or run:

git restore --staged <directory-path>

Notes

  • git restore was introduced in July 2019 and released in version 2.23.
    With the --staged flag, it restores the content of the working tree from HEAD (so it does the opposite of git add and does not delete any change).

  • This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset or git reset HEAD are still perfectly valid.

  • When running git status with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file> as it used to prior to v2.23).

Pad with leading zeros

The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.

Console.WriteLine("{0:0000000}", FileRecordCount);

Forgot to end the double quotes!

What does 'const static' mean in C and C++?

A lot of people gave the basic answer but nobody pointed out that in C++ const defaults to static at namespace level (and some gave wrong information). See the C++98 standard section 3.5.3.

First some background:

Translation unit: A source file after the pre-processor (recursively) included all its include files.

Static linkage: A symbol is only available within its translation unit.

External linkage: A symbol is available from other translation units.

At namespace level

This includes the global namespace aka global variables.

static const int sci = 0; // sci is explicitly static
const int ci = 1;         // ci is implicitly static
extern const int eci = 2; // eci is explicitly extern
extern int ei = 3;        // ei is explicitly extern
int i = 4;                // i is implicitly extern
static int si = 5;        // si is explicitly static

At function level

static means the value is maintained between function calls.
The semantics of function static variables is similar to global variables in that they reside in the program's data-segment (and not the stack or the heap), see this question for more details about static variables' lifetime.

At class level

static means the value is shared between all instances of the class and const means it doesn't change.

How do I vertically center an H1 in a div?

HTML

<div id='sample'>
<span class='vertical'>Test Message</span>
</div>

CSS

    #sample 
    {
        height:100px;
         width:100%;
        background-color:#003366;
        display:table;
        text-align: center;

    }
    .vertical 
    {
           color:white;
         display:table-cell;
        vertical-align:middle;
}

Fiddle : Demo

Ansible: get current target host's IP address

You can get the IP address from hostvars, dict ansible_default_ipv4 and key address

hostvars[inventory_hostname]['ansible_default_ipv4']['address']

and IPv6 address respectively

hostvars[inventory_hostname]['ansible_default_ipv6']['address']

An example playbook:

---
- hosts: localhost
  tasks:
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv6']['address']

Is Google Play Store supported in avd emulators?

It's not officially supported yet.

Edit: It's now supported in modern versions of Android Studio, at least on some platforms.

Old workarounds

If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:

  1. Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.

  2. Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk ]. Then use adb install to install the .apk file.

how to delete files from amazon s3 bucket?

Via which interface? Using the REST interface, you just send a delete:

DELETE /ObjectName HTTP/1.1
Host: BucketName.s3.amazonaws.com
Date: date
Content-Length: length
Authorization: signatureValue

Via the SOAP interface:

<DeleteObject xmlns="http://doc.s3.amazonaws.com/2006-03-01">
  <Bucket>quotes</Bucket>
  <Key>Nelson</Key>
  <AWSAccessKeyId> 1D9FVRAYCP1VJEXAMPLE=</AWSAccessKeyId>
  <Timestamp>2006-03-01T12:00:00.183Z</Timestamp>
  <Signature>Iuyz3d3P0aTou39dzbqaEXAMPLE=</Signature>
</DeleteObject>

If you're using a Python library like boto, it should expose a "delete" feature, like delete_key().