Programs & Examples On #Unix

The Unix operating system is a general purpose OS that was developed by Bell Labs in the late 1960s and today exists in various versions. Important note: This tag is exclusively for programming questions that are directly related to Unix; general software issues should be directed to the Unix & Linux Stack Exchange site or to Super User.

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

Aborting a shell script if any command returns a non-zero value

The $? variable is rarely needed. The pseudo-idiom command; if [ $? -eq 0 ]; then X; fi should always be written as if command; then X; fi.

The cases where $? is required is when it needs to be checked against multiple values:

command
case $? in
  (0) X;;
  (1) Y;;
  (2) Z;;
esac

or when $? needs to be reused or otherwise manipulated:

if command; then
  echo "command successful" >&2
else
  ret=$?
  echo "command failed with exit code $ret" >&2
  exit $ret
fi

npm throws error without sudo

use below command while installing packages

 sudo npm install --unsafe-perm=true --allow-root

How to make grep only match if the entire line matches?

This is with HPUX, if the content of the files has space between words, use this:

egrep "[[:space:]]ABC\.log[[:space:]]" a.tmp

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

Sometimes you need to use double brackets, otherwise you get an error like too many arguments

if [[ $OUTMERGE == *"fatal"* ]] || [[ $OUTMERGE == *"Aborting"* ]]
  then
fi

change PATH permanently on Ubuntu

Add

export PATH=$PATH:/home/me/play

to your ~/.profile and execute

source ~/.profile 

in order to immediately reflect changes to your current terminal instance.

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

How do I open a URL from C++?

Create a function and copy the code using winsock which is mentioned already by Software_Developer.

For Instance:

#ifdef _WIN32

// this is required only for windows

if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{

  //...

}

#endif

winsock code here

#ifdef _WIN32

WSACleanup();

#endif

'^M' character at end of lines

Another vi command that'll do: :%s/.$// This removes the last character of each line in the file. The drawback to this search and replace command is that it doesn't care what the last character is, so be careful not to call it twice.

Unix: How to delete files listed in a file

This is not very efficient, but will work if you need glob patterns (as in /var/www/*)

for f in $(cat 1.txt) ; do 
  rm "$f"
done

If you don't have any patterns and are sure your paths in the file do not contain whitespaces or other weird things, you can use xargs like so:

xargs rm < 1.txt

how to find host name from IP with out login to the host

python -c "import socket;print(socket.gethostbyaddr('127.0.0.1'))"

if you just need the name, no additional info, add [0] at the end:

python -c "import socket;print(socket.gethostbyaddr('8.8.8.8'))[0]"

Diff files present in two different directories

If you are only interested to see the files that differ, you may use:

diff -qr dir_one dir_two | sort

Option "q" will only show the files that differ but not the content that differ, and "sort" will arrange the output alphabetically.

compare two files in UNIX

There are 3 basic commands to compare files in unix:

  1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

  2. comm : This command is used to find out the records available in one but not in another

  3. diff

List of Java processes

I use this (good on Debian 8): alias psj='ps --no-headers -ww -C java -o pid,user,start_time,command'

Trim leading and trailing spaces from a string in awk

remove leading and trailing white space in 2nd column

awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt

another way by one gsub:

awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile

Environment variable substitution in sed

?. bad way: change delimiter

sed 's/xxx/'"$PWD"'/'
sed 's:xxx:'"$PWD"':'
sed 's@xxx@'"$PWD"'@'

maybe those not the final answer,

you can not known what character will occur in $PWD, / : OR @.

the good way is replace(escape) the special character in $PWD.

?. good way: escape delimiter

for example: try to replace URL as $url (has : / in content)

x.com:80/aa/bb/aa.js

in string $tmp

<a href="URL">URL</a>

A. use / as delimiter

escape / as \/ in var (before use in sed expression)

echo ${url//\//\\/}
x.com:80\/aa\/bb\/aa.js   #escape fine

echo ${url//\//\/}
x.com:80/aa/bb/aa.js      #escape not success

echo "${url//\//\/}"
x.com:80\/aa\/bb\/aa.js   #escape fine, notice `"`

echo $tmp | sed "s/URL/${url//\//\\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>

echo $tmp | sed "s/URL/${url//\//\/}/"
<a href="x.com:80/aa/bb/aa.js">URL</a>

OR

B. use : as delimiter (more readable than /)

escape : as \: in var (before use in sed expression)

echo ${url//:/\:}
x.com:80/aa/bb/aa.js     #escape not success

echo "${url//:/\:}"
x.com\:80/aa/bb/aa.js    #escape fine, notice `"`

echo $tmp | sed "s:URL:${url//:/\:}:g"
<a href="x.com:80/aa/bb/aa.js">x.com:80/aa/bb/aa.js</a>

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

Had the same error when installing PhantomJS on Ubuntu 14.04 64bit with gcc-4.8 (CXXABI_1.3.7)

Upgrading to gcc-4.9 (CXXABI_1.3.8) fixed the issue. HOWTO: https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04

How can I convert tabs to spaces in every file of a directory?

Git repository friendly method

git-tab-to-space() (
  d="$(mktemp -d)"
  git grep --cached -Il '' | grep -E "${1:-.}" | \
    xargs -I'{}' bash -c '\
    f="${1}/f" \
    && expand -t 4 "$0" > "$f" && \
    chmod --reference="$0" "$f" && \
    mv "$f" "$0"' \
    '{}' "$d" \
  ;
  rmdir "$d"
)

Act on all files under the current directory:

git-tab-to-space

Act only on C or C++ files:

git-tab-to-space '\.(c|h)(|pp)$'

You likely want this notably because of those annoying Makefiles which require tabs.

The command git grep --cached -Il '':

  • lists only the tracked files, so nothing inside .git
  • excludes directories, binary files (would be corrupted), and symlinks (would be converted to regular files)

as explained at: How to list all text (non-binary) files in a git repository?

chmod --reference keeps the file permissions unchanged: https://unix.stackexchange.com/questions/20645/clone-ownership-and-permissions-from-another-file Unfortunately I can't find a succinct POSIX alternative.

If your codebase had the crazy idea to allow functional raw tabs in strings, use:

expand -i

and then have fun going over all non start of line tabs one by one, which you can list with: Is it possible to git grep for tabs?

Tested on Ubuntu 18.04.

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

How to split a delimited string into an array in awk?

I do not like the echo "..." | awk ... solution as it calls unnecessary fork and execsystem calls.

I prefer a Dimitre's solution with a little twist

awk -F\| '{print $3 $2 $1}' <<<'12|23|11'

Or a bit shorter version:

awk -F\| '$0=$3 $2 $1' <<<'12|23|11'

In this case the output record put together which is a true condition, so it gets printed.

In this specific case the stdin redirection can be spared with setting an internal variable:

awk -v T='12|23|11' 'BEGIN{split(T,a,"|");print a[3] a[2] a[1]}'

I used quite a while, but in this could be managed by internal string manipulation. In the first case the original string is split by internal terminator. In the second case it is assumed that the string always contains digit pairs separated by a one character separator.

T='12|23|11';echo -n ${T##*|};T=${T%|*};echo ${T#*|}${T%|*}
T='12|23|11';echo ${T:6}${T:3:2}${T:0:2}

The result in all cases is

112312

grep --ignore-case --only

It should be a problem in your version of grep.

Your test cases are working correctly here on my machine:

$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC

And my version is:

$ grep --version
grep (GNU grep) 2.10

How do you extract IP addresses from files using a regex in a linux shell?

You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:

perl -n '/(\d+\.\d+\.\d+\.\d+)/ && print "$1\n"' < file

How to get the current directory in a C program?

Look up the man page for getcwd.

Display filename before matching line

How about this, which I managed to achieve thanks, in part, to this post.

You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE), inside several directories with a pattern (e.g. /logsapp1, /logsapp2). Each file has a pattern you want to grep (e.g. "init time"), and you want to have the "init time" of each file, but knowing which file it belongs to.

find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt

Then the outputfilename.txt would be something like

./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms

In general

find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt

Explanation:

find command will search the filenames based in the pattern

then, pipe xargs -I{} will redirect the find output to the {}

which will be the input for grep ""pattern" {}

Then the trick to make grep display the filenames \dev\null

and finally, write the output in file with tee outputfile.txt

This worked for me in grep version 9.0.5 build 1989.

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

How to run a shell script on a Unix console or Mac terminal?

First, give permission for execution:-
chmod +x script_name

  1. If script is not executable:-
    For running sh script file:-
    sh script_name
    For running bash script file:-
    bash script_name
  2. If script is executable:-
    ./script_name

NOTE:-you can check if the file is executable or not by using 'ls -a'

centos: Another MySQL daemon already running with the same unix socket

TL;DR:

Run this as root and you'll be all set:

rm $(grep socket /etc/my.cnf | cut -d= -f2)  && service mysqld start

Longer version:

You can find the location of MySQL's socket file by manually poking around in /etc/my.conf, or just by using

grep socket /etc/my.cnf | cut -d= -f2

It is likely to be /var/lib/mysql/mysql.sock. Then (as root, of course, or with sudo prepended) remove that file:

rm /var/lib/mysql/mysql.sock

Then start the MySQL daemon:

service mysqld start

Removing mysqld will not address the problem at all. The problem is that CentOS & RedHat do not clean up the sock file after a crash, so you have to do it yourself. Avoiding powering off your system is (of course) also advised, but sometimes you can't avoid it, so this procedure will solve the problem.

Restarting cron after changing crontab file?

On CentOS with cPanel sudo /etc/init.d/crond reload does the trick.

On CentOS7: sudo systemctl start crond.service

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

To go the other way:

double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;

Truncate to Int64 and/or use TotalSeconds as needed.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

In the old days, "/opt" was used by UNIX vendors like AT&T, Sun, DEC and 3rd-party vendors to hold "Option" packages; i.e. packages that you might have paid extra money for. I don't recall seeing "/opt" on Berkeley BSD UNIX. They used "/usr/local" for stuff that you installed yourself.

But of course, the true "meaning" of the different directories has always been somewhat vague. That is arguably a good thing, because if these directories had precise (and rigidly enforced) meanings you'd end up with a proliferation of different directory names.

According to the Filesystem Hierarchy Standard, /opt is for "the installation of add-on application software packages". /usr/local is "for use by the system administrator when installing software locally".

How do I escape spaces in path for scp copy in Linux?

Also you can do something like:

scp foo@bar:"\"apath/with spaces in it/\""

The first level of quotes will be interpreted by scp and then the second level of quotes will preserve the spaces.

In the shell, what does " 2>&1 " mean?

From a programmer's point of view, it means precisely this:

dup2(1, 2);

See the man page.

Understanding that 2>&1 is a copy also explains why ...

command >file 2>&1

... is not the same as ...

command 2>&1 >file

The first will send both streams to file, whereas the second will send errors to stdout, and ordinary output into file.

How to read a file into a variable in shell?

If you want to read the whole file into a variable:

#!/bin/bash
value=`cat sources.xml`
echo $value

If you want to read it line-by-line:

while read line; do    
    echo $line    
done < file.txt

Differences between fork and exec

The main difference between fork() and exec() is that,

The fork() system call creates a clone of the currently running program. The original program continues execution with the next line of code after the fork() function call. The clone also starts execution at the next line of code. Look at the following code that i got from http://timmurphy.org/2014/04/26/using-fork-in-cc-a-minimum-working-example/

#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    printf("--beginning of program\n");
    int counter = 0;
    pid_t pid = fork();
    if (pid == 0)
    {
        // child process
        int i = 0;
        for (; i < 5; ++i)
        {
            printf("child process: counter=%d\n", ++counter);
        }
    }
    else if (pid > 0)
    {
        // parent process
        int j = 0;
        for (; j < 5; ++j)
        {
            printf("parent process: counter=%d\n", ++counter);
        }
    }
    else
    {
        // fork failed
        printf("fork() failed!\n");
        return 1;
    }
    printf("--end of program--\n");
    return 0;
}

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

The exec() family of system calls replaces the currently executing code of a process with another piece of code. The process retains its PID but it becomes a new program. For example, consider the following code:

#include <stdio.h> 
#include <unistd.h> 
main() {
 char program[80],*args[3];
 int i; 
printf("Ready to exec()...\n"); 
strcpy(program,"date"); 
args[0]="date"; 
args[1]="-u"; 
args[2]=NULL; 
i=execvp(program,args); 
printf("i=%d ... did it work?\n",i); 
} 

This program calls the execvp() function to replace its code with the date program. If the code is stored in a file named exec1.c, then executing it produces the following output:

Ready to exec()... 
Tue Jul 15 20:17:53 UTC 2008 

The program outputs the line -Ready to exec() . . . ? and after calling the execvp() function, replaces its code with the date program. Note that the line - . . . did it work? is not displayed, because at that point the code has been replaced. Instead, we see the output of executing -date -u.?

Why should text files end with a newline?

A separate use case: when your text file is version controlled (in this case specifically under git although it applies to others too). If content is added to the end of the file, then the line that was previously the last line will have been edited to include a newline character. This means that blameing the file to find out when that line was last edited will show the text addition, not the commit before that you actually wanted to see.

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

How can I check if a directory exists in a Bash shell script?

I find the double-bracket version of test makes writing logic tests more natural:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi

In Python script, how do I set PYTHONPATH?

you can set PYTHONPATH, by os.environ['PATHPYTHON']=/some/path, then you need to call os.system('python') to restart the python shell to make the newly added path effective.

Find all files with name containing string

An alternative to the many solutions already provided is making use of the glob **. When you use bash with the option globstar (shopt -s globstar) or you make use of zsh, you can just use the glob ** for this.

**/bar

does a recursive directory search for files named bar (potentially including the file bar in the current directory). Remark that this cannot be combined with other forms of globbing within the same path segment; in that case, the * operators revert to their usual effect.

Note that there is a subtle difference between zsh and bash here. While bash will traverse soft-links to directories, zsh will not. For this you have to use the glob ***/ in zsh.

What do pty and tty mean?

If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system

Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).

Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .

For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.

How to move (and overwrite) all files from one directory to another?

It's also possible by using rsync, for example:

rsync -va --delete-after src/ dst/

where:

  • -v, --verbose: increase verbosity
  • -a, --archive: archive mode; equals -rlptgoD (no -H,-A,-X)
  • --delete-after: delete files on the receiving side be done after the transfer has completed

If you've root privileges, prefix with sudo to override potential permission issues.

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Instead of explicitly defining the path to the interpreter as in /usr/bin/bash/, by using the env command, the interpreter is searched for and launched from wherever it is first found. This has both upsides and downsides

How to display line numbers in 'less' (GNU)

If you hit = and expect to see line numbers, but only see byte counts, then line numbers are turned off. Hit -n to turn them on, and make sure $LESS doesn't include 'n'.

Turning off line numbers by default (for example, setting LESS=n) speeds up searches in very large files. It is handy if you frequently search through big files, but don't usually care which line you're on.

I typically run with LESS=RSXin (escape codes enabled, long lines chopped, don't clear the screen on exit, ignore case on all lower case searches, and no line number counting by default) and only use -n or -S from inside less as needed.

UNIX export command

Unix

The commands env, set, and printenv display all environment variables and their values. env and set are also used to set environment variables and are often incorporated directly into the shell. printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.

In Unix, the following commands can also be used, but are often dependent on a certain shell.

export VARIABLE=value  # for Bourne, bash, and related shells
setenv VARIABLE value  # for csh and related shells

You can have a look at this at

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

Shell script to copy files from one location to another location and rename add the current date to every file

cp --archive home/webapps/project1/folder1/{aaa,bbb,ccc,ddd}.csv home/webapps/project1/folder2
rename 's/\.csv$/'$(date +%m%d%Y).csv'/' home/webapps/project1/folder2/{aaa,bbb,ccc,ddd}.csv

Explanation:

  • --archive ensures that the files are copied with the same ownership and permissions.
  • foo{bar,baz} is expanded into foobar foobaz.
  • rename is a commonly available program to do exactly this kind of substitution.

PS: don't use ls for this.

How do I syntax check a Bash script without running it?

null command [colon] also useful when debugging to see variable's value

set -x
for i in {1..10}; do
    let i=i+1
    : i=$i
done
set - 

How do I remove the passphrase for the SSH key without having to create a new key?

Short answer:

$ ssh-keygen -p

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).


If you would like to do it all on one line without prompts do:

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.

Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

Difference between sh and bash

Post from UNIX.COM

Shell features

This table below lists most features that I think would make you choose one shell over another. It is not intended to be a definitive list and does not include every single possible feature for every single possible shell. A feature is only considered to be in a shell if in the version that comes with the operating system, or if it is available as compiled directly from the standard distribution. In particular the C shell specified below is that available on SUNOS 4.*, a considerable number of vendors now ship either tcsh or their own enhanced C shell instead (they don't always make it obvious that they are shipping tcsh.

Code:

                                     sh   csh  ksh  bash tcsh zsh  rc   es
Job control                          N    Y    Y    Y    Y    Y    N    N
Aliases                              N    Y    Y    Y    Y    Y    N    N
Shell functions                      Y(1) N    Y    Y    N    Y    Y    Y
"Sensible" Input/Output redirection  Y    N    Y    Y    N    Y    Y    Y
Directory stack                      N    Y    Y    Y    Y    Y    F    F
Command history                      N    Y    Y    Y    Y    Y    L    L
Command line editing                 N    N    Y    Y    Y    Y    L    L
Vi Command line editing              N    N    Y    Y    Y(3) Y    L    L
Emacs Command line editing           N    N    Y    Y    Y    Y    L    L
Rebindable Command line editing      N    N    N    Y    Y    Y    L    L
User name look up                    N    Y    Y    Y    Y    Y    L    L
Login/Logout watching                N    N    N    N    Y    Y    F    F
Filename completion                  N    Y(1) Y    Y    Y    Y    L    L
Username completion                  N    Y(2) Y    Y    Y    Y    L    L
Hostname completion                  N    Y(2) Y    Y    Y    Y    L    L
History completion                   N    N    N    Y    Y    Y    L    L
Fully programmable Completion        N    N    N    N    Y    Y    N    N
Mh Mailbox completion                N    N    N    N(4) N(6) N(6) N    N
Co Processes                         N    N    Y    N    N    Y    N    N
Builtin artithmetic evaluation       N    Y    Y    Y    Y    Y    N    N
Can follow symbolic links invisibly  N    N    Y    Y    Y    Y    N    N
Periodic command execution           N    N    N    N    Y    Y    N    N
Custom Prompt (easily)               N    N    Y    Y    Y    Y    Y    Y
Sun Keyboard Hack                    N    N    N    N    N    Y    N    N
Spelling Correction                  N    N    N    N    Y    Y    N    N
Process Substitution                 N    N    N    Y(2) N    Y    Y    Y
Underlying Syntax                    sh   csh  sh   sh   csh  sh   rc   rc
Freely Available                     N    N    N(5) Y    Y    Y    Y    Y
Checks Mailbox                       N    Y    Y    Y    Y    Y    F    F
Tty Sanity Checking                  N    N    N    N    Y    Y    N    N
Can cope with large argument lists   Y    N    Y    Y    Y    Y    Y    Y
Has non-interactive startup file     N    Y    Y(7) Y(7) Y    Y    N    N
Has non-login startup file           N    Y    Y(7) Y    Y    Y    N    N
Can avoid user startup files         N    Y    N    Y    N    Y    Y    Y
Can specify startup file             N    N    Y    Y    N    N    N    N
Low level command redefinition       N    N    N    N    N    N    N    Y
Has anonymous functions              N    N    N    N    N    N    Y    Y
List Variables                       N    Y    Y    N    Y    Y    Y    Y
Full signal trap handling            Y    N    Y    Y    N    Y    Y    Y
File no clobber ability              N    Y    Y    Y    Y    Y    N    F
Local variables                      N    N    Y    Y    N    Y    Y    Y
Lexically scoped variables           N    N    N    N    N    N    N    Y
Exceptions                           N    N    N    N    N    N    N    Y

Key to the table above.

Y Feature can be done using this shell.

N Feature is not present in the shell.

F Feature can only be done by using the shells function mechanism.

L The readline library must be linked into the shell to enable this Feature.

Notes to the table above

1. This feature was not in the original version, but has since become
   almost standard.
2. This feature is fairly new and so is often not found on many
   versions of the shell, it is gradually making its way into
   standard distribution.
3. The Vi emulation of this shell is thought by many to be
   incomplete.
4. This feature is not standard but unofficial patches exist to
   perform this.
5. A version called 'pdksh' is freely available, but does not have
   the full functionality of the AT&T version.
6. This can be done via the shells programmable completion mechanism.
7. Only by specifying a file via the ENV environment variable.

How to find the files that are created in the last hour in unix

Check out this link for more details.

To find files which are created in last one hour in current directory, you can use -amin

find . -amin -60 -type f

This will find files which are created with in last 1 hour.

How to run the sftp command with a password from Bash script?

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

Find and replace in file and overwrite file doesn't work, it empties the file

You can use Vim in Ex mode:

ex -sc '%s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g|x' index.html
  1. % select all lines

  2. x save and close

How do I write stderr to a file while using "tee" with a pipe?

If you're using zsh, you can use multiple redirections, so you don't even need tee:

./cmd 1>&1 2>&2 1>out_file 2>err_file

Here you're simply redirecting each stream to itself and the target file.


Full example

% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err

Note that this requires the MULTIOS option to be set (which is the default).

MULTIOS

Perform implicit tees or cats when multiple redirections are attempted (see Redirection).

Hide/encrypt password in bash file to stop accidentally seeing it

Following line in above code is not working

DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)

Correct line is:

DB_PASSWORD=`echo $PASSWORD|base64 -d`

And save the password in other file as PASSWORD.

What does ^M character mean in Vim?

To translate the new line instead of removing it:

:%s/\r/\r/g

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Is there a way to make mv create the directory to be moved to if it doesn't exist?

I frequently stumble upon this issue while bulk moving files to new subdirectories. Ideally, I want to do this:

mv * newdir/  

Most of the answers in this thread propose to mkdir and then mv, but this results in:

mkdir newdir && mv * newdir 
mv: cannot move 'newdir/' to a subdirectory of itself

The problem I face is slightly different in that I want to blanket move everything, and, if I create the new directory before moving then it also tries to move the new directory to itself. So, I work around this by using the parent directory:

mkdir ../newdir && mv * ../newdir && mv ../newdir .

Caveats: Does not work in the root folder (/).

Fastest way to tell if two files have the same contents in Unix/Linux?

I believe cmp will stop at the first byte difference:

cmp --silent $old $new || echo "files are different"

How to attach a file using mail command on Linux?

With mailx you can do:

mailx -s "My Subject"  -a ./mail_att.csv -S [email protected]  [email protected] < ./mail_body.txt

This worked great on our GNU Linux servers, but unfortunately my dev environment is Mac OsX which only has a crummy old BSD version of mailx. Normally I use Coreutils to get better versions of unix commands than the Mac BSD ones, but mailx is not in Coreutils.

I found a solution from notpeter in an unrelated thread (https://serverfault.com/questions/196001/using-unix-mail-mailx-with-a-modern-mail-server-imap-instead-of-mbox-files) which was to download the Heirloom mailx OSX binary package from http://www.tramm.li/iWiki/HeirloomNotes.html. It has a more featured mailx which can handle the above command syntax.

(Apologies for poor cross linking linking or attribution, I'm new to the site.)

How to use "/" (directory separator) in both Linux and Windows in Python?

Use os.path.join(). Example: os.path.join(pathfile,"output","log.txt").

In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))

Get last field using awk substr

I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

$ var1='/home/parent/child1/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/child3/filename'
$ echo ${var1##*/}
filename

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

I think you're a little confused. PYTHONPATH sets the search path for importing python modules, not for executing them like you're trying.

PYTHONPATH Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.

http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH

What you're looking for is PATH.

export PATH=$PATH:/home/randy/lib/python 

However, to run your python script as a program, you also need to set a shebang for Python in the first line. Something like this should work:

#!/usr/bin/env python

And give execution privileges to it:

chmod +x /home/randy/lib/python/gbmx.py

Then you should be able to simply run gmbx.py from anywhere.

How do I list all the files in a directory and subdirectories in reverse chronological order?

find -type f -print0 | xargs -0 ls -t

Drawback: Works only to a certain amount of files. If you have extremly large amounts of files you need something more complicated

gpg decryption fails with no secret key error

When migrating from one machine to another-

  1. Check the gpg version and supported algorithms between the two systems.

    gpg --version

  2. Check the presence of keys on both systems.

    gpg --list-keys

    pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04

    gpg --list-secret-keys

    sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04

Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.

If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.

Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.

gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>

gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key

Use space as a delimiter with cut command

scut, a cut-like utility (smarter but slower I made) that can use any perl regex as a breaking token. Breaking on whitespace is the default, but you can also break on multi-char regexes, alternative regexes, etc.

scut -f='6 2 8 7' < input.file  > output.file

so the above command would break columns on whitespace and extract the (0-based) cols 6 2 8 7 in that order.

Add up a column of numbers at the Unix shell

Pipe to gawk:

 cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'

ORA-00054: resource busy and acquire with NOWAIT specified

You'll have to wait. The session that was killed was in the middle of a transaction and updated lots of records. These records have to be rollbacked and some background process is taking care of that. In the meantime you cannot modify the records that were touched.

127 Return code from $?

It has no special meaning, other than that the last process to exit did so with an exit status of 127.

However, it is also used by bash (assuming you're using bash as a shell) to tell you that the command you tried to execute couldn't be executed (i.e. it couldn't be found). It's unfortunately not immediately deducible though, if the process exited with status 127, or if it couldn't found.

EDIT:
Not immediately deducible, except for the output on the console, but this is stack overflow, so I assume you're doing this in a script.

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

cd into directory without having permission

@user812954's answer was quite helpful, except I had to do this this in two steps:

sudo su
cd directory

Then, to exit out of "super user" mode, just type exit.

Using `date` command to get previous, current and next month

the main problem occur when you don't have date --date option available and you don't have permission to install it, then try below -

Previous month
#cal -3|awk 'NR==1{print toupper(substr($1,1,3))"-"$2}'
DEC-2016 
Current month
#cal -3|awk 'NR==1{print toupper(substr($3,1,3))"-"$4}'
JAN-2017
Next month
#cal -3|awk 'NR==1{print toupper(substr($5,1,3))"-"$6}'
FEB-2017

Print a file's last modified date in Bash

You can use the stat command

stat -c %y "$entry"

More info

%y   time of last modification, human-readable

C fopen vs open

Using open, read, write means you have to worry about signal interaptions.

If the call was interrupted by a signal handler the functions will return -1 and set errno to EINTR.

So the proper way to close a file would be

while (retval = close(fd), retval == -1 && ernno == EINTR) ;

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

How can I add a help method to a shell script?

For a quick single option solution, use if

If you only have a single option to check and it will always be the first option ($1) then the simplest solution is an if with a test ([). For example:

if [ "$1" == "-h" ] ; then
    echo "Usage: `basename $0` [-h]"
    exit 0
fi

Note that for posix compatibility = will work as well as ==.

Why quote $1?

The reason the $1 needs to be enclosed in quotes is that if there is no $1 then the shell will try to run if [ == "-h" ] and fail because == has only been given a single argument when it was expecting two:

$ [ == "-h" ]
bash: [: ==: unary operator expected

For anything more complex use getopt or getopts

As suggested by others, if you have more than a single simple option, or need your option to accept an argument, then you should definitely go for the extra complexity of using getopts.

As a quick reference, I like The 60 second getopts tutorial.

You may also want to consider the getopt program instead of the built in shell getopts. It allows the use of long options, and options after non option arguments (e.g. foo a b c --verbose rather than just foo -v a b c). This Stackoverflow answer explains how to use GNU getopt.

jeffbyrnes mentioned that the original link died but thankfully the way back machine had archived it.

Unix command to find lines common in two files

To complement the Perl one-liner, here's its awk equivalent:

awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2

This will read all lines from file1 into the array arr[], and then check for each line in file2 if it already exists within the array (i.e. file1). The lines that are found will be printed in the order in which they appear in file2. Note that the comparison in arr uses the entire line from file2 as index to the array, so it will only report exact matches on entire lines.

Bash or KornShell (ksh)?

I'm a korn-shell veteran, so know that I speak from that perspective.

However, I have been comfortable with Bourne shell, ksh88, and ksh93, and for the most I know which features are supported in which. (I should skip ksh88 here, as it's not widely distributed anymore.)

For interactive use, take whatever fits your need. Experiment. I like being able to use the same shell for interactive use and for programming.

I went from ksh88 on SVR2 to tcsh, to ksh88sun (which added significant internationalisation support) and ksh93. I tried bash, and hated it because it flattened my history. Then I discovered shopt -s lithist and all was well. (The lithist option assures that newlines are preserved in your command history.)

For shell programming, I'd seriously recommend ksh93 if you want a consistent programming language, good POSIX conformance, and good performance, as many common unix commands can be available as builtin functions.

If you want portability use at least both. And make sure you have a good test suite.

There are many subtle differences between shells. Consider for example reading from a pipe:

b=42 && echo one two three four |
    read a b junk && echo $b

This will produce different results in different shells. The korn-shell runs pipelines from back to front; the last element in the pipeline runs in the current process. Bash did not support this useful behaviour until v4.x, and even then, it's not the default.

Another example illustrating consistency: The echo command itself, which was made obsolete by the split between BSD and SYSV unix, and each introduced their own convention for not printing newlines (and other behaviour). The result of this can still be seen in many 'configure' scripts.

Ksh took a radical approach to that - and introduced the print command, which actually supports both methods (the -n option from BSD, and the trailing \c special character from SYSV)

However, for serious systems programming I'd recommend something other than a shell, like python, perl. Or take it a step further, and use a platform like puppet - which allows you to watch and correct the state of whole clusters of systems, with good auditing.

Shell programming is like swimming in uncharted waters, or worse.

Programming in any language requires familiarity with its syntax, its interfaces and behaviour. Shell programming isn't any different.

Command-line Unix ASCII-based charting / plotting tool

Here is my patch for eplot that adds a -T option for terminal output:

--- eplot       2008-07-09 16:50:04.000000000 -0400
+++ eplot+      2017-02-02 13:20:23.551353793 -0500
@@ -172,7 +172,10 @@
                                        com=com+"set terminal postscript color;\n"
                                        @o["DoPDF"]=true

-                               # ---- Specify a custom output file
+                               when /^-T$|^--terminal$/
+                                       com=com+"set terminal dumb;\n"
+
+                                # ---- Specify a custom output file
                                when /^-o$|^--output$/
                                        @o["OutputFileSpecified"]=checkOptArg(xargv,i)
                                        i=i+1

                                    i=i+1

Using this you can run it as eplot -T to get ASCII-graphics result instead of a gnuplot window.

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

top -c command in linux to filter processes listed based on processname

I ended up using a shell script with the following code:

#!/bin/bash

while [ 1 == 1 ]
do
    clear
    ps auxf |grep -ve "grep" |grep -E "MSG[^\ ]*" --color=auto
    sleep 5
done

Sorting data based on second column of a file

For tab separated values the code below can be used

sort -t$'\t' -k2 -n

-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code

sort -t$'\t' -k2 -rn

Is mongodb running?

check with either:

   ps -edaf | grep mongo | grep -v grep  # "ps" flags may differ on your OS

or

   /etc/init.d/mongodb status     # for MongoDB version < 2.6

   /etc/init.d/mongod status      # for MongoDB version >= 2.6

or

   service mongod status

to see if mongod is running (you need to be root to do this, or prefix everything with sudo). Please note that the 'grep' command will always also show up as a separate process.

check the log file /var/log/mongo/mongo.log to see if there are any problems reported

Copy all files with a certain extension from all subdirectories

find [SOURCEPATH] -type f -name '[PATTERN]' | 
    while read P; do cp --parents "$P" [DEST]; done

you may remove the --parents but there is a risk of collision if multiple files bear the same name.

How do I pause my shell script for a second before continuing?

Use the sleep command.

Example:

sleep .5 # Waits 0.5 second.
sleep 5  # Waits 5 seconds.
sleep 5s # Waits 5 seconds.
sleep 5m # Waits 5 minutes.
sleep 5h # Waits 5 hours.
sleep 5d # Waits 5 days.

One can also employ decimals when specifying a time unit; e.g. sleep 1.5s

Waiting for background processes to finish before exiting script

If you want to wait for jobs to finish, use wait. This will make the shell wait until all background jobs complete. However, if any of your jobs daemonize themselves, they are no longer children of the shell and wait will have no effect (as far as the shell is concerned, the child is already done. Indeed, when a process daemonizes itself, it does so by terminating and spawning a new process that inherits its role).

#!/bin/sh
{ sleep 5; echo waking up after 5 seconds; } &
{ sleep 1; echo waking up after 1 second; } &
wait
echo all jobs are done!

Move top 1000 lines from text file to a new file using Unix shell commands

This is a one-liner but uses four atomic commands:

head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp

How to set environment variable for everyone under my linux system?

Some interesting excerpts from the bash manpage:

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
...
When an interactive shell that is not a login shell is started, bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of /etc/bash.bashrc and ~/.bashrc.

So have a look at /etc/profile or /etc/bash.bashrc, these files are the right places for global settings. Put something like this in them to set up an environement variable:

export MY_VAR=xxx

How to use find command to find all files with extensions from list?

On Mac OS use

find -E packages  -regex ".*\.(jpg|gif|png|jpeg)"

Setting environment variables in Linux using Bash

Set a local and environment variable using Bash on Linux

Check for a local or environment variables for a variable called LOL in Bash:

el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $

Sanity check, no local or environment variable called LOL.

Set a local variable called LOL in local, but not environment. So set it:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $

Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash.

Set a local variable, and then clear out all local variables in Bash

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $

You could also just unset the one variable:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $

Local variable LOL is gone.

Promote a local variable to an environment variable:

el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable

Note that exporting makes it show up as both a local variable and an environment variable.

Exported variable DOGE above survives a Bash reset:

el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'

Unset all environment variables:

You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:

el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN

You created an environment variable, and then reset the terminal to get rid of them.

Or you could set and unset an environment variable manually like this:

el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $

Creating temporary files in bash

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)

Remove all files in a directory

os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:

os.system('rm '+test)

Else you can:

import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
   os.remove(i)

How to append contents of multiple files into one file

You need the cat (short for concatenate) command, with shell redirection (>) into your output file

cat 1.txt 2.txt 3.txt > 0.txt

How to get last items of a list in Python?

a negative index will count from the end of the list, so:

num_list[-9:]

SQL Query - Using Order By in UNION

SELECT table1Column1 as col1,table1Column2 as col2
    FROM table1
UNION
(    SELECT table2Column1 as col1, table1Column2 as col2
         FROM table2
)
ORDER BY col1 ASC

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

OK, encouraged by jimhark here is an example of the old single hash table approach: -

CREATE PROCEDURE SP3 as

BEGIN

    SELECT 1, 'Data1'
    UNION ALL
    SELECT 2, 'Data2'

END
go


CREATE PROCEDURE SP2 as

BEGIN

    if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
        INSERT INTO #tmp1
        EXEC SP3
    else
        EXEC SP3

END
go

CREATE PROCEDURE SP1 as

BEGIN

    EXEC SP2

END
GO


/*
--I want some data back from SP3

-- Just run the SP1

EXEC SP1
*/


/*
--I want some data back from SP3 into a table to do something useful
--Try run this - get an error - can't nest Execs

if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
    DROP TABLE #tmp1

CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))

INSERT INTO #tmp1
EXEC SP1


*/

/*
--I want some data back from SP3 into a table to do something useful
--However, if we run this single hash temp table it is in scope anyway so
--no need for the exec insert

if exists (select  * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tmp1'))
    DROP TABLE #tmp1

CREATE TABLE #tmp1 (ID INT, Data VARCHAR(20))

EXEC SP1

SELECT * FROM #tmp1

*/

Select default option value from typescript angular 6

You may use bellow like in angular 9

 <select [(ngModel)]="itemId"  formControlName="itemId" class="form-control" >
          <option [ngValue]="" disabled>Choose Gender</option>             
          <option *ngFor="let item of items"  [ngValue]="item .id" [selected]="item .id == this.id"  >
             {{item.name}}
          </option>
   </select>

Showing empty view when ListView is empty

Just to add that you don't really need to create new IDs, something like the following will work.

In the layout:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list"/>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@android:id/empty"
    android:text="Empty"/>

Then in the activity:

    ListView listView = (ListView) findViewById(android.R.id.list);
    listView.setEmptyView(findViewById(android.R.id.empty));

Find package name for Android apps to use Intent to launch Market app from web

If you want this information in your phone, then best is to use an app like 'APKit' that shows the full package name of each app in you phone. This information can then be used in your phone.

How to find out which package version is loaded in R?

To check the version of R execute : R --version

Or after you are in the R shell print the contents of version$version.string

EDIT

To check the version of installed packages do the following.

After loading the library, you can execute sessionInfo ()

But to know the list of all installed packages:

packinfo <- installed.packages(fields = c("Package", "Version"))
packinfo[,c("Package", "Version")]

OR to extract a specific library version, once you have extracted the information using the installed.package function as above just use the name of the package in the first dimension of the matrix.

packinfo["RANN",c("Package", "Version")]
packinfo["graphics",c("Package", "Version")]

The above will print the versions of the RANN library and the graphics library.

How to wait for a process to terminate to execute another process in batch file

'start /w' does NOT work in all cases. The original solution works great. However, on some machines, it is wise to put a delay immediately after starting the executable. Otherwise, the task name may not appear in the task list yet, and the loop will not work as expected (someone pointed that out). The 2 delays can be combined and put at the top of the loop. Can also get rid of the 'else' just to shorten. Example of 2 programs running sequentially:

c:\prog1.exe 
:loop1
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog1.exe" >nul 2>&1
if errorlevel 1 goto cont1
goto loop1
:cont1

c:\prog2.exe
:loop2
timeout /t 1 /nobreak >nul 2>&1
tasklist | find /i "prog2.exe" >nul 2>&1
if errorlevel 1 goto cont2
goto loop2
:cont2

john refling

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 10
});

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.

How to get the input from the Tkinter Text Widget?

To get Tkinter input from the text box, you must add a few more attributes to the normal .get() function. If we have a text box myText_Box, then this is the method for retrieving its input.

def retrieve_input():
    input = self.myText_Box.get("1.0",END)

The first part, "1.0" means that the input should be read from line one, character zero (ie: the very first character). END is an imported constant which is set to the string "end". The END part means to read until the end of the text box is reached. The only issue with this is that it actually adds a newline to our input. So, in order to fix it we should change END to end-1c(Thanks Bryan Oakley) The -1c deletes 1 character, while -2c would mean delete two characters, and so on.

def retrieve_input():
    input = self.myText_Box.get("1.0",'end-1c')

How do I get formatted JSON in .NET using C#?

You may use following standard method for getting formatted Json

JsonReaderWriterFactory.CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)

Only set "indent==true"

Try something like this

    public readonly DataContractJsonSerializerSettings Settings = 
            new DataContractJsonSerializerSettings
            { UseSimpleDictionaryFormat = true };

    public void Keep<TValue>(TValue item, string path)
    {
        try
        {
            using (var stream = File.Open(path, FileMode.Create))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    using (var writer = JsonReaderWriterFactory.CreateJsonWriter(
                        stream, Encoding.UTF8, true, true, "  "))
                    {
                        var serializer = new DataContractJsonSerializer(type, Settings);
                        serializer.WriteObject(writer, item);
                        writer.Flush();
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch (Exception exception)
        {
            Debug.WriteLine(exception.ToString());
        }
    }

Pay your attention to lines

    var currentCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
    ....
    Thread.CurrentThread.CurrentCulture = currentCulture;

For some kinds of xml-serializers you should use InvariantCulture to avoid exception during deserialization on the computers with different Regional settings. For example, invalid format of double or DateTime sometimes cause them.

For deserializing

    public TValue Revive<TValue>(string path, params object[] constructorArgs)
    {
        try
        {
            using (var stream = File.OpenRead(path))
            {
                //var currentCulture = Thread.CurrentThread.CurrentCulture;
                //Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                try
                {
                    var serializer = new DataContractJsonSerializer(type, Settings);
                    var item = (TValue) serializer.ReadObject(stream);
                    if (Equals(item, null)) throw new Exception();
                    return item;
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                    return (TValue) Activator.CreateInstance(type, constructorArgs);
                }
                finally
                {
                    //Thread.CurrentThread.CurrentCulture = currentCulture;
                }
            }
        }
        catch
        {
            return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);
        }
    }

Thanks!

Very simple C# CSV reader

First of all need to understand what is CSV and how to write it.

(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)

  1. Every next string ( /r/n ) is next "table" row.
  2. "Table" cells is separated by some delimiter symbol.
  3. As delimiter can be used ANY symbol. Often this is \t or ,.
  4. Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)
  5. Each cell possibly can contains /r/n symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)

Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO library. Using this simple class you will be able to work with CSV like with 2 dimensions array.

Simple example of using my library:

Csv csv = new Csv("\t");//delimiter symbol

csv.FileOpen("c:\\file1.csv");

var row1Cell6Value = csv.Rows[0][5];

csv.AddRow("asdf","asdffffff","5")

csv.FileSave("c:\\file2.csv");

You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter

This library code is really fast in work and source code is really short.

PS: In the same time this solution will not work for unity.

PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.

How to insert element into arrays at specific position?

Simplest solution, if you want to insert (an element or array) after a certain key:

function array_splice_after_key($array, $key, $array_to_insert)
{
    $key_pos = array_search($key, array_keys($array));
    if($key_pos !== false){
        $key_pos++;
        $second_array = array_splice($array, $key_pos);
        $array = array_merge($array, $array_to_insert, $second_array);
    }
    return $array;
}

So, if you have:

$array = [
    'one' => 1,
    'three' => 3
];
$array_to_insert = ['two' => 2];

And execute:

$result_array = array_splice_after_key($array, 'one', $array_to_insert);

You'll have:

Array ( 
    ['one'] => 1 
    ['two'] => 2 
    ['three'] => 3 
)

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I too encountered this issue while auto inserting a sysdate to a column.

What I did is I changed my system date format to match with SQL server's date format. e.g. my SQL format was mm/dd/yyyy and my system format was set to dd/mm/yyyy. I changed my system format to mm/dd/yyyy and error gone

-kb

JPA: unidirectional many-to-one and cascading delete

Use this way to delete only one side

    @ManyToOne(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
//  @JoinColumn(name = "qid")
    @JoinColumn(name = "qid", referencedColumnName = "qid", foreignKey = @ForeignKey(name = "qid"), nullable = false)
    // @JsonIgnore
    @JsonBackReference
    private QueueGroup queueGroup;

Understanding the main method of python

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

meth1
main code

More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

html form - make inputs appear on the same line

use table

<table align="center" width="100%" cellpadding="0" cellspacing="0" border="0"> 
<tr>
<td><label for="First_Name">First Name:</label></td>
<td><input name="first_name" id="First_Name" type="text" /></td>
<td><label for="last_name">Last Name:</label></td> <td> 
<input name="last_name" id="Last_Name" type="text" /></td> 
</tr> 
<tr> 
<td colspan="2"><label for="Email">Email:</label></td> 
<td colspan="2"><input name="email" id="Email" type="email" /></td> 
</tr> 
<tr> 
<td colspan="4"><input type="submit" value="Submit"/></td> 
</tr> 
</table>

Check if a string contains a number

You can use NLTK method for it.

This will find both '1' and 'One' in the text:

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Naming returned columns in Pandas aggregate function?

This will drop the outermost level from the hierarchical column index:

df = data.groupby(...).agg(...)
df.columns = df.columns.droplevel(0)

If you'd like to keep the outermost level, you can use the ravel() function on the multi-level column to form new labels:

df.columns = ["_".join(x) for x in df.columns.ravel()]

For example:

import pandas as pd
import pandas.rpy.common as com
import numpy as np

data = com.load_data('Loblolly')
print(data.head())
#     height  age Seed
# 1     4.51    3  301
# 15   10.89    5  301
# 29   28.72   10  301
# 43   41.74   15  301
# 57   52.70   20  301

df = data.groupby('Seed').agg(
    {'age':['sum'],
     'height':['mean', 'std']})
print(df.head())
#       age     height           
#       sum        std       mean
# Seed                           
# 301    78  22.638417  33.246667
# 303    78  23.499706  34.106667
# 305    78  23.927090  35.115000
# 307    78  22.222266  31.328333
# 309    78  23.132574  33.781667

df.columns = df.columns.droplevel(0)
print(df.head())

yields

      sum        std       mean
Seed                           
301    78  22.638417  33.246667
303    78  23.499706  34.106667
305    78  23.927090  35.115000
307    78  22.222266  31.328333
309    78  23.132574  33.781667

Alternatively, to keep the first level of the index:

df = data.groupby('Seed').agg(
    {'age':['sum'],
     'height':['mean', 'std']})
df.columns = ["_".join(x) for x in df.columns.ravel()]

yields

      age_sum   height_std  height_mean
Seed                           
301        78    22.638417    33.246667
303        78    23.499706    34.106667
305        78    23.927090    35.115000
307        78    22.222266    31.328333
309        78    23.132574    33.781667

How to compile Tensorflow with SSE4.2 and AVX instructions?

2.0 COMPATIBLE SOLUTION:

Execute the below commands in Terminal (Linux/MacOS) or in Command Prompt (Windows) to install Tensorflow 2.0 using Bazel:

git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow

#The repo defaults to the master development branch. You can also checkout a release branch to build:
git checkout r2.0

#Configure the Build => Use the Below line for Windows Machine
python ./configure.py 

#Configure the Build => Use the Below line for Linux/MacOS Machine
./configure
#This script prompts you for the location of TensorFlow dependencies and asks for additional build configuration options. 

#Build Tensorflow package

#CPU support
bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package 

#GPU support
bazel build --config=opt --config=cuda --define=no_tensorflow_py_deps=true //tensorflow/tools/pip_package:build_pip_package

Entity Framework The underlying provider failed on Open

This solution is for someone facing this issue while deploying a windows application,

I know this is late, but this maybe useful for someone in future, In my scenario, purely this is a connection string issue I developed a windows application using entity framework (DB First approach) and I published it, the code was worked fine on my machine, but it's not worked on the client machine

Reason for this issue:-

I updated the client machine connection string in App.config file, but this is wrong, if that is a windows application, then it will not read the connection string from App.config (For deployed machines), it will read from .exe.config file,

So after deployment, we need to change the connection string in "AppicationName".exe.config file

Count the number of Occurrences of a Word in a String

This should be a faster non-regex solution.
(note - Not a Java programmer)

 String str = "i have a male cat. the color of male cat is Black";
 int found  = 0;
 int oldndx = 0;
 int newndx = 0;

 while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
 {
     found++;
     oldndx = newndx+8;
 }

Tar archiving that takes input from a list of files

On Solaris, you can use the option -I to read the filenames that you would normally state on the command line from a file. In contrast to the command line, this can create tar archives with hundreds of thousands of files (just did that).

So the example would read

tar -cvf allfiles.tar -I mylist.txt

How do you concatenate Lists in C#?

Concat returns a new sequence without modifying the original list. Try myList1.AddRange(myList2).

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

Convert hex to binary

Use Built-in format() function and int() function It's simple and easy to understand. It's little bit simplified version of Aaron answer

int()

int(string, base)

format()

format(integer, # of bits)

Example

# w/o 0b prefix
>> format(int("ABC123EFFF", 16), "040b")
1010101111000001001000111110111111111111

# with 0b prefix
>> format(int("ABC123EFFF", 16), "#042b")
0b1010101111000001001000111110111111111111

# w/o 0b prefix + 64bit
>> format(int("ABC123EFFF", 16), "064b")
0000000000000000000000001010101111000001001000111110111111111111

See also this answer

How to delete a specific line in a file?

Save the file lines in a list, then remove of the list the line you want to delete and write the remain lines to a new file

with open("file_name.txt", "r") as f:
    lines = f.readlines() 
    lines.remove("Line you want to delete\n")
    with open("new_file.txt", "w") as new_f:
        for line in lines:        
            new_f.write(line)

Rotate axis text in python matplotlib

To rotate the x-axis label to 90 degrees

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

How to run ssh-add on windows?

I have been in similar situation before. In Command prompt, you type 'start-ssh-agent' and voila! The ssh-agent will be started. Input the passphrase if it asked you.

Scroll Element into View with Selenium

Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.

I chose this over the JavaScript injection technique just because it felt less hacky.

Raise warning in Python without interrupting program

You shouldn't raise the warning, you should be using warnings module. By raising it you're generating error, rather than warning.

How to force link from iframe to be opened in the parent window

The most versatile and most cross-browser solution is to avoid use of the "base" tag, and instead use the target attribute of the "a" tags:

<a target="_parent" href="http://www.stackoverflow.com">Stack Overflow</a>

The <base> tag is less versatile and browsers are inconsistent in their requirements for its placement within the document, requiring more cross-browser testing. Depending on your project and situation, it can be difficult or even totally unfeasible to achieve the ideal cross-browser placement of the <base> tag.

Doing this with the target="_parent" attribute of the <a> tag is not only more browser-friendly, but also allows you to distinguish between those links you want to open in the iframe, and those you want to open in the parent.

Renaming part of a filename

for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done

No rename or sed needed. Just bash parameter expansion.

What does the symbol \0 mean in a string-literal?

Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:

$ cat junk.c
#include <stdio.h>

char* string = "Hello\0";

int main(int argv, char** argc)
{
    printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s

... eliding the unnecessary parts ...

.LC0:
    .string "Hello"
    .string ""

...

.LC1:
    .string "-->%s<--\n"

...

Note here how the string I used for printf is just "-->%s<---\n" while the global string is in two parts: "Hello" and "". The GNU assembler also terminates strings with an implicit NUL character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NULs. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S (for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";

lessons is Main table and lessons_game is subtable so Right Join

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

How does Google calculate my location on a desktop?

I am currently in Tokyo, and I used to be in Switzerland. Yet, my location until some days ago was not pinpinted exactly, except in the broad Tokyo area. Today I tried, and I appear to be in Switzerland. How?

Well the secret is that I am now connected through wireless, and my wireless router has been identified (thanks to association to other wifis around me at that time) in a very accurate area in Switzerland. Now, my wifi moved to Tokyo, but the queried system still thinks the wifi router is in Switzerland, because either it has no information about the additional wifis surrounding me right now, or it cannot sort out the conflicting info (namely, the specific info about my wifi router against my ip geolocation, which pinpoints me in the far east).

So, to answer your question, google, or someone for him, did "wardriving" around, mapping the wifi presence. Every time a query is performed to the system (probably in compliance with the W3C draft for the geolocation API) your computer sends the wifi identifiers it sees, and the system does two things:

  1. queries its database if geolocation exists for some of the wifis you passed, and returns the "wardrived" position if found, eventually with triangulation if intensities are present. The more wifi networks around, the higher is the accuracy of the positioning.
  2. adds additional networks you see that are currently not in the database to their database, so they can be reused later.

As you see, the system builds up by itself. The only thing you need is good seeding. After that, it extends in "50 meters chunks" (the range of a newly found wifi connection).

Of course, if you really want the system go banana, you can start exchanging wifi routers around the globe with fellow revolutionaries of the no-global-positioning movement.

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

Retrieve Button value with jQuery

 <!DOCTYPE html>
 <html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
 </script>
 <script>
 $(document).ready(function(){
   $("#hide").click(function(){
    $("p").toggle();

    var x = $("#hide").text();

      if(x=="Hide"){
      $("button").html("show");

      }
     else 
     {
     $("button").html("Hide");

      }

       });

   });

  </script>
  </head>
  <body>

 <p>If you click on the "Hide" button, I will disappear.</p>

 <button id="hide">Hide</button>



 </body>
 </html>

What's the difference between %s and %d in Python string formatting?

These are all informative answers, but none are quite getting at the core of what the difference is between %s and %d.

%s tells the formatter to call the str() function on the argument and since we are coercing to a string by definition, %s is essentially just performing str(arg).

%d on the other hand, is calling int() on the argument before calling str(), like str(int(arg)), This will cause int coercion as well as str coercion.

For example, I can convert a hex value to decimal,

>>> '%d' % 0x15
'21'

or truncate a float.

>>> '%d' % 34.5
'34'

But the operation will raise an exception if the argument isn't a number.

>>> '%d' % 'thirteen'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So if the intent is just to call str(arg), then %s is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.

With the f-string notation, when you leave the formatter out, the default is str.

>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'

The same is true with string.format; the default is str.

>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'

Insert new column into table in sqlite?

You have two options. First, you could simply add a new column with the following:

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:

ALTER TABLE {tableName} RENAME TO TempOldTable;

Then create the new table with the missing column:

CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);

And populate it with the old data:

INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;

Then delete the old table:

DROP TABLE TempOldTable;

I'd much prefer the second option, as it will allow you to completely rename everything if need be.

When to use window.opener / window.parent / window.top

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

offsetTop vs. jQuery.offset().top

This is what jQuery API Doc says about .offset():

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

This is what MDN Web API says about .offsetTop:

offsetTop returns the distance of the current element relative to the top of the offsetParent node

This is what jQuery v.1.11 .offset() basically do when getting the coords:

var box = { top: 0, left: 0 };

// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
  box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
  top: box.top  + ( win.pageYOffset || docElem.scrollTop )  - ( docElem.clientTop  || 0 ),
  left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
  • pageYOffset intuitively says how much was the page scrolled
  • docElem.scrollTop is the fallback for IE<9 (which are BTW unsupported in jQuery 2)
  • docElem.clientTop is the width of the top border of an element (the document in this case)
  • elem.getBoundingClientRect() gets the coords relative to the document viewport (see comments). It may return fraction values, so this is the source of your bug. It also may cause a bug in IE<8 when the page is zoomed. To avoid fraction values, try to calculate the position iteratively

Conclusion

  • If you want coords relative to the parent node, use element.offsetTop. Add element.scrollTop if you want to take the parent scrolling into account. (or use jQuery .position() if you are fan of that library)
  • If you want coords relative to the viewport use element.getBoundingClientRect().top. Add window.pageYOffset if you want to take the document scrolling into account. You don't need to subtract document's clientTop if the document has no border (usually it doesn't), so you have position relative to the document
  • Subtract element.clientTop if you don't consider the element border as the part of the element

Java: how can I split an ArrayList in multiple small ArrayLists?

You can add the Guava library to your project and use the Lists.partition method, e.g.

List<Integer> bigList = ...
List<List<Integer>> smallerLists = Lists.partition(bigList, 10);

Java: how do I initialize an array size if it's unknown?

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

Get random item from array

echo $items[array_rand($items)];

array_rand()

ssl_error_rx_record_too_long and Apache SSL

In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <VirtualHost 192.168.0.1:443> but the server did not have the 192.168.0.1 address!

HTML forms - input type submit problem with action=URL when URL contains index.aspx

Put the query arguments in hidden input fields:

<form action="http://spufalcons.com/index.aspx">
    <input type="hidden" name="tab" value="gymnastics" />
    <input type="hidden" name="path" value="gym" />
    <input type="submit" value="SPU Gymnastics"/>
</form>

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

Although this may not be the cause of your issue, you'll get the same error if there are two MySQL services running on the same port. You can check on windows by looking at the list of services in the services tab of Task Manager.

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Removing array item by value

The most powerful solution would be using array_filter, which allows you to define your own filtering function.

But some might say it's a bit overkill, in your situation...
A simple foreach loop to go trough the array and remove the item you don't want should be enough.

Something like this, in your case, should probably do the trick :

foreach ($items as $key => $value) {
    if ($value == $id) {
        unset($items[$key]);
        // If you know you only have one line to remove, you can decomment the next line, to stop looping
        //break;
    }
}

java.net.SocketTimeoutException: Read timed out under Tomcat

Here are the basic instructions:-

  1. Locate the "server.xml" file in the "conf" folder beneath Tomcat's base directory (i.e. %CATALINA_HOME%/conf/server.xml).
  2. Open the file in an editor and search for <Connector.
  3. Locate the relevant connector that is timing out - this will typically be the HTTP connector, i.e. the one with protocol="HTTP/1.1".
  4. If a connectionTimeout value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.
  5. Restart Tomcat

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

how to change attribute "hidden" in jquery

$(':checkbox').change(function(){
    $('#delete').removeAttr('hidden');
});

Note, thanks to tip by A.Wolff, you should use removeAttr instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.

The remote server returned an error: (403) Forbidden

Setting:

request.Referer = @"http://www.somesite.com/";

and adding cookies than worked for me

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

Capturing window.onbeforeunload

The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Conda command is not recognized on Windows 10

If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.

Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

Inserting an item in a Tuple

For the case where you are not adding to the end of the tuple

>>> a=(1,2,3,5,6)
>>> a=a[:3]+(4,)+a[3:]
>>> a
(1, 2, 3, 4, 5, 6)
>>> 

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

npm will install dev dependencies when installing from inside a package (if there is a package.json in the current directory). If it is from another location (npm registry, git repo, different location on the filesystem) it only installs the dependencies.

Reading output of a command into an array in Bash

You can use

my_array=( $(<command>) )

to store the output of command <command> into the array my_array.

You can access the length of that array using

my_array_length=${#my_array[@]}

Now the length is stored in my_array_length.

iconv - Detected an illegal character in input string

BE VERY CAREFUL, the problem may come from multibytes encoding and inappropriate PHP functions used...

It was the case for me and it took me a while to figure it out.

For example, I get the a string from MySQL using utf8mb4 (very common now to encode emojis):

$formattedString = strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WILL RETURN THE ERROR 'Detected an illegal character in input string'

The problem does not stand in iconv() but stands in strtolower() in this case.

The appropriate way is to use Multibyte String Functions mb_strtolower() instead of strtolower()

$formattedString = mb_strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WORK FINE

MORE INFO

More examples of this issue are available at this SO answer

PHP Manual on the Multibyte String

How to get base URL in Web API controller?

In .NET Core WebAPI (version 3.0 and above):

var requestUrl = $"{Request.Scheme}://{Request.Host.Value}/";


     

Is it possible to preview stash contents in git?

I'm a fan of gitk's graphical UI to visualize git repos. You can view the last item stashed with:

gitk stash

You can also use view any of your stashed changes (as listed by git stash list). For example:

gitk stash@{2}

In the below screenshot, you can see the stash as a commit in the upper-left, when and where it came from in commit history, the list of files modified on the bottom right, and the line-by-line diff in the lower-left. All while the stash is still tucked away.

gitk viewing a stash

What do pty and tty mean?

A tty is a physical terminal-teletype port on a computer (usually a serial port).

The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.

Teletypewriter
TTY - Teletypewriter 1930s

A pty is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.

enter image description here
PTY - PseudoTeletype

A terminal is simply a computer's user interface that uses text for input and output.


OS Implementations

These use pseudo-teletype ports however, their naming and implementations have diverged a little.

Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts for every new terminal window you open, e.g. /dev/pts/0


macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY naming convention ttys for every new terminal window you open e.g. /dev/ttys002


Microsoft Windows still has the concept of an LPT port for Line Printer Terminals within it's Command Shell for output to a printer.

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

How to add minutes to my Date

There's an error in the pattern of your SimpleDateFormat. it should be

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

Excel "External table is not in the expected format."

This can also be a file that contains images or charts, see this: http://kb.tableausoftware.com/articles/knowledgebase/resolving-error-external-table-is-not-in-expected-format

The recommendation is to save as Excel 2003

DateTime.TryParseExact() rejecting valid formats

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

How to set image width to be 100% and height to be auto in react native?

Solution April 2020:

So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.

To have a truly responsive (i.e. width: 100%, height: auto) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.

Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.

So all we need to do is create a View with width: "100%", then use onLayout to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.

 

Just show me the code...

The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.

JavaScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";

const ResponsiveImage = props => {
  const [containerWidth, setContainerWidth] = useState(0);
  const _onViewLayoutChange = event => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

 

TypeScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import {
  Image,
  ImageSourcePropType,
  LayoutChangeEvent,
  StyleSheet,
  View
} from "react-native";

interface ResponsiveImageProps {
  src: ImageSourcePropType;
  srcWidth: number;
  srcHeight: number;
}

const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
  const [containerWidth, setContainerWidth] = useState<number>(0);
  const _onViewLayoutChange = (event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

How is Docker different from a virtual machine?

The docker documentation (and self-explanation) makes a distinction between "virtual machines" vs. "containers". They have the tendency to interpret and use things in a little bit uncommon ways. They can do that because it is up to them, what do they write in their documentation, and because the terminology for virtualization is not yet really exact.

Fact is what the Docker documentation understands on "containers", is paravirtualization (sometimes "OS-Level virtualization") in the reality, contrarily the hardware virtualization, which is docker not.

Docker is a low quality paravirtualisation solution. The container vs. VM distinction is invented by the docker development, to explain the serious disadvantages of their product.

The reason, why it became so popular, is that they "gave the fire to the ordinary people", i.e. it made possible the simple usage of typically server ( = Linux) environments / software products on Win10 workstations. This is also a reason for us to tolerate their little "nuance". But it does not mean that we should also believe it.

The situation is made yet more cloudy by the fact that docker on Windows hosts used an embedded Linux in HyperV, and its containers have run in that. Thus, docker on Windows uses a combined hardware and paravirtualization solution.

In short, Docker containers are low-quality (para)virtual machines with a huge advantage and a lot of disadvantages.

Chrome hangs after certain amount of data transfered - waiting for available socket

Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.

The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.

As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.

ImportError: No module named mysql.connector using Python2

I was facing the similar issue. My env details - Python 2.7.11 pip 9.0.1 CentOS release 5.11 (Final)

Error on python interpreter -

>>> import mysql.connector
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mysql.connector
>>>

Use pip to search the available module -

 $ pip search mysql-connector | grep --color mysql-connector-python



mysql-connector-python-rf (2.2.2)        - MySQL driver written in Python
mysql-connector-python (2.0.4)           - MySQL driver written in Python

Install the mysql-connector-python-rf -

$ pip install mysql-connector-python-rf

Verify

$ python
Python 2.7.11 (default, Apr 26 2016, 13:18:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>

CSS :not(:last-child):after selector

Your example as written works perfectly in Chrome 11 for me. Perhaps your browser just doesn't support the :not() selector?

You may need to use JavaScript or similar to accomplish this cross-browser. jQuery implements :not() in its selector API.

Visual Studio : short cut Key : Duplicate Line

In Visual Studio 2010 you copy the entire line the cursor is on with CTRL + INSERT then you can use Ctrl + V or SHIFT + INSERT to paste it.

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

How do I specify new lines on Python, when writing on files?

In Python you can just use the new-line character, i.e. \n

Parsing JSON string in Java

Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I was facing the same issue while i was using "jdk-10.0.1_windows-x64_bin" and eclipse-jee-oxygen-3a-win32-x86_64 on Windows 64 bit Operating System.

But Finally i resolved this issue by changing my jdk to "jdk-8u172-windows-x64", Now its working fine. @Thanks

how to implement a pop up dialog box in iOS

Here is C# version in Xamarin.iOS

var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();

CSV parsing in Java - working example..?

i had to use a csv parser about 5 years ago. seems there are at least two csv standards: http://en.wikipedia.org/wiki/Comma-separated_values and what microsoft does in excel.

i found this libaray which eats both: http://ostermiller.org/utils/CSV.html, but afaik, it has no way of inferring what data type the columns were.

Installing a plain plugin jar in Eclipse 3.5

Simplest way - just put in the Eclipse plugins folder. You can start Eclipse with the -clean option to make sure Eclipse cleans its' plugins cache and sees the new plugin.

In general, it is far more recommended to install plugins using proper update sites.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

simply do this..

@Override
public void onBackPressed() {
    //super.onBackPressed();
}

commenting out the //super.onBackPressed(); will do the trick

Delete files in subfolder using batch script

Use powershell inside your bat file

PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse

You can also exclude from removing some specific folder or file:

PowerShell Remove-Item C:/*  -Exclude WINDOWS,autoexec.bat -force -recurse

How to split a string, but also keep the delimiters?

I like the idea of StringTokenizer because it is Enumerable.
But it is also obsolete, and replace by String.split which return a boring String[] (and does not includes the delimiters).

So I implemented a StringTokenizerEx which is an Iterable, and which takes a true regexp to split a string.

A true regexp means it is not a 'Character sequence' repeated to form the delimiter:
'o' will only match 'o', and split 'ooo' into three delimiter, with two empty string inside:

[o], '', [o], '', [o]

But the regexp o+ will return the expected result when splitting "aooob"

[], 'a', [ooo], 'b', []

To use this StringTokenizerEx:

final StringTokenizerEx aStringTokenizerEx = new StringTokenizerEx("boo:and:foo", "o+");
final String firstDelimiter = aStringTokenizerEx.getDelimiter();
for(String aString: aStringTokenizerEx )
{
    // uses the split String detected and memorized in 'aString'
    final nextDelimiter = aStringTokenizerEx.getDelimiter();
}

The code of this class is available at DZone Snippets.

As usual for a code-challenge response (one self-contained class with test cases included), copy-paste it (in a 'src/test' directory) and run it. Its main() method illustrates the different usages.


Note: (late 2009 edit)

The article Final Thoughts: Java Puzzler: Splitting Hairs does a good work explaning the bizarre behavior in String.split().
Josh Bloch even commented in response to that article:

Yes, this is a pain. FWIW, it was done for a very good reason: compatibility with Perl.
The guy who did it is Mike "madbot" McCloskey, who now works with us at Google. Mike made sure that Java's regular expressions passed virtually every one of the 30K Perl regular expression tests (and ran faster).

The Google common-library Guava contains also a Splitter which is:

  • simpler to use
  • maintained by Google (and not by you)

So it may worth being checked out. From their initial rough documentation (pdf):

JDK has this:

String[] pieces = "foo.bar".split("\\.");

It's fine to use this if you want exactly what it does: - regular expression - result as an array - its way of handling empty pieces

Mini-puzzler: ",a,,b,".split(",") returns...

(a) "", "a", "", "b", ""
(b) null, "a", null, "b", null
(c) "a", null, "b"
(d) "a", "b"
(e) None of the above

Answer: (e) None of the above.

",a,,b,".split(",")
returns
"", "a", "", "b"

Only trailing empties are skipped! (Who knows the workaround to prevent the skipping? It's a fun one...)

In any case, our Splitter is simply more flexible: The default behavior is simplistic:

Splitter.on(',').split(" foo, ,bar, quux,")
--> [" foo", " ", "bar", " quux", ""]

If you want extra features, ask for them!

Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.split(" foo, ,bar, quux,")
--> ["foo", "bar", "quux"]

Order of config methods doesn't matter -- during splitting, trimming happens before checking for empties.

Java array assignment (multiple values)

int a[] = { 2, 6, 8, 5, 4, 3 }; 
int b[] = { 2, 3, 4, 7 };

if you take float number then you take float and it's your choice

this is very good way to show array elements.

What is copy-on-write?

I found this good article about zval in PHP, which mentioned COW too:

Copy On Write (abbreviated as ‘COW’) is a trick designed to save memory. It is used more generally in software engineering. It means that PHP will copy the memory (or allocate new memory region) when you write to a symbol, if this one was already pointing to a zval.

Simple line plots using seaborn

Yes, you can do the same in Seaborn directly. This is done with tsplot() which allows either a single array as input, or two arrays where the other is 'time' i.e. x-axis.

import seaborn as sns

data =  [1,5,3,2,6] * 20
time = range(100)

sns.tsplot(data, time)

enter image description here

How do I access Configuration in any class in ASP.NET Core?

I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

  1. My startup class is as default
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
  1. My appsettings.json is like this
{
  "CompanySettings": {
    "name": "Fake Co"
  }
}

  1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;

public class EmployeeController 
{
    private IConfiguration _configuration;
    public EmployeeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
    var companyName = configuration.GetValue<string>("CompanySettings:name");
    // companyName = "Fake Co"
}

alternative to "!is.null()" in R

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
{
  do whatever
}

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Post Django version 1.9, on_delete became a required argument, i.e. from Django 2.0.

In older versions, it defaults to CASCADE.

So, if you want to replicate the functionality that you used in earlier versions. Use the following argument.

categorie = models.ForeignKey('Categorie', on_delete = models.CASCADE)

This will have the same effect as that was in earlier versions, without specifying it explicitly.

Official Documentation on other arguments that go with on_delete

Is it possible to start activity through adb shell?

eg:

MyPackageName is com.example.demo

MyActivityName is com.example.test.MainActivity

adb shell am start -n com.example.demo/com.example.test.MainActivity

how to find host name from IP with out login to the host

You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

$ host 192.168.0.10
server10 has address 192.168.0.10

How do you Make A Repeat-Until Loop in C++?

When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while loop:

while(!cond) { ... }

If you need it at the end, use a do ... while loop and negate the condition:

do { ... } while(!cond);

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

Materialize CSS - Select Doesn't Seem to Render

Just to follow up on this since the top answer recommends not using materializecss... in the current version of materialize you no longer need to initialize selects.

What version of MongoDB is installed on Ubuntu

In the terminal just write : $ mongod --version

Get Row Index on Asp.net Rowcommand event

this is answer for your question.

GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

int RowIndex = gvr.RowIndex; 

How do I unlock a SQLite database?

Should be a database's internal problem...
For me it has been manifested after trying to browse database with "SQLite manager"...
So, if you can't find another process connect to database and you just can't fix it, just try this radical solution:

  1. Provide to export your tables (You can use "SQLite manager" on Firefox)
  2. If the migration alter your database scheme delete the last failed migration
  3. Rename your "database.sqlite" file
  4. Execute "rake db:migrate" to make a new working database
  5. Provide to give the right permissions to database for table's importing
  6. Import your backed up tables
  7. Write the new migration
  8. Execute it with "rake db:migrate"

Pretty-Printing JSON with PHP

Have color full output: Tiny Solution

Code:

$s = '{"access": {"token": {"issued_at": "2008-08-16T14:10:31.309353", "expires": "2008-08-17T14:10:31Z", "id": "MIICQgYJKoZIhvcIegeyJpc3N1ZWRfYXQiOiAi"}, "serviceCatalog": [], "user": {"username": "ajay", "roles_links": [], "id": "16452ca89", "roles": [], "name": "ajay"}}}';

$crl = 0;
$ss = false;
echo "<pre>";
for($c=0; $c<strlen($s); $c++)
{
    if ( $s[$c] == '}' || $s[$c] == ']' )
    {
        $crl--;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && ($s[$c-1] == ',' || $s[$c-2] == ',') )
    {
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
    if ( $s[$c] == '"' && !$ss )
    {
        if ( $s[$c-1] == ':' || $s[$c-2] == ':' )
            echo '<span style="color:#0000ff;">';
        else
            echo '<span style="color:#ff0000;">';
    }
    echo $s[$c];
    if ( $s[$c] == '"' && $ss )
        echo '</span>';
    if ( $s[$c] == '"' )
          $ss = !$ss;
    if ( $s[$c] == '{' || $s[$c] == '[' )
    {
        $crl++;
        echo "\n";
        echo str_repeat(' ', ($crl*2));
    }
}
echo $s[$c];

Repeat rows of a data.frame

df <- data.frame(a = 1:2, b = letters[1:2]) 
df[rep(seq_len(nrow(df)), each = 2), ]

How to change date format using jQuery?

You can use date.js to achieve this:

var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');

Alternatively, you can do it natively like this:

_x000D_
_x000D_
var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_
_x000D_
console.log(newDate);
_x000D_
_x000D_
_x000D_

Convert Array to Object

For ES2016, spread operator for objects. Note: This is after ES6 and so transpiler will need to be adjusted.

_x000D_
_x000D_
const arr = ['a', 'b', 'c'];_x000D_
const obj = {...arr}; // -> {0: "a", 1: "b", 2: "c"} 
_x000D_
_x000D_
_x000D_

How to open a new tab using Selenium WebDriver

The below code will open the link in a new window:

String selectAll = Keys.chord(Keys.SHIFT, Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);

Set JavaScript variable = null, or leave undefined?

The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.

if(a === null) {

}

...is not the same as:

if(a === undefined) {

}

That said, a == null && a == undefined will return true.

Fiddle

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The second result set have only one column but it should have 3 columns for it to be contented to the first result set

(columns must match when you use UNION)

Try to add ID as first column and PartOf_LOC_id to your result set, so you can do the UNION.

;
WITH    q AS ( SELECT   ID ,
                    Location ,
                    PartOf_LOC_id
           FROM     tblLocation t
           WHERE    t.ID = 1 -- 1 represents an example
           UNION ALL
           SELECT   t.ID ,
                    parent.Location + '>' + t.Location ,
                    t.PartOf_LOC_id
           FROM     tblLocation t
                    INNER JOIN q parent ON parent.ID = t.LOC_PartOf_ID
         )
SELECT  *
FROM    q

How can I specify my .keystore file with Spring Boot and Tomcat?

Starting with Spring Boot 1.2, you can configure SSL using application.properties or application.yml. Here's an example for application.properties:

server.port = 8443
server.ssl.key-store = classpath:keystore.jks
server.ssl.key-store-password = secret
server.ssl.key-password = another-secret

Same thing with application.yml:

server:
  port: 8443
  ssl:
    key-store: classpath:keystore.jks
    key-store-password: secret
    key-password: another-secret

Here's a link to the current reference documentation.

Android: combining text & image on a Button or ImageButton

<Button android:id="@+id/myButton" 
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:text="Image Button"
    android:drawableTop="@drawable/myimage"         
    />  

Or you can programmatically:

Drawable drawable = getResources.getDrawable(R.drawable.myimage);
drawable.setBounds(0, 0, 60, 60);
myButton.setCompoundDrawables(null, drawable, null, null);//to the Top of the Button

Javascript Regular Expression Remove Spaces

Remove all spaces in string

// Remove only spaces
`
Text with spaces 1 1     1     1 
and some
breaklines

`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines

"

// Remove spaces and breaklines
`
Text with spaces 1 1     1     1
and some
breaklines

`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"

How do you add multi-line text to a UIButton?

I had an issue with auto-layout, after enabling multi-line the result was like this:
enter image description here
so the titleLabel size doesn't affect the button size
I've added Constraints based on contentEdgeInsets (in this case contentEdgeInsets was (10, 10, 10, 10)
after calling makeMultiLineSupport():
enter image description here
hope it helps you (swift 5.0):

extension UIButton {

    func makeMultiLineSupport() {
        guard let titleLabel = titleLabel else {
            return
        }
        titleLabel.numberOfLines = 0
        titleLabel.setContentHuggingPriority(.required, for: .vertical)
        titleLabel.setContentHuggingPriority(.required, for: .horizontal)
        addConstraints([
            .init(item: titleLabel,
                  attribute: .top,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .top,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.top),
            .init(item: titleLabel,
                  attribute: .bottom,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .bottom,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.bottom),
            .init(item: titleLabel,
                  attribute: .left,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .left,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.left),
            .init(item: titleLabel,
                  attribute: .right,
                  relatedBy: .greaterThanOrEqual,
                  toItem: self,
                  attribute: .right,
                  multiplier: 1.0,
                  constant: contentEdgeInsets.right)
            ])
    }

}

Laravel Eloquent LEFT JOIN WHERE NULL

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);

Git: how to reverse-merge a commit?

If I understand you correctly, you're talking about doing a

svn merge -rn:n-1

to back out of an earlier commit, in which case, you're probably looking for

git revert

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

How to overcome TypeError: unhashable type: 'list'

    python 3.2

    with open("d://test.txt") as f:
              k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
              d={}
              for i,_,v in k:
                      d.setdefault(i,[]).append(v)

How to change the locale in chrome browser

Open chrome, go to chrome://settings/languages

On the left, you should see a list of languages. Use mouse to drag the language you want to the top, that will change the order for the values in Accept-language of requests.

If you still don't see the language you prefer, it may be cookies. Go to cookies and clean it up you should be good.

Is there Java HashMap equivalent in PHP?

HashMap that also works with keys other than strings and integers with O(1) read complexity (depending on quality of your own hash-function).

You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:

class IEqualityComparer {
    public function equals($x, $y) {
        throw new Exception("Not implemented!");
    }
    public function getHashCode($obj) {
        throw new Exception("Not implemented!");
    }
}

class HashMap {
    private $map = array();
    private $comparer;

    public function __construct(IEqualityComparer $keyComparer) {
        $this->comparer = $keyComparer;
    }

    public function has($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                return true;
            }
        }

        return false;
    }

    public function get($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                return $item['value'];
            }
        }

        return false;
    }

    public function del($key) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            return false;
        }

        foreach ($this->map[$hash] as $index => $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                unset($this->map[$hash][$index]);
                if (count($this->map[$hash]) == 0)
                    unset($this->map[$hash]);

                return true;
            }
        }

        return false;
    }

    public function put($key, $value) {
        $hash = $this->comparer->getHashCode($key);

        if (!isset($this->map[$hash])) {
            $this->map[$hash] = array();
        }

        $newItem = array('key' => $key, 'value' => $value);        

        foreach ($this->map[$hash] as $index => $item) {
            if ($this->comparer->equals($item['key'], $key)) {
                $this->map[$hash][$index] = $newItem;
                return;
            }
        }

        $this->map[$hash][] = $newItem;
    }
}

For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)

Here is an example:

class IntArrayComparer extends IEqualityComparer {
    public function equals($x, $y) {
        if (count($x) !== count($y))
            return false;

        foreach ($x as $key => $value) {
            if (!isset($y[$key]) || $y[$key] !== $value)
                return false;
        }

        return true;
    }

    public function getHashCode($obj) {
        $hash = 0;
        foreach ($obj as $key => $value)
            $hash ^= $key ^ $value;

        return $hash;
    }
}

$hashmap = new HashMap(new IntArrayComparer());

for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
        $hashmap->put(array($i, $j), $i * 10 + $j);
    }
}

echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";

echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";

$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";

Which gives as output:

37
51
true
false
false
false
false

PadLeft function in T-SQL

I created a function:

CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255) 
AS 
BEGIN
    DECLARE @strInt varchar(255)

    SET @strInt = CAST(@int as varchar(255))
    RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;

Use: select dbo.fnPadLeft(123, 10)

Returns: 0000000123

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

CSS: fixed position on x-axis but not y?

Yes, You actually can do that only by using CSS...

body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }

Tell me if it works

How to detect control+click in Javascript from an onclick div attribute?

Try this:

var control = false;
$(document).on('keyup keydown', function(e) {
  control = e.ctrlKey;
});

$('div#1').on('click', function() {
  if (control) {
    // control-click
  } else {
    // single-click
  }
});

And the right-click triggers a contextmenu event, so:

$('div#1').on('contextmenu', function() {
  // right-click handler
})

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

How do I install Python packages in Google's Colab?

A better, more modern, answer to this question is to use the %pip magic, like:

%pip install scipy

That will automatically use the correct Python version. Using !pip might be tied to a different version of Python, and then you might not find the package after installing it.

And in colab, the magic gives a nice message and button if it detects that you need to restart the runtime if pip updated a packaging you have already imported.

BTW, there is also a %conda magic for doing the same with conda.

How can I add a box-shadow on one side of an element?

This site helped me: https://gist.github.com/ocean90/1268328 (Note that on that site the left and right are reversed as of the date of this post... but they work as expected). They are corrected in the code below.

<!DOCTYPE html>
<html>
    <head>
        <title>Box Shadow</title>

        <style>
            .box {
                height: 150px;
                width: 300px;
                margin: 20px;
                border: 1px solid #ccc;
            }

            .top {
                box-shadow: 0 -5px 5px -5px #333;
            }

            .right {
                box-shadow: 5px 0 5px -5px #333;
            }

            .bottom {
                box-shadow: 0 5px 5px -5px #333;
            }

            .left {
                box-shadow: -5px 0 5px -5px #333;
            }

            .all {
                box-shadow: 0 0 5px #333;
            }
        </style>
    </head>
    <body>
        <div class="box top"></div>
        <div class="box right"></div>
        <div class="box bottom"></div>
        <div class="box left"></div>
        <div class="box all"></div>
    </body>
</html>

What are abstract classes and abstract methods?

ABSTRACT CLASSES AND ABSTARCT METHODS FULL DESCRIPTION GO THROUGH IT

abstract method do not have body.A well defined method can't be declared abstract.

A class which has abstract method must be declared as abstract.

Abstract class can't be instantiated.

iPhone viewWillAppear not firing

I use this code for push and pop view controllers:

push:

[self.navigationController pushViewController:detaiViewController animated:YES];
[detailNewsViewController viewWillAppear:YES];

pop:

[[self.navigationController popViewControllerAnimated:YES] viewWillAppear:YES];

.. and it works fine for me.

How do I find the length of an array?

This is pretty much old and legendary question and there are already many amazing answers out there. But with time there are new functionalities being added to the languages, so we need to keep on updating things as per new features available.

I just noticed any one hasn't mentioned about C++20 yet. So thought to write answer.

C++20

In C++20, there is a new better way added to the standard library for finding the length of array i.e. std:ssize(). This function returns a signed value.

#include <iostream>

int main() {
    int arr[] = {1, 2, 3};
    std::cout << std::ssize(arr);
    return 0;
}

C++17

In C++17 there was a better way (at that time) for the same which is std::size() defined in iterator.

#include <iostream>
#include <iterator> // required for std::size

int main(){
    int arr[] = {1, 2, 3};
    std::cout << "Size is " << std::size(arr);
    return 0;
}

P.S. This method works for vector as well.

Old

This traditional approach is already mentioned in many other answers.

#include <iostream>

int main() {
    int array[] = { 1, 2, 3 };
    std::cout << sizeof(array) / sizeof(array[0]);
    return 0;
}

Just FYI, if you wonder why this approach doesn't work when array is passed to another function. The reason is,

An array is not passed by value in C++, instead the pointer to array is passed. As in some cases passing the whole arrays can be expensive operation. You can test this by passing the array to some function and make some changes to array there and then print the array in main again. You'll get updated results.

And as you would already know, the sizeof() function gives the number of bytes, so in other function it'll return the number of bytes allocated for the pointer rather than the whole array. So this approach doesn't work.

But I'm sure you can find a good way to do this, as per your requirement.

Happy Coding.

What is the scope of variables in JavaScript?

ECMAScript 6 introduced the let and const keywords. These keywords can be used in place of the var keyword. Contrary to the var keyword, the let and const keywords support the declaration of local scope inside block statements.

var x = 10
let y = 10
const z = 10
{
  x = 20
  let y = 20
  const z = 20
  {
    x = 30
    // x is in the global scope because of the 'var' keyword
    let y = 30
    // y is in the local scope because of the 'let' keyword
    const z = 30
    // z is in the local scope because of the 'const' keyword
    console.log(x) // 30
    console.log(y) // 30
    console.log(z) // 30
  }
  console.log(x) // 30
  console.log(y) // 20
  console.log(z) // 20
}

console.log(x) // 30
console.log(y) // 10
console.log(z) // 10

Postgresql -bash: psql: command not found

In case you are running it on Fedora or CentOS, this is what worked for me (PostgreSQL 9.6):

In terminal:

$ sudo visudo -f /etc/sudoers

modify the following text from:

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

to

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/pgsql-9.6/bin

exit, then:

$ printenv PATH

$ sudo su postgres

$ psql

To exit postgreSQL terminal, you need to digit:

$ \q

Source: https://serverfault.com/questions/541847/why-doesnt-sudo-know-where-psql-is#comment623883_541880

Traverse all the Nodes of a JSON Object Tree with JavaScript

My Script:

op_needed = [];
callback_func = function(val) {
  var i, j, len;
  results = [];
  for (j = 0, len = val.length; j < len; j++) {
    i = val[j];
    if (i['children'].length !== 0) {
      call_func(i['children']);
    } else {
      op_needed.push(i['rel_path']);
    }
  }
  return op_needed;
};

Input JSON:

[
    {
        "id": null, 
        "name": "output",   
        "asset_type_assoc": [], 
        "rel_path": "output",
        "children": [
            {
                "id": null, 
                "name": "output",   
                "asset_type_assoc": [], 
                "rel_path": "output/f1",
                "children": [
                    {
                        "id": null, 
                        "name": "v#",
                        "asset_type_assoc": [], 
                        "rel_path": "output/f1/ver",
                        "children": []
                    }
                ]
            }
       ]
   }
]

Function Call:

callback_func(inp_json);

Output as per my Need:

["output/f1/ver"]

What are the differences between JSON and JSONP?

JSONP allows you to specify a callback function that is passed your JSON object. This allows you to bypass the same origin policy and load JSON from an external server into the JavaScript on your webpage.

How do I get a YouTube video thumbnail from the YouTube API?

This is my client-side-only no-API-key-required solution.

YouTube.parse('https://www.youtube.com/watch?v=P3DGwyl0mJQ').then(_ => console.log(_))

The code:

import { parseURL, parseQueryString } from './url'
import { getImageSize } from './image'

const PICTURE_SIZE_NAMES = [
    // 1280 x 720.
    // HD aspect ratio.
    'maxresdefault',
    // 629 x 472.
    // non-HD aspect ratio.
    'sddefault',
    // For really old videos not having `maxresdefault`/`sddefault`.
    'hqdefault'
]

// - Supported YouTube URL formats:
//   - http://www.youtube.com/watch?v=My2FRPA3Gf8
//   - http://youtu.be/My2FRPA3Gf8
export default
{
    parse: async function(url)
    {
        // Get video ID.
        let id
        const location = parseURL(url)
        if (location.hostname === 'www.youtube.com') {
            if (location.search) {
                const query = parseQueryString(location.search.slice('/'.length))
                id = query.v
            }
        } else if (location.hostname === 'youtu.be') {
            id = location.pathname.slice('/'.length)
        }

        if (id) {
            return {
                source: {
                    provider: 'YouTube',
                    id
                },
                picture: await this.getPicture(id)
            }
        }
    },

    getPicture: async (id) => {
        for (const sizeName of PICTURE_SIZE_NAMES) {
            try {
                const url = getPictureSizeURL(id, sizeName)
                return {
                    type: 'image/jpeg',
                    sizes: [{
                        url,
                        ...(await getImageSize(url))
                    }]
                }
            } catch (error) {
                console.error(error)
            }
        }
        throw new Error(`No picture found for YouTube video ${id}`)
    },

    getEmbeddedVideoURL(id, options = {}) {
        return `https://www.youtube.com/embed/${id}`
    }
}

const getPictureSizeURL = (id, sizeName) => `https://img.youtube.com/vi/${id}/${sizeName}.jpg`

Utility image.js:

// Gets image size.
// Returns a `Promise`.
function getImageSize(url)
{
    return new Promise((resolve, reject) =>
    {
        const image = new Image()
        image.onload = () => resolve({ width: image.width, height: image.height })
        image.onerror = reject
        image.src = url
    })
}

Utility url.js:

// Only on client side.
export function parseURL(url)
{
    const link = document.createElement('a')
    link.href = url
    return link
}

export function parseQueryString(queryString)
{
    return queryString.split('&').reduce((query, part) =>
    {
        const [key, value] = part.split('=')
        query[decodeURIComponent(key)] = decodeURIComponent(value)
        return query
    },
    {})
}

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

A pretty surefire way is to implement a unique ID into the post and cache it in the

<input type='hidden' name='post_id' value='".createPassword(64)."'>

Then in your code do this:

if( ($_SESSION['post_id'] != $_POST['post_id']) )
{
    $_SESSION['post_id'] = $_POST['post_id'];
    //do post stuff
} else {
    //normal display
}

function createPassword($length)
{
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= ($length - 1)) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}

How do I pass an object from one activity to another on Android?

Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable() method and pass your object between activities within intent.

The Photostream application uses this approach and may be used as a reference.

How to identify platform/compiler from preprocessor macros?

If you're writing C++, I can't recommend using the Boost libraries strongly enough.

The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.

#include <boost/predef.h>

// ...

#if BOOST_OS_WINDOWS

#elif BOOST_OS_LINUX

#elif BOOST_OS_MACOS

#endif

SQL Server - In clause with a declared variable

First, create a quick function that will split a delimited list of values into a table, like this:

CREATE FUNCTION dbo.udf_SplitVariable
(
    @List varchar(8000),
    @SplitOn varchar(5) = ','
)

RETURNS @RtnValue TABLE
(
    Id INT IDENTITY(1,1),
    Value VARCHAR(8000)
)

AS
BEGIN

--Account for ticks
SET @List = (REPLACE(@List, '''', ''))

--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
    SET @List = ''
END

--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN

    INSERT INTO @RtnValue (value)
    SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))  

    SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))

END

INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))

RETURN

END 

Then call the function like this...

SELECT * 
FROM A
LEFT OUTER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
WHERE f.Id IS NULL

This has worked really well on our project...

Of course, the opposite could also be done, if that was the case (though not your question).

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value

And this really comes in handy when dealing with reports that have an optional multi-select parameter list. If the parameter is NULL you want all values selected, but if it has one or more values you want the report data filtered on those values. Then use SQL like this:

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value OR @ExcludeList IS NULL

This way, if @ExcludeList is a NULL value, the OR clause in the join becomes a switch that turns off filtering on this value. Very handy...

What is the equivalent of Java's System.out.println() in Javascript?

I'm using Chrome and print() literally prints the text on paper. This is what works for me:

document.write("My message");

Force "portrait" orientation mode

Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges as noted below.

Example:

<activity
   android:screenOrientation="portrait"
   android:configChanges="orientation|keyboardHidden">
</activity>

This is applied in the manifest file AndroidManifest.xml.

Angular: How to update queryParams without changing route

In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.

  let urlTree = this.router.parseUrl(this.router.url);
  urlTree.queryParams['newParamKey'] = 'newValue';

  this.router.navigateByUrl(urlTree); 

The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.

import { Router } from '@angular/router';

constructor(private router: Router) { }

appendAQueryParam() {

  const urlTree = this.router.createUrlTree([], {
    queryParams: { newParamKey: 'newValue' },
    queryParamsHandling: "merge",
    preserveFragment: true });

  this.router.navigateByUrl(urlTree); 
}

In order to remove a query parameter this way you can set it to undefined or null.

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

Difference between acceptance test and functional test?

In my view the main difference is who says if the tests succeed or fail.

A functional test tests that the system meets predefined requirements. It is carried out and checked by the people responsible for developing the system.

An acceptance test is signed off by the users. Ideally the users will say what they want to test but in practice it is likely to be a sunset of a functional test as users don't invest enough time. Note that this view is from the business users I deal with other sets of users e.g. aviation and other safety critical might well not have this difference,

Finding the mode of a list

def mode(inp_list):
    sort_list = sorted(inp_list)
    dict1 = {}
    for i in sort_list:        
            count = sort_list.count(i)
            if i not in dict1.keys():
                dict1[i] = count

    maximum = 0 #no. of occurences
    max_key = -1 #element having the most occurences

    for key in dict1:
        if(dict1[key]>maximum):
            maximum = dict1[key]
            max_key = key 
        elif(dict1[key]==maximum):
            if(key<max_key):
                maximum = dict1[key]
                max_key = key

    return max_key

How to force Selenium WebDriver to click on element which is not currently visible?

Or you may use Selenium Action Class to simulate user interaction -- For example

    WebDriver = new FirefoxDriver();

    WebElement menu = driver.findElement(By.xpath("")); // the triger event element

    Actions build = new Actions(driver); // heare you state ActionBuider
    build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
    WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
    m2m.click();

how to run two commands in sudo?

The -s option didn't work for me, -i did.

Here is an example of how I could update the log size from my bash:

sudo -u [user] -i -- sh -c 'db2 connect to [database name];db2 update db cfg for [database name] using logsecond 20;db2 update db cfg for [database name] using logprimary 20;'

Read next word in java

you're better off reading a line and then doing a split.

File file = new File("path/to/file");
String words[]; // I miss C
String line;
HashMap<String, String> hm = new HashMap<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")))
{
    while((line = br.readLine() != null)){
        words = line.split("\\s");
        if (hm.containsKey(words[0])){
                System.out.println("Found duplicate ... handle logic");
        }
        hm.put(words[0],words[1]); //if index==0 is ur key
    }

} catch (FileNotFoundException e) {
        e.printStackTrace();
} catch (IOException e) {
        e.printStackTrace();
}

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

Uninstall all installed gems, in OSX?

Rubygems >= 2.1.0

gem uninstall -aIx

If Terminal returns below error

ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

Then write above command as below

sudo gem uninstall -aIx

And enter your mac os account password Done!!

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

How can I mock an ES6 module import using Jest?

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});

Best way to check for null values in Java?

Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.

Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.

Method 2 is just making it more complicated than it needs to be.

Method 1 is just method 4 with an extra line of code.

Take a screenshot via a Python script on Linux

Just for completeness: Xlib - But it's somewhat slow when capturing the whole screen:

from Xlib import display, X
import Image #PIL

W,H = 200,200
dsp = display.Display()
try:
    root = dsp.screen().root
    raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)
    image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")
    image.show()
finally:
    dsp.close()

One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.


Edit: We can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:

#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>
//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c

void getScreen(const int, const int, const int, const int, unsigned char *);
void getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) 
{
   Display *display = XOpenDisplay(NULL);
   Window root = DefaultRootWindow(display);

   XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);

   unsigned long red_mask   = image->red_mask;
   unsigned long green_mask = image->green_mask;
   unsigned long blue_mask  = image->blue_mask;
   int x, y;
   int ii = 0;
   for (y = 0; y < H; y++) {
       for (x = 0; x < W; x++) {
         unsigned long pixel = XGetPixel(image,x,y);
         unsigned char blue  = (pixel & blue_mask);
         unsigned char green = (pixel & green_mask) >> 8;
         unsigned char red   = (pixel & red_mask) >> 16;

         data[ii + 2] = blue;
         data[ii + 1] = green;
         data[ii + 0] = red;
         ii += 3;
      }
   }
   XDestroyImage(image);
   XDestroyWindow(display, root);
   XCloseDisplay(display);
}

And then the python-file:

import ctypes
import os
from PIL import Image

LibName = 'prtscn.so'
AbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName
grab = ctypes.CDLL(AbsLibPath)

def grab_screen(x1,y1,x2,y2):
    w, h = x2-x1, y2-y1
    size = w * h
    objlength = size * 3

    grab.getScreen.argtypes = []
    result = (ctypes.c_ubyte*objlength)()

    grab.getScreen(x1,y1, w, h, result)
    return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)
    
if __name__ == '__main__':
  im = grab_screen(0,0,1440,900)
  im.show()

What does flex: 1 mean?

flex: 1 means the following:

flex-grow : 1;    ? The div will grow in same proportion as the window-size       
flex-shrink : 1;  ? The div will shrink in same proportion as the window-size 
flex-basis : 0;   ? The div does not have a starting value as such and will 
                     take up screen as per the screen size available for
                     e.g:- if 3 divs are in the wrapper then each div will take 33%.

Access: Move to next record until EOF

If you want cmd buttons that loop through the form's records, try adding this code to your cmdNext_Click and cmdPrevious_Click VBA. I have found it works well and copes with BOF / EOF issues:

On Error Resume Next

DoCmd.GoToRecord , , acNext

On Error Goto 0


On Error Resume Next

DoCmd.GoToRecord , , acPrevious

On Error Goto 0

Good luck! PT

Undefined symbols for architecture armv7

I give you more suggestions that you can check when other common suggestions are not help.

If you link with other project(libxxx.a) you might sometimes meet strange problem which you can find the symbol with tools like nm but they just can not find the symbols in ld. Then you should check if the two projects are built in the same flags, some of them may affect the binary format.

  1. check c++ compiler.
  2. check c++ dialect setting.
  3. check c++ runtime type support. (-frtti/-fnortti)
  4. check if there is .a with the same name appears elsewhere, could be beyond the wanted file in the link path list. remove them.

Listing all extras of an Intent

I wanted a way to output the contents of an intent to the log, and to be able to read it easily, so here's what I came up with. I've created a LogUtil class, and then took the dumpIntent() method @Pratik created, and modified it a bit. Here's what it all looks like:

public class LogUtil {

    private static final String TAG = "IntentDump";

    public static void dumpIntent(Intent i){
        Bundle bundle = i.getExtras();
        if (bundle != null) {
            Set<String> keys = bundle.keySet();

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("IntentDump \n\r");
            stringBuilder.append("-------------------------------------------------------------\n\r");

            for (String key : keys) {
                stringBuilder.append(key).append("=").append(bundle.get(key)).append("\n\r");
            }

            stringBuilder.append("-------------------------------------------------------------\n\r");
            Log.i(TAG, stringBuilder.toString());
        }
    }
}

Hope this helps someone!

iPhone keyboard, Done button and resignFirstResponder

From the documentation (any version):

It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.

So, you have to send resignFirstResponder somehow. But there is a possibility that textfield loses focus another way during processing of textFieldShouldReturn: message. This also will cause keyboard to disappear.

Show and hide a View with a slide up/down animation

Kotlin

Based on Suragch's answer, here is an elegant way using View extension:

fun View.slideUp(duration: Int = 500) {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, this.height.toFloat(), 0f)
    animate.duration = duration.toLong()
    animate.fillAfter = true
    this.startAnimation(animate)
}

fun View.slideDown(duration: Int = 500) {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, 0f, this.height.toFloat())
    animate.duration = duration.toLong()
    animate.fillAfter = true
    this.startAnimation(animate)
}

And then wherever you want to use it, you just need myView.slideUp() or myView.slideDown()

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) 
{
  . . .
  . . .
}

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

When you pass props to super, the props get assigned to this. Take a look at the following scenario:

constructor(props) {
    super();
    console.log(this.props) //undefined
}

How ever when you do :

constructor(props) {
    super(props);
    console.log(this.props) //props will get logged.
}

Jquery validation plugin - TypeError: $(...).validate is not a function

for me, the problem was from require('jquery-validation') i added in the begging of that js file which Validate method used which is necessary as an npm module

unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes

so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before

How to recursively find and list the latest modified files in a directory with subdirectories and times

You may give the printf command of find a try

%Ak File's last access time in the format specified by k, which is either @' or a directive for the C strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.

403 - Forbidden: Access is denied. ASP.Net MVC

In addition to the answers above, you may also get that error when you have Windows Authenticaton set and :

  • IIS is pointing to an empty folder.
  • You do not have a default document set.

How and where to use ::ng-deep?

Usually /deep/ “shadow-piercing” combinator can be used to force a style down to child components. This selector had an alias >>> and now has another one called ::ng-deep.

since /deep/ combinator has been deprecated, it is recommended to use ::ng-deep

For example:

<div class="overview tab-pane" id="overview" role="tabpanel" [innerHTML]="project?.getContent( 'DETAILS')"></div>

and css

.overview {
    ::ng-deep {
        p {
            &:last-child {
                margin-bottom: 0;
            }
        }
    }
}

it will be applied to child components

How to change the port of Tomcat from 8080 to 80?

Don't forget to edit the file. Open file /etc/default/tomcat7 and change

#AUTHBIND=no

to

AUTHBIND=yes

then restart.

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

data.frame Group By column

I would recommend having a look at the plyr package. It might not be as fast as data.table or other packages, but it is quite instructive, especially when starting with R and having to do some data manipulation.

> DF <- data.frame(A = c("1", "1", "2", "3", "3"), B = c(2, 3, 3, 5, 6))
> library(plyr)
> DF.sum <- ddply(DF, c("A"), summarize, B = sum(B))
> DF.sum
  A  B
1 1  5
2 2  3
3 3 11

How do I return an int from EditText? (Android)

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

Leave menu bar fixed on top when scrolled

$(window).scroll(function () {

        var ControlDivTop = $('#cs_controlDivFix');

        $(window).scroll(function () {
            if ($(this).scrollTop() > 50) {
               ControlDivTop.stop().animate({ 'top': ($(this).scrollTop() - 62) + "px" }, 600);
            } else {
              ControlDivTop.stop().animate({ 'top': ($(this).scrollTop()) + "px" },600);
            }
        });
    });

Possible to iterate backwards through a foreach?

Before using foreach for iteration, reverse the list by the reverse method:

    myList.Reverse();
    foreach( List listItem in myList)
    {
       Console.WriteLine(listItem);
    }

Using Rsync include and exclude options to include directory and file by pattern

Add -m to the recommended answer above to prune empty directories.

How to get the integer value of day of week

The correct answer, is indeed the correct answer to get the int value.

But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.

if (yourDateTimeObject.DayOfWeek == DayOfWeek.Sunday)
{
    // You can easily see you're checking for sunday, and not just "0"
}

multiple where condition codeigniter

you can use both use array like :

$array = array('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE' );

and direct assign like:

$this->db->where('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE');

I wish help you.

Is it possible to hide/encode/encrypt php source code and let others have the system?

You could just split the frontend and backend. The frontend is hosted on the customers server with an API that makes calls to the backend on your server. This keeps all of the proprietary code proprietary and forces users to sign up / pay for subscriptions.

Docker can't connect to docker daemon

You can use the command

sudo service docker stop && sudo service docker start

to simply start it.

Best Practice to Use HttpClient in Multithreaded Environment

My reading of the docs is that HttpConnection itself is not treated as thread safe, and hence MultiThreadedHttpConnectionManager provides a reusable pool of HttpConnections, you have a single MultiThreadedHttpConnectionManager shared by all threads and initialised exactly once. So you need a couple of small refinements to option A.

MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManag

Then each thread should be using the sequence for every request, getting a conection from the pool and putting it back on completion of its work - using a finally block may be good. You should also code for the possibility that the pool has no available connections and process the timeout exception.

HttpConnection connection = null
try {
    connection = connman.getConnectionWithTimeout(
                        HostConfiguration hostConfiguration, long timeout) 
    // work
} catch (/*etc*/) {/*etc*/} finally{
    if ( connection != null )
        connman.releaseConnection(connection);
}

As you are using a pool of connections you won't actually be closing the connections and so this should not hit the TIME_WAIT problem. This approach does assuume that each thread doesn't hang on to the connection for long. Note that conman itself is left open.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

What is the difference between declarative and imperative paradigm in programming?

I liked an explanation from a Cambridge course + their examples:

  • Declarative - specify what to do, not how to do it
    • E.g.: HTML describes what should appear on a web page, not how it should be drawn on the screen
  • Imperative - specify both what and how
    • int x; - what (declarative)
    • x=x+1; - how

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

Downloading all maven dependencies to a directory NOT in repository?

I found the next command

mvn dependency:copy-dependencies -Dclassifier=sources

here maven.apache.org

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

How do I uniquely identify computers visiting my web site?

My post might not be a solution, but I can provide an example, where this feature has been implemented.

If you visit the signup page of www.supertorrents.org for the first time from you computer, it's fine. But if you refresh the page or open the page again, it identifies you've previously visited the page. The real beauty comes here - it identifies even if you re-install Windows or other OS.

I read somewhere that they store the CPU ID. Although I couldn't find how do they do it, I seriously doubt it, and they might use MAC Address to do it.

I'll definitely share if I find how to do it.

How to connect to MySQL Database?

 private void Initialize()
    {
        server = "localhost";
        database = "connectcsharptomysql";
        uid = "username";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
        database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

How to clear text area with a button in html using javascript?

You need to attach a click event handler and clear the contents of the textarea from that handler.

HTML

<input type="button" value="Clear" id="clear"> 
<textarea id='output' rows=20 cols=90></textarea>

JS

var input = document.querySelector('#clear');
var textarea = document.querySelector('#output');

input.addEventListener('click', function () {
    textarea.value = '';
}, false);

and here's the working demo.

postgresql COUNT(DISTINCT ...) very slow

-- My default settings (this is basically a single-session machine, so work_mem is pretty high)
SET effective_cache_size='2048MB';
SET work_mem='16MB';

\echo original
EXPLAIN ANALYZE
SELECT
        COUNT (distinct val) as aantal
FROM one
        ;

\echo group by+count(*)
EXPLAIN ANALYZE
SELECT
        distinct val
       -- , COUNT(*)
FROM one
GROUP BY val;

\echo with CTE
EXPLAIN ANALYZE
WITH agg AS (
    SELECT distinct val
    FROM one
    GROUP BY val
    )
SELECT COUNT (*) as aantal
FROM agg
        ;

Results:

original                                                      QUERY PLAN                                                      
----------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36448.06..36448.07 rows=1 width=4) (actual time=1766.472..1766.472 rows=1 loops=1)
   ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=31.371..185.914 rows=1499845 loops=1)
 Total runtime: 1766.642 ms
(3 rows)

group by+count(*)
                                                         QUERY PLAN                                                         
----------------------------------------------------------------------------------------------------------------------------
 HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=412.470..412.598 rows=1300 loops=1)
   ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=412.066..412.203 rows=1300 loops=1)
         ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=26.134..166.846 rows=1499845 loops=1)
 Total runtime: 412.686 ms
(4 rows)

with CTE
                                                             QUERY PLAN                                                             
------------------------------------------------------------------------------------------------------------------------------------
 Aggregate  (cost=36506.56..36506.57 rows=1 width=0) (actual time=408.239..408.239 rows=1 loops=1)
   CTE agg
     ->  HashAggregate  (cost=36464.31..36477.31 rows=1300 width=4) (actual time=407.704..407.847 rows=1300 loops=1)
           ->  HashAggregate  (cost=36448.06..36461.06 rows=1300 width=4) (actual time=407.320..407.467 rows=1300 loops=1)
                 ->  Seq Scan on one  (cost=0.00..32698.45 rows=1499845 width=4) (actual time=24.321..165.256 rows=1499845 loops=1)
       ->  CTE Scan on agg  (cost=0.00..26.00 rows=1300 width=0) (actual time=407.707..408.154 rows=1300 loops=1)
     Total runtime: 408.300 ms
    (7 rows)

The same plan as for the CTE could probably also be produced by other methods (window functions)

How to import image (.svg, .png ) in a React Component

If the images are inside the src/assets folder you can use require with the correct path in the require statement,

var Diamond = require('../../assets/linux_logo.jpg');

 export class ItemCols extends Component {
    render(){
        return (
            <div>
                <section className="one-fourth" id="html">
                    <img src={Diamond} />
                </section>
            </div>
        )
    } 
}

Smooth scrolling when clicking an anchor link

There are already a lot of good answers here - however they are all missing the fact that empty anchors have to be excluded. Otherwise those scripts generate JavaScript errors as soon as an empty anchor is clicked.

In my opinion the correct answer is like this:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

Git Bash is extremely slow on Windows 7 x64

I was having the same problem, in both Git Bash and Git GUI. Both programs use to run nicely, but then they randomly slowed down to a crawl, and I couldn't figure out why.

As it turns out, it was Avast. Avast has caused odd things to happen to various programs (including programs I write), so I disabled it for a second, and sure enough, Bash now runs as fast as it does on Linux. I just added the Git program files folder (C:\Program Files\Git) to the Avast exclusion list, and now it runs as fast as it does on Linux.

And yes, I realize the antivirus software was not the issue in the original post, but I'll just put this here in case it's useful to someone.

PHP Session data not being saved

Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out

How to darken a background using CSS?

This is the easiest way I found

  background: black;
  opacity: 0.5;

month name to month number and vice versa in python

Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:

from time import strptime
monthWord = 'september'

newWord = monthWord [0].upper() + monthWord [1:3].lower() 
# converted to "Sep"

print(strptime(newWord,'%b').tm_mon) 
# "Sep" converted to "9" by strptime