Don't make it complicated. I just used this and got a beautiful output:
ls -lR /path/I/need
To do rounding up in truncating arithmetic, simply add (denom-1)
to the numerator.
Example, rounding down:
N/2
M/5
K/16
Example, rounding up:
(N+1)/2
(M+4)/5
(K+15)/16
To do round-to-nearest, add (denom/2)
to the numerator (halves will round up):
(N+1)/2
(M+2)/5
(K+8)/16
If you want to run it @build time :
CMD /bin/bash /file.sh arg1
if you want to run it @run time :
ENTRYPOINT ["/bin/bash"]
CMD ["/file.sh", "arg1"]
Then in the host shell
docker build -t test .
docker run -i -t test
For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:
#!/bin/sh
echo -n "Enter username: "
read uname
echo -n "Enter password: "
read -s passwd
adduser "$uname"
echo $uname:$passwd | sudo chpasswd
gpasswd wheel -a $uname
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
I normally use the 'back tick' feature of bash
export NUM_LINES=`wc -l filename`
Note the 'tick' is the 'back tick' e.g. ` not the normal single quote
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
It really depends on how you write your bash scripts. If your /bin/sh
is symlinked to bash, when bash is invoked as sh
, some features are unavailable.
If you want bash-specific, non-POSIX features, use #!/bin/bash
This should do the trick
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server
Of course, it leaves you with a blank root password - so you'll want to run something like
mysqladmin -u root password mysecretpasswordgoeshere
Afterwards to add a password to the account.
Lots of answer but couldn't find what I was looking for :
date +"%s.%3N"
returns something like : 1606297368.210
To append
a file use >>
echo "hello world" >> read.txt
cat read.txt
echo "hello siva" >> read.txt
cat read.txt
then the output should be
hello world # from 1st echo command
hello world # from 2nd echo command
hello siva
To overwrite
a file use >
echo "hello tom" > read.txt
cat read.txt
then the out put is
hello tom
May be the "\" char, try this one:
sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g'
As Explains in here, you can do it with a simple steps:
By default, word jumps (option + ? or ?) and word deletions (option + backspace) do not work. To enable these, go to "iTerm ? Preferences ? Profiles ? Keys ? Load Preset... ? Natural Text Editing ? Boom! Head explodes"
A simple example that will clear both during executing script or inside script while calling a function.
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" # As string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) # Process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution
# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5
The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.
TIME=10
# WRONG: no such variable called 'TIMEsecs'
echo "Time taken = $TIMEsecs"
# What we want is $TIME followed by "secs" with no whitespace between the two.
echo "Time taken = ${TIME}secs"
# WRONG - no such variable LATESTVERSION_src
CLASSPATH=hibernate-$LATESTVERSION_src.zip:hibernate_$LATEST_VERSION.jar
# RIGHT
CLASSPATH=hibernate-${LATESTVERSION}_src.zip:hibernate_$LATEST_VERSION.jar
(Fred's answer already states this but his example is a bit too abstract)
This approach will not consume any resources for keeping process alive.
while :; do sleep 1; done & kill -STOP $! && wait $!
while :; do sleep 1; done &
Creates a dummy process in backgroundkill -STOP $!
Stops the background process wait $!
Wait for the background process, this will be blocking forever, cause background process was stopped beforedate only work with GNU date (usually comes with Linux)
for OS X, two choices:
change command (verified)
#!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\"" date "Saturday, 1 August 2009 20:41:50"
http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html
Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html
Easiest way for checking file is empty or not:
if [ -s /path-to-file/filename.txt ]
then
echo "File is not empty"
else
echo "File is empty"
fi
You can also write it on single line:
[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"
In shell you assign to a variable without the dollar-sign:
TEST=`pwd`
echo $TEST
that's better (and can be nested) but is not as portable as the backtics:
TEST=$(pwd)
echo $TEST
Always remember: the dollar-sign is only used when reading a variable.
This works even if the script is sourced:
source "$( dirname "${BASH_SOURCE[0]}" )/incl.sh"
Another portable POSIX
compliant way to do in bash
, which can be defined as a function in .bashrc
for all the arithmetic operators of convenience.
addNumbers () {
local IFS='+'
printf "%s\n" "$(( $* ))"
}
and just call it in command-line as,
addNumbers 1 2 3 4 5 100
115
The idea is to use the Input-Field-Separator(IFS), a special variable in bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +
.
Remember the IFS
is changed locally and does NOT take effect on the default IFS
behaviour outside the function scope. An excerpt from the man bash
page,
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.
The "$(( $* ))"
represents the list of arguments passed to be split by +
and later the sum value is output using the printf
function. The function can be extended to add scope for other arithmetic operations also.
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
I recommend using json format, it's easier for parsing
ffprobe -i your-input-file.mp4 -v quiet -print_format json -show_format -show_streams -hide_banner
{
"streams": [
{
"index": 0,
"codec_name": "aac",
"codec_long_name": "AAC (Advanced Audio Coding)",
"profile": "HE-AACv2",
"codec_type": "audio",
"codec_time_base": "1/44100",
"codec_tag_string": "[0][0][0][0]",
"codec_tag": "0x0000",
"sample_fmt": "fltp",
"sample_rate": "44100",
"channels": 2,
"channel_layout": "stereo",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/28224000",
"duration_ts": 305349201,
"duration": "10.818778",
"bit_rate": "27734",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0
}
}
],
"format": {
"filename": "your-input-file.mp4",
"nb_streams": 1,
"nb_programs": 0,
"format_name": "aac",
"format_long_name": "raw ADTS AAC (Advanced Audio Coding)",
"duration": "10.818778",
"size": "37506",
"bit_rate": "27734",
"probe_score": 51
}
}
you can find the duration information in format section, works both for video and audio
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
By far the simplest solution:
if id -u "$user" >/dev/null 2>&1; then
echo 'user exists'
else
echo 'user missing'
fi
The >/dev/null 2>&1
can be shortened to &>/dev/null
in Bash.
echo "$string" | tr xyz _
would replace each occurrence of x
, y
, or z
with _
, giving A__BC___DEF__LMN
in your example.
echo "$string" | sed -r 's/[xyz]+/_/g'
would replace repeating occurrences of x
, y
, or z
with a single _
, giving A_BC_DEF_LMN
in your example.
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
You mean, like this:
grep -o '.\{0,20\}test_pattern.\{0,20\}' file
?
That will print up to twenty characters on either side of test_pattern
. The \{0,20\}
notation is like *
, but specifies zero to twenty repetitions instead of zero or more.The -o
says to show only the match itself, rather than the entire line.
Don't store lists as strings; store them as arrays to avoid all this delimiter confusion. Here's an example script that'll either operate on all subdirectories of test, or the list supplied on its command line:
#!/bin/bash
if [ $# -eq 0 ]; then
# if no args supplies, build a list of subdirs of test/
dirlist=() # start with empty list
for f in test/*; do # for each item in test/ ...
if [ -d "$f" ]; then # if it's a subdir...
dirlist=("${dirlist[@]}" "$f") # add it to the list
fi
done
else
# if args were supplied, copy the list of args into dirlist
dirlist=("$@")
fi
# now loop through dirlist, operating on each one
for dir in "${dirlist[@]}"; do
printf "Directory: %s\n" "$dir"
done
Now let's try this out on a test directory with a curve or two thrown in:
$ ls -F test
Baltimore/
Cherry Hill/
Edison/
New York City/
Philadelphia/
this is a dirname with quotes, lfs, escapes: "\''?'?\e\n\d/
this is a file, not a directory
$ ./test.sh
Directory: test/Baltimore
Directory: test/Cherry Hill
Directory: test/Edison
Directory: test/New York City
Directory: test/Philadelphia
Directory: test/this is a dirname with quotes, lfs, escapes: "\''
'
\e\n\d
$ ./test.sh "Cherry Hill" "New York City"
Directory: Cherry Hill
Directory: New York City
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
You need a space on either side of the !=
. Change your code to:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
Had the same issue, I solved the issue killing the process and then waiting for each process to finish using the PROC filesystem:
while [ -e /proc/${pid} ]; do sleep 0.1; done
I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.
With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node
at the top of my executed node.js script.
Since then, no problems, although I intend to see what else can be extended to the service itself.
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
zsh has a builtin command emulate
which can emulate different shells by setting the appropriate options, although csh will never be fully emulated.
emulate bash
perform commands
emulate -R zsh
The -R flag restores all the options to their default values for that shell.
See: zsh manual
Here documents with the <<-HERE
terminator work well for indented multi-line text strings. It will remove any leading tabs from the here document. (Line terminators will still remain, though.)
cat <<-____HERE
continuation
lines
____HERE
See also http://ss64.com/bash/syntax-here.html
If you need to preserve some, but not all, leading whitespace, you might use something like
sed 's/^ //' <<____HERE
This has four leading spaces.
Two of them will be removed by sed.
____HERE
or maybe use tr
to get rid of newlines:
tr -d '\012' <<-____
continuation
lines
____
(The second line has a tab and a space up front; the tab will be removed by the dash operator before the heredoc terminator, whereas the space will be preserved.)
For wrapping long complex strings over many lines, I like printf
:
printf '%s' \
"This will all be printed on a " \
"single line (because the format string " \
"doesn't specify any newline)"
It also works well in contexts where you want to embed nontrivial pieces of shell script in another language where the host language's syntax won't let you use a here document, such as in a Makefile
or Dockerfile
.
printf '%s\n' >./myscript \
'#!/bin/sh` \
"echo \"G'day, World\"" \
'date +%F\ %T' && \
chmod a+x ./myscript && \
./myscript
A more elegant alternative to the proposed Python solution could be:
python -c 'print "="*(1000)'
Try something like grep -r -n -i --include="*.html *.php *.js" searchstrinhere .
the -i
makes it case insensitlve
the .
at the end means you want to start from your current directory, this could be substituted with any directory.
the -r
means do this recursively, right down the directory tree
the -n
prints the line number for matches.
the --include
lets you add file names, extensions. Wildcards accepted
For more info see: http://www.gnu.org/software/grep/
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
that value is contained in the variable $#
The seq
method is the simplest, but Bash has built-in arithmetic evaluation.
END=5
for ((i=1;i<=END;i++)); do
echo $i
done
# ==> outputs 1 2 3 4 5 on separate lines
The for ((expr1;expr2;expr3));
construct works just like for (expr1;expr2;expr3)
in C and similar languages, and like other ((expr))
cases, Bash treats them as arithmetic.
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
Here is what I use for listing only directory names:
ls -1d /some/folder/*/ | awk -F "/" "{print \$(NF-1)}"
sudo tar -xvzf ./PhpStorm-2018.3.4.tar.gz
I wanted to display logs on stdout and log file along with the timestamp. None of the above answers worked for me. I made use of process substitution and exec command and came up with the following code. Sample logs:
2017-06-21 11:16:41+05:30 Fetching information about files in the directory...
Add following lines at the top of your script:
LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)
Hope this helps somebody!
Specify NR
if you want to capture output from selected rows:
awk 'NR==1{print $1}' /etc/*release
An alternative (ugly) way of achieving the same would be:
awk '{print $1; exit}'
An efficient way of getting the first string from a specific line, say line 42, in the output would be:
awk 'NR==42{print $1; exit}'
There's an easier way:
find ... | while read -r file; do
echo "look at my $file, my $file is amazing";
done
Alternatively:
while read -r file; do
echo "look at my $file, my $file is amazing";
done <<< "$(find ...)"
Buffering of output depends on how your program /homedir/MyScript
is implemented. If you find that output is getting buffered, you have to force it in your implementation. For example, use sys.stdout.flush() if it's a python program or use fflush(stdout) if it's a C program.
See Redirecting Output from a Running Process.
Firstly I run the command
cat > foo1
in one session and test that data from stdin is copied to the file. Then in another session I redirect the output.Firstly find the PID of the process:
$ ps aux | grep cat rjc 6760 0.0 0.0 1580 376 pts/5 S+ 15:31 0:00 cat
Now check the file handles it has open:
$ ls -l /proc/6760/fd total 3 lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5 l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1 lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5
Now run GDB:
$ gdb -p 6760 /bin/cat GNU gdb 6.4.90-debian [license stuff snipped] Attaching to program: /bin/cat, process 6760 [snip other stuff that's not interesting now] (gdb) p close(1) $1 = 0 (gdb) p creat("/tmp/foo3", 0600) $2 = 1 (gdb) q The program is running. Quit anyway (and detach it)? (y or n) y Detaching from program: /bin/cat, process 6760
The
p
command in GDB will print the value of an expression, an expression can be a function to call, it can be a system call… So I execute aclose()
system call and pass file handle 1, then I execute acreat()
system call to open a new file. The result of thecreat()
was 1 which means that it replaced the previous file handle. If I wanted to use the same file for stdout and stderr or if I wanted to replace a file handle with some other number then I would need to call thedup2()
system call to achieve that result.For this example I chose to use
creat()
instead ofopen()
because there are fewer parameter. The C macros for the flags are not usable from GDB (it doesn’t use C headers) so I would have to read header files to discover this – it’s not that hard to do so but would take more time. Note that 0600 is the octal permission for the owner having read/write access and the group and others having no access. It would also work to use 0 for that parameter and run chmod on the file later on.After that I verify the result:
ls -l /proc/6760/fd/ total 3 lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5 l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/foo3 <==== lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5
Typing more data in to
cat
results in the file/tmp/foo3
being appended to.If you want to close the original session you need to close all file handles for it, open a new device that can be the controlling tty, and then call
setsid()
.
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
Use a shell script:
#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2
> ./myscript
With docker compose there's a simple alternative (no need to create a Dockerfile). Just create a init-database.sh:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER docker;
CREATE DATABASE my_project_development;
GRANT ALL PRIVILEGES ON DATABASE my_project_development TO docker;
CREATE DATABASE my_project_test;
GRANT ALL PRIVILEGES ON DATABASE my_project_test TO docker;
EOSQL
And reference it in the volumes section:
version: '3.4'
services:
postgres:
image: postgres
restart: unless-stopped
volumes:
- postgres:/var/lib/postgresql/data
- ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
volumes:
postgres:
Instead of if
construct, you can leverage the short-circuit evaluation:
#!/usr/bin/env bash
echo $[1+1]
echo $[2/0] # division by 0 but execution of script proceeds
echo $[3+1]
(echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
echo $[5+1]
Note the pair of parentheses which is necessary because of priority of alternation operator. $?
is a special variable set to exit code of most recently called command.
Suspend the process with CTRL+Z then use the command bg
to resume it in background. For example:
sleep 60
^Z #Suspend character shown after hitting CTRL+Z
[1]+ Stopped sleep 60 #Message showing stopped process info
bg #Resume current job (last job stopped)
More about job control and bg
usage in bash
manual page:
JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.
EDIT
To start a process where you can even kill the terminal and it still carries on running
nohup [command] [-args] > [filename] 2>&1 &
e.g.
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &
To just ignore the output (not very wise) change the filename to /dev/null
To get the error message set to a different file change the &1
to a filename.
In addition: You can use the jobs
command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1
or kill %2
with the number being the index of the process.
Don't use spaces...
(Incorrect)
SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
(Correct)
SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'
For zsh, echo
setopt VERBOSE
And for debugging,
setopt XTRACE
If you are just comparing numbers, I think there's no need to change syntax, just correct those lines, lines 6 and 9 brackets.
Line 6 before: if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
After: if [ "$age" -le "7" -o "$age" -ge "65" ]
Line 9 before: elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]
There are two ways you can do this. One is the one already mentioned, i.e.:
php -f filename.php
The second option is making the script executable (chmod +x filename.php
) and adding the following line to the top of your .php file:
#!/path/to/php
I'm not sure though if a webserver likes this, so if you also want to use the .php file in a website, that might not be the best idea. Still, if you're just writing some kind of script, it is easier to type ./path/to/phpfile.php
than having to type php -f /path/to/phpfile.php
every time.
I have a sample from your code. Try this:
echo "*Select Option:*"
echo "1 - script1"
echo "2 - script2"
echo "3 - script3 "
read option
echo "You have selected" $option"."
if [ $option="1" ]
then
echo "1"
elif [ $option="2" ]
then
echo "2"
exit 0
elif [ $option="3" ]
then
echo "3"
exit 0
else
echo "Please try again from given options only."
fi
This should work. :)
In this answer I copy Dennis Williamson's answer and modify it slightly to allow a vast speed increase when piping a column of many timestamps to the script. For example, piping 1000 timestamps to the original script with xargs -n1 on my machine took 6.929s as opposed to 0.027s with this modified version:
#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
if [[ -p /dev/stdin ]] # input from a pipe
then
cat - | gawk '{ print strftime("%c", $1); }'
else
echo "No timestamp given." >&2
exit
fi
else
date -d @$1 +%c
fi
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
The dogbane
answer with the description what is coming on:
#! /bin/sh
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
Explanation:
"$1"
dirname "$1"
cd "$(dirname "$1")
into this relative dir and get absolute path for it by running pwd
shell command$(basename "$1")
echo
itexit 1
is all you need. The 1
is a return code, so you can change it if you want, say, 1
to mean a successful run and -1
to mean a failure or something like that.
there is no need to use for cycle
you can benefit from bash parameter expansion functions:
var="a b c";
var=${var// /\\n};
echo -e $var
a
b
c
or just use tr:
var="a b c"
echo $var | tr " " "\n"
a
b
c
1.modify "/etc/profile" file.
#vi /etc/profile
Press "i" key to enter editing status and move cursor to the end of the file,Additional entries:
export PATH=$PATH:/path/to/dir;
Press "Esc" key exit edit status,':wq' save the file.
2.Make configuration effective
source /etc/profile
Explain: profile file works for all users,if you want to be valid only for the active user, set the ".bashrc" file
1 - You can script sshpass's ssh
command like this:
#!/bin/bash
export SSHPASS=password
sshpass -e ssh -oBatchMode=no user@host
2 - You can script sshpass
's sftp
commandlike this:
#!/bin/bash
export SSHPASS=password
sshpass -e sftp -oBatchMode=no -b - user@host << !
put someFile
get anotherFile
bye
!
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
Yes; you can use return
instead of exit
. Its main purpose is to return from a shell function, but if you use it within a source
-d script, it returns from that script.
As §4.1 "Bourne Shell Builtins" of the Bash Reference Manual puts it:
return [n]
Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the
.
(orsource
) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with theRETURN
trap is executed before execution resumes after the function or script. The return status is non-zero ifreturn
is used outside a function and not during the execution of a script by.
orsource
.
I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60
returns nothing. The command find . -mmin -60 |xargs ls -l
, however, returns every file in the directory which is consistent with what happens when ls -l
is run without an argument.
To make sure that ls -l
is only run when a file is found, try:
find . -mmin -60 -type f -exec ls -l {} +
hostname -I | awk ' {print $1}'
All,
From what I'm seeing here all answers are wrong, especially if you entered the sudo mode, with all returning 'root' instead of the logged in user. The answer is in using 'who' and finding eh 'tty1' user and extracting that. Thw "w" command works the same and var=$SUDO_USER gets the real logged in user.
Cheers!
TBNK
Whenever possible, you should avoid parsing the output of ls
(see Greg's wiki on the subject). Basically, the output of ls
will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */
, what happens is that the shell expands */
to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d
, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls
command isn't doing anything useful!
Well, ok, it is doing one thing that's useful: if there are no subdirectories, */
will get left as is, ls
will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).
The cleaner way to make an array of subdirectory names is to use the glob (*/
) without passing it to ls
. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):
shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}" # Note double-quotes to avoid extra parsing of funny characters in filenames
If you want to print an error message if there are no subdirectories, you're better off doing it yourself:
if (( ${#array[@]} == 0 )); then
echo "No subdirectories found" >&2
fi
This may not be possible with cat
. Is there a reason you have to use cat
?
If you simply need to do it with a bash command, this should work for you:
head -n 1 file.txt
I tend to keep my .bashrc and .bash_alias on a file share that all platforms can access. This is how I conquer the problem in my .bash_alias:
if [[ -f (name of share)/.bash_alias_$(uname) ]]; then
. (name of share)/.bash_alias_$(uname)
fi
And I have for example a .bash_alias_Linux with:
alias ls='ls --color=auto'
This way I keep platform specific and portable code separate, you can do the same for .bashrc
After I had tried everything described, I looked up into the folder permission of brew in /usr/local/etc/. Somehow the permission were changed and I was not able to open the folder. I changed the folder permissions(with chmod) with same permissions as the other folders and brew start working.
This was happening for me when I was trying to call a function using parens, e.g.
run() {
echo hello
}
run()
should be:
run() {
echo hello
}
run
It is:
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
The $#
variable will tell you the number of input arguments the script was passed.
Or you can check if an argument is an empty string or not like:
if [ -z "$1" ]
then
echo "No argument supplied"
fi
The -z
switch will test if the expansion of "$1"
is a null string or not. If it is a null string then the body is executed.
For windows: Follow these steps-
cd-to-home
from target
(b) Type folder path you want to start with git in "Start in".This worked for me:)
I think this should be a comment or an edit to ThinkingMedia's answer on this very question (Check free disk space for current partition in bash), but I am not allowed to comment (not enough rep) and my edit has been rejected (reason: "this should be a comment or an answer"). So please, powers of the SO universe, don't damn me for repeating and fixing someone else's "answer". But someone on the internet was wrong!™ and they wouldn't let me fix it.
The code
df --output=avail -h "$PWD" | sed '1d;s/[^0-9]//g'
has a substantial flaw:
Yes, it will output 50G
free as 50 -- but it will also output 5.0M
free as 50 or 3.4G
free as 34 or 15K
free as 15.
To create a script with the purpose of checking for a certain amount of free disk space you have to know the unit you're checking against. Remove it (as sed
does in the example above) the numbers don't make sense anymore.
If you actually want it to work, you will have to do something like:
FREE=`df -k --output=avail "$PWD" | tail -n1` # df -k not df -h
if [[ $FREE -lt 10485760 ]]; then # 10G = 10*1024*1024k
# less than 10GBs free!
fi;
Also for an installer to df -k $INSTALL_TARGET_DIRECTORY
might make more sense than df -k "$PWD"
.
Finally, please note that the --output
flag is not available in every version of df / linux.
Graphviz - from the web page:
The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)
It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".
It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.
This is a workaround (for me: I don't use awk very often):
Display the first row of the file containing the data, replace all pipes with newlines and then count the lines:
$ head -1 stores.dat | tr '|' '\n' | wc -l
I use the environment variable CDPATH
line=`sed -n 2p myfile`
echo $line
If you have a file named filelist.txt that is a list paths such as the following: c:/dir1/dir2/file1.h c:/dir1/dir2/dir3/file2.h
then you can do this: rev filelist.txt | cut -d"/" -f1 | rev
This also works :
if ssh user@ip "[ -s /path/file_name ]" ;then
status=RECEIVED ;
else
status=MISSING ;
fi
nano ~/.profile
add these lines:
export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
save the file:
Ctrl + X
then Y
then Enter
then render the changes:
source ~/.profile
-z string
True if the length of string is zero.
-n string
string
True if the length of string is non-zero.
You can use shorthand version:
if [[ $(ls -A) ]]; then
echo "there are files"
else
echo "no files found"
fi
Use find
with a wildcard:
find . -name 'mystring*'
If you found the variant of your preference you can also wrap it into a function.
Here I'm wrapping some bashism into a div function:
One liner:
function div { local _d=${3:-2}; local _n=0000000000; _n=${_n:0:$_d}; local _r=$(($1$_n/$2)); _r=${_r:0:-$_d}.${_r: -$_d}; echo $_r;}
Or multi line:
function div {
local _d=${3:-2}
local _n=0000000000
_n=${_n:0:$_d}
local _r=$(($1$_n/$2))
_r=${_r:0:-$_d}.${_r: -$_d}
echo $_r
}
Now you have the function
div <dividend> <divisor> [<precision=2>]
and use it like
> div 1 2
.50
> div 273 123 5
2.21951
> x=$(div 22 7)
> echo $x
3.14
UPDATE I added a little script which provides you the basic operations with floating point numbers for bash:
Usage:
> add 1.2 3.45
4.65
> sub 1000 .007
999.993
> mul 1.1 7.07
7.7770
> div 10 3
3.
> div 10 3.000
3.333
And here the script:
#!/bin/bash
__op() {
local z=00000000000000000000000000000000
local a1=${1%.*}
local x1=${1//./}
local n1=$((${#x1}-${#a1}))
local a2=${2%.*}
local x2=${2//./}
local n2=$((${#x2}-${#a2}))
local n=$n1
if (($n1 < $n2)); then
local n=$n2
x1=$x1${z:0:$(($n2-$n1))}
fi
if (($n1 > $n2)); then
x2=$x2${z:0:$(($n1-$n2))}
fi
if [ "$3" == "/" ]; then
x1=$x1${z:0:$n}
fi
local r=$(($x1"$3"$x2))
local l=$((${#r}-$n))
if [ "$3" == "*" ]; then
l=$(($l-$n))
fi
echo ${r:0:$l}.${r:$l}
}
add() { __op $1 $2 + ;}
sub() { __op $1 $2 - ;}
mul() { __op $1 $2 "*" ;}
div() { __op $1 $2 / ;}
If anyone finds themselves in a position where they need to remember set -e or set -x values and be able to restore them, please check out this gist which uses the first array deletion solution to manage it's own stack:
https://gist.github.com/kigster/94799325e39d2a227ef89676eed44cc6
move
and del
ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move
command. And the same thing applies with del
.
The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.
mv
and rm
are in the CoreUtils package and they work wonderfully!
Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.
Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.
Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.
you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:
#!/bin/sh
OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")
if [ $? -ne 0 ]; then
echo "getopt error"
exit 1
fi
eval set -- $OPTIONS
while true; do
case "$1" in
-h|--help) HELP=1 ;;
-f|--file) FILE="$2" ; shift ;;
-g|--foo) FOO=1 ;;
-b|--bar) BAR=1 ;;
--) shift ; break ;;
*) echo "unknown option: $1" ; exit 1 ;;
esac
shift
done
if [ $# -ne 0 ]; then
echo "unknown option(s): $@"
exit 1
fi
echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"
see also:
man getopt
for i in *_h.png ; do
mv $i `echo "$i"|awk -F'.' '{print $1"alf."$2}'`
done
If you're using Bash you could also use one of the following commands:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
I needed to keep double quotes in my configuration file so double escaping double quotes with sed helps:
render_template() {
eval "echo \"$(sed 's/\"/\\\\"/g' $1)\""
}
I can't think of keeping trailing new lines, but empty lines in between are kept.
Although it is an old topic, IMO I found out more elegant solution here: http://pempek.net/articles/2013/07/08/bash-sh-as-template-engine/
#!/bin/sh
# render a template configuration file
# expand variables + preserve formatting
render_template() {
eval "echo \"$(cat $1)\""
}
user="Gregory"
render_template /path/to/template.txt > path/to/configuration_file
All credits to Grégory Pakosz.
The following (evil) code runs more than TWICE as fast as the nmap method
for i in {1..254} ;do (ping 192.168.1.$i -c 1 -w 5 >/dev/null && echo "192.168.1.$i" &) ;done
takes around 10 seconds, where the standard nmap
nmap -sP 192.168.1.1-254
takes 25 seconds...
SELECT DATEPART(QUARTER, @date)
This returns the quarter of the @date
, assuming @date
is a DATETIME
.
I solved this by assigning a ref to the component and then checking if the ref exists before setting the state:
myMethod(){
if (this.refs.myRef)
this.setState({myVar: true});
}
render() {
return (
<div ref="myRef">
{this.state.myVar}
</div>
);
}
And lately, since I am using mostly functional components, I am using this pattern:
const Component = () => {
const ref = React.useRef(null);
const [count, setCount] = React.useState(0);
const increment = () => {
setTimeout(() => { // usually fetching API data here
if (ref.current !== null) {
setCount((count) => count + 1);
}
}, 100);
};
return (
<button onClick={increment} ref={ref}>
Async Increment {count}
</button>
);
};
Try something like this...
<div id="wrapper" style="width:100%; text-align:center">
<img id="yourimage"/>
</div>
The simplest:
int main()
{
const char* str = "hello";
for (const char* p = str; *p; ++p)
{
printf("%02x", *p);
}
printf("\n");
return 0;
}
Clearing my browser's cache fixed this issue for me. I had been switching between local development environments to do the django-blog-zinnia tutorial after working on another project when it happened. At first, I thought changing the order of INSTALLED_APPS to match the tutorial had caused it, but I set these back and was unable to correct it until clearing the cache.
We can use the get_locale
function:
if (get_locale() == 'en_GB') {
// drink tea
}
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
You update core-js with the following command:
npm install --save core-js@^3
If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.
They're a bad idea in general because it's a truly rare condition where a failure (exceptional condition, more generically) is properly met with NO response whatsoever. On top of that, empty catch
blocks are a common tool used by people who use the exception engine for error checking that they should be doing preemptively.
To say that it's always bad is untrue...that's true of very little. There can be circumstances where either you don't care that there was an error or that the presence of the error somehow indicates that you can't do anything about it anyway (for example, when writing a previous error to a text log file and you get an IOException
, meaning that you couldn't write out the new error anyway).
rsync is work!
#file:
rsync -aqz _vimrc ~/.vimrc
#directory:
rsync -aqz _vim/ ~/.vim
I faced with the same issue. I just added credentials config:
aws_access_key_id = your_aws_access_key_id
aws_secret_access_key = your_aws_secret_access_key
into "~/.aws/credentials" + restart terminal for default profile.
In the case of multi profiles --profile arg needs to be added:
aws s3 sync ./localDir s3://bucketName --profile=${PROFILE_NAME}
where PROFILE_NAME:
.bash_profile ( or .bashrc) -> export PROFILE_NAME="yourProfileName"
More info about how to config credentials and multi profiles can be found here
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
Supports :
CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!
Option 1
: Declare a struct with an int and string and return a struct variable.
struct foo {
int bar1;
char bar2[MAX];
};
struct foo fun() {
struct foo fooObj;
...
return fooObj;
}
Option 2
: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:
int fun(char **param) {
int bar;
...
strcpy(*param,"....");
return bar;
}
or
char* fun(int *param) {
char *str = /* malloc suitably.*/
...
strcpy(str,"....");
*param = /* some value */
return str;
}
Option 3
: Similar to the option 2. You can pass both via pointer and return nothing from the function:
void fun(char **param1,int *param2) {
strcpy(*param1,"....");
*param2 = /* some calculated value */
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
<input type='file' id="getFile" style="display:none">
</body>
</html>
_x000D_
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
From Wikipedia http://en.wikipedia.org/wiki/Berkeley_sockets#bind.28.29
connect():
The connect() system call connects a socket, identified by its file descriptor, to a remote host specified by that host's address in the argument list.
Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets.
connect() returns an integer representing the error code: 0 represents success, while -1 represents an error.
bind():
bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments:
sockfd, a descriptor representing the socket to perform the bind on. my_addr, a pointer to a sockaddr structure representing the address to bind to. addrlen, a socklen_t field specifying the size of the sockaddr structure. Bind() returns 0 on success and -1 if an error occurs.
Examples: 1.)Using Connect
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(){
int clientSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
socklen_t addr_size;
/*---- Create the socket. The three arguments are: ----*/
/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
clientSocket = socket(PF_INET, SOCK_STREAM, 0);
/*---- Configure settings of the server address struct ----*/
/* Address family = Internet */
serverAddr.sin_family = AF_INET;
/* Set port number, using htons function to use proper byte order */
serverAddr.sin_port = htons(7891);
/* Set the IP address to desired host to connect to */
serverAddr.sin_addr.s_addr = inet_addr("192.168.1.17");
/* Set all bits of the padding field to 0 */
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
/*---- Connect the socket to the server using the address struct ----*/
addr_size = sizeof serverAddr;
connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);
/*---- Read the message from the server into the buffer ----*/
recv(clientSocket, buffer, 1024, 0);
/*---- Print the received message ----*/
printf("Data received: %s",buffer);
return 0;
}
2.)Bind Example:
int main()
{
struct sockaddr_in source, destination = {}; //two sockets declared as previously
int sock = 0;
int datalen = 0;
int pkt = 0;
uint8_t *send_buffer, *recv_buffer;
struct sockaddr_storage fromAddr; // same as the previous entity struct sockaddr_storage serverStorage;
unsigned int addrlen; //in the previous example socklen_t addr_size;
struct timeval tv;
tv.tv_sec = 3; /* 3 Seconds Time-out */
tv.tv_usec = 0;
/* creating the socket */
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
printf("Failed to create socket\n");
/*set the socket options*/
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
/*Inititalize source to zero*/
memset(&source, 0, sizeof(source)); //source is an instance of sockaddr_in. Initialization to zero
/*Inititalize destinaton to zero*/
memset(&destination, 0, sizeof(destination));
/*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
/* Address family = Internet */
source.sin_family = AF_INET;
/* Set IP address to localhost */
source.sin_addr.s_addr = INADDR_ANY; //INADDR_ANY = 0.0.0.0
/* Set port number, using htons function to use proper byte order */
source.sin_port = htons(7005);
/* Set all bits of the padding field to 0 */
memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional
/*bind socket to the source WHERE THE PACKET IS COMING FROM*/
if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0)
printf("Failed to bind socket");
/* setting the destination, i.e our OWN IP ADDRESS AND PORT */
destination.sin_family = AF_INET;
destination.sin_addr.s_addr = inet_addr("127.0.0.1");
destination.sin_port = htons(7005);
//Creating a Buffer;
send_buffer=(uint8_t *) malloc(350);
recv_buffer=(uint8_t *) malloc(250);
addrlen=sizeof(fromAddr);
memset((void *) recv_buffer, 0, 250);
memset((void *) send_buffer, 0, 350);
sendto(sock, send_buffer, 20, 0,(struct sockaddr *) &destination, sizeof(destination));
pkt=recvfrom(sock, recv_buffer, 98,0,(struct sockaddr *)&destination, &addrlen);
if(pkt > 0)
printf("%u bytes received\n", pkt);
}
I hope that clarifies the difference
Please note that the socket type that you declare will depend on what you require, this is extremely important
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
If you want your result concatenated, as you show in your question, you could try something like:
>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'
Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
I needed to correct the privileges.REVOKE ALL PRIVILEGES ON
logs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ON
logs.* TO 'root'@'root'WITH GRANT OPTION;
Here's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:
List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?
) as the request body.
This requires Content-Type
and Content-Length
headers, so the receiving server knows how to interpret the incoming data. (*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded
for the traditional format that a standard HTML form would use.
It's easy to send JSON (application/json
) in exactly the same manner; just JSON.stringify()
the data beforehand.
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
The bottom line is: The server must be able to interpret the content type in question. It could be text/plain
or anything else; there is no need to convert data if the receiving server understands it as it is.
Add a charset parameter (e.g. application/json; charset=Windows-1252
) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
The 'react-json-view' provides solution rendering json string.
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
You can just put r
in front of the string with your actual path, which denotes a raw string. For example:
data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")
ALTER TABLE tbl_Country DROP columnName;
You can also simply use this:
.bg_rgba {
background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
width: 200px;
height: 200px;
border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
You can change the opacity of the color to your preference.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict
is not atomic—it is possible that 'key'
may be in my_dict
during the if
statement, but may be deleted before del
is executed, in which case del
will fail with a KeyError
. Given this, it would be safest to either use dict.pop
or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
A dozen pages is not a big deal when using OFFSET
. But when you have hundreds of pages, you will find that OFFSET
is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
Requests doesn't have an equivalent to Urlib2's read()
.
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
It looks like the POST request you are making is returning no content. Which is often the case with a POST request. Perhaps it set a cookie? The status code is telling you that the POST succeeded after all.
Edit for Python 3:
Python now handles data types differently. response.content
returns a sequence of bytes
(integers that represent ASCII) while response.text
is a string
(sequence of chars).
Thus,
>>> print response.content == response.text
False
>>> print str(response.content) == response.text
True
/* iPad */
@media screen and (min-device-width: 768px) {
/* ipad-portrait */
@media screen and (max-width: 896px) {
.logo{
display: none !important;
}
}
/* ipad-landscape */
@media screen and (min-width: 897px) {
}
}
/* iPhone */
@media screen and (max-device-width: 480px) {
/* iphone-portrait */
@media screen and (max-width: 400px) {
}
/* iphone-landscape */
@media screen and (min-width: 401px) {
}
}
Not sure if this is correct in any sense but this seems to work for me.
someHeader.h
inline int someVar;
I don't have linking/multiple definition issues and it "just works"... ;- )
It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.
The octothorpe/number-sign/hashmark has a special significance in an URL, it normally identifies the name of a section of a document. The precise term is that the text following the hash is the anchor portion of an URL. If you use Wikipedia, you will see that most pages have a table of contents and you can jump to sections within the document with an anchor, such as:
https://en.wikipedia.org/wiki/Alan_Turing#Early_computers_and_the_Turing_test
https://en.wikipedia.org/wiki/Alan_Turing
identifies the page and Early_computers_and_the_Turing_test
is the anchor. The reason that Facebook and other Javascript-driven applications (like my own Wood & Stones) use anchors is that they want to make pages bookmarkable (as suggested by a comment on that answer) or support the back button without reloading the entire page from the server.
In order to support bookmarking and the back button, you need to change the URL. However, if you change the page portion (with something like window.location = 'http://raganwald.com';
) to a different URL or without specifying an anchor, the browser will load the entire page from the URL. Try this in Firebug or Safari's Javascript console. Load http://minimal-github.gilesb.com/raganwald
. Now in the Javascript console, type:
window.location = 'http://minimal-github.gilesb.com/raganwald';
You will see the page refresh from the server. Now type:
window.location = 'http://minimal-github.gilesb.com/raganwald#try_this';
Aha! No page refresh! Type:
window.location = 'http://minimal-github.gilesb.com/raganwald#and_this';
Still no refresh. Use the back button to see that these URLs are in the browser history. The browser notices that we are on the same page but just changing the anchor, so it doesn't reload. Thanks to this behaviour, we can have a single Javascript application that appears to the browser to be on one 'page' but to have many bookmarkable sections that respect the back button. The application must change the anchor when a user enters different 'states', and likewise if a user uses the back button or a bookmark or a link to load the application with an anchor included, the application must restore the appropriate state.
So there you have it: Anchors provide Javascript programmers with a mechanism for making bookmarkable, indexable, and back-button-friendly applications. This technique has a name: It is a Single Page Interface.
p.s. There is a fourth benefit to this technique: Loading page content through AJAX and then injecting it into the current DOM can be much faster than loading a new page. In addition to the speed increase, further tricks like loading certain portions in the background can be performed under the programmer's control.
p.p.s. Given all of that, the 'bang' or exclamation mark is a further hint to Google's web crawler that the exact same page can be loaded from the server at a slightly different URL. See Ajax Crawling. Another technique is to make each link point to a server-accessible URL and then use unobtrusive Javascript to change it into an SPI with an anchor.
Here's the key link again: The Single Page Interface Manifesto
Use simple FileStream.Read
then print it with Convert.ToString(b, 2)
The class attribute can contain multiple styles, so you could specify it as
<tr class="row-even highlight">
and do string manipulation to remove 'highlight' from element.className
element.className=element.className.replace('hightlight','');
Using jQuery would make this simpler as you have the methods
$("#id").addClass("highlight");
$("#id").removeClass("hightlight");
that would enable you to toggle highlighting easily
Late to the game but you could alternatively just apply a python filter
to the result of a glob
:
files = glob.iglob('your_path_here')
files_i_care_about = filter(lambda x: not x.startswith("eph"), files)
or replacing the lambda with an appropriate regex search, etc...
EDIT: I just realized that if you're using full paths the startswith
won't work, so you'd need a regex
In [10]: a
Out[10]: ['/some/path/foo', 'some/path/bar', 'some/path/eph_thing']
In [11]: filter(lambda x: not re.search('/eph', x), a)
Out[11]: ['/some/path/foo', 'some/path/bar']
pack_forget
and grid_forget
will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy
method.
To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.
Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.
Before update SDK components, check in Android SDK Manager ? Tools ? Options and set HTTP proxy and port if it is set in local LAN.
Note that the if $myVar; then ... ;fi
construct has a security problem you might want to avoid with
case $myvar in
(true) echo "is true";;
(false) echo "is false";;
(rm -rf*) echo "I just dodged a bullet";;
esac
You might also want to rethink why if [ "$myvar" = "true" ]
appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case
solution is also handled without forks.
Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
Or on an actual device you can go to Settings -> Mobile Networks -> Preferred network types and chose the slowest available... Of course this is very limited, but for some test- purposes it might be enough.
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
This will work if you know the tree only has two levels:
for k1 in cars:
print(k1)
d = cars[k1]
for k2 in d
print(k2, ':', d[k2])
Check out Convert a string representation of a hex dump to a byte array using Java?
Disregarding encoding, etc. you can do new String (hexStringToByteArray("75546..."));
Run your script with .
. myscript.sh
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you say
FOO=1
export BAR=2
./runScript.sh
then $BAR
will be available in the environment of runScript.sh
, but $FOO
will not.
Well, I figured out the problem.
Basically Go starting path for import is $HOME/go/src
So I just needed to add myapp
in front of the package names, that is, the import should be:
import (
"log"
"net/http"
"myapp/common"
"myapp/routers"
)
Assuming that start_date is before end_date,
interval [start_date..end_date] NOT BETWEEN two dates simply means that either it starts before 2009-12-15 or it ends after 2010-01-02.
Then you can simply do
start_date<CAST('2009-12-15' AS DATE) or end_date>CAST('2010-01-02' AS DATE)
I have had this issue before, you need more than the standard 755
or 644
permission to store the $_SESSION
information. You need to be able to write to that file as that is how it remembers.
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
A complete C++ code example, may be helpful for the beginners
#include <iostream>
#include <string>
#include "opencv/highgui.h"
using namespace std;
using namespace cv;
int main()
{
cv:Mat M(102,201,CV_8UC1);
int rows = M.rows;
int cols = M.cols;
cout<<rows<<" "<<cols<<endl;
cv::Size sz = M.size();
rows = sz.height;
cols = sz.width;
cout<<rows<<" "<<cols<<endl;
cout<<sz<<endl;
return 0;
}
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
]4
Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.
If you want something which is much more simpler, go with InnoSetup.
I found a PHP class that let me do this server side. I just output an inline CSS color style for whatever I need to be lighter/darker. Works great.
http://www.barelyfitz.com/projects/csscolor/
(note that the class uses PEAR for throwing errors, but I didn't want to include PEAR just to modify colors, so I just removed all the PEAR references)
I turned it into a static class with static methods so I can call "lighten" & "darken" functions directly without creating a new object.
Sample usage:
$original_color = 'E58D8D';
$lighter_color = Css::lighten($original_color, .7);
$darker_color = Css::darken($original_color, .7);
In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd. These are the two you need to adjust.
In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it:
[users]
User1=password1
User2=password2
Then you want to assign permissions accordingly with the authz file:
Create the conceptual groups you want, and add people to it:
[groups]
allaccess = user1
someaccess = user2
Then choose what access they have from both the permissions and project level.
So let's give our "all access" guys all access from the root:
[/]
@allaccess = rw
But only give our "some access" guys read-only access to some lower level project:
[/someproject]
@someaccess = r
You will also find some simple documentation in the authz and passwd files.
The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.
.imagetest img {
transform: rotate(270deg);
...
margin: 10px 0px;
}
The amount will depend on the difference in height x width of the image.
You may also need to add display:inline-block;
or display:block
to get it to recognize the margin parameter.
No one here posted an answer with all of the correct CSS variations, so here it is:
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
From the HTML 4 spec:
If a form contains more than one submit button, only the activated submit button is successful.
This means that given more than 1 submit button and none activated (clicked), none should be successful.
And I'd argue this makes sense: Imagine a huge form with multiple submit-buttons. At the top, there is a "delete this record"-button, then lots of inputs follow and at the bottom there is an "update this record"-button. A user hitting enter while in a field at the bottom of the form would never suspect that he implicitly hits the "delete this record" from the top.
Therefore I think it is not a good idea to use the first or any other button it the user does not define (click) one. Nevertheless, browsers are doing it of course.
Contacts.add(objt.Data(name, address, contact));
This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.
The correct way is:
// object creation.
Data object1 = new Data(name, address, contact);
// adding Data object to ArrayList object Contacts.
Contacts.add(object1);
You can use <hr>
for a vertical line as well.
Set the width
to 1
and the size(height) as long as you want.
I used 500 in my example(demo):
With <hr width="1" size="500">
var getHtmlWeb = new HtmlWeb() { AutoDetectEncoding = false, OverrideEncoding = Encoding.GetEncoding("iso-8859-2") };
WebProxy myproxy = new WebProxy("127.0.0.1:8888", false);
NetworkCredential cred = (NetworkCredential)CredentialCache.DefaultCredentials;
var document = getHtmlWeb.Load("URL", "GET", myproxy, cred);
I didn't want to have to have the YouTube app present on the device so I used this tutorial:
http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html
...to produce this code in my app:
WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.video_webview);
mWebView=(WebView)findViewById(R.id.videoview);
//build your own src link with your video ID
String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
mWebView.loadData(videoStr, "text/html", "utf-8");
}
//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:background="#000000"
android:id="@+id/bmp_programme_ll"
android:orientation="vertical" >
<WebView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.
None of the older answers describe exit status 2 correctly. Contrary to what they claim, status 2 is what your command line utilities actually return when called improperly. (Yes, an answer can be nine years old, have hundreds of upvotes, and still be wrong.)
Here is the real, long-standing exit status convention for normal termination, i.e. not by signal:
For example, diff
returns 0 if the files it compares are identical, and 1 if they differ. By long-standing convention, unix programs return exit status 2 when called incorrectly (unknown options, wrong number of arguments, etc.) For example, diff -N
, grep -Y
or diff a b c
will all result in $?
being set to 2. This is and has been the practice since the early days of Unix in the 1970s.
The accepted answer explains what happens when a command is terminated by a signal. In brief, termination due to an uncaught signal results in exit status 128+[<signal number>
. E.g., termination by SIGINT
(signal 2) results in exit status 130.
Several answers define exit status 2 as "Misuse of bash builtins". This applies only when bash (or a bash script) exits with status 2. Consider it a special case of incorrect usage error.
In sysexits.h
, mentioned in the most popular answer, exit status EX_USAGE
("command line usage error") is defined to be 64. But this does not reflect reality: I am not aware of any common Unix utility that returns 64 on incorrect invocation (examples welcome). Careful reading of the source code reveals that sysexits.h
is aspirational, rather than a reflection of true usage:
* This include file attempts to categorize possible error * exit statuses for system programs, notably delivermail * and the Berkeley network. * Error numbers begin at EX__BASE [64] to reduce the possibility of * clashing with other exit statuses that random programs may * already return.
In other words, these definitions do not reflect the common practice at the time (1993) but were intentionally incompatible with it. More's the pity.
<div @click="f1() + f2()"></div>
<div @click="f3()"></div>
<script>
var app = new Vue({
// ...
methods: {
f3: function() { f1() + f2(); }
f1: function() {},
f2: function() {}
}
})
</script>
In case anyone's reading this and wanting to protect master
with client-side branch protection,
git branch -vv | grep "^\*" |grep -E '\* master |origin\/master'
will return 0
if either the local checked-out branch or its upstream remote branch is master
.
Just put this in your .git/hooks
directory's pre-commit
and update
files accordingly and Bob is your father's brother.
While Shannon's answer is technically correct, it looks like overkill.
The simple solution is that you need to put your summation outside of the case
statement.
This should do the trick:
sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product
Basically, your old code tells SQL to execute the sum(X*Y)
for each line individually (leaving each line with its own answer that can't be grouped).
The code line I have written takes the sum product, which is what you want.
One option would be
const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well. put the following below your body tag
<script>
$('#mainCat').on('change', function() {
let selected = $(this).val();
$("#expertCat option").each(function(){
let element = $(this) ;
if (element.data("tag") != selected){
element.removeClass('visible');
element.addClass('hidden');
element.hide() ;
}else{
element.removeClass('hidden');
element.addClass('visible');
element.show();
}
});
let expertCat = $('#expertCat');
expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>
#!/usr/bin/env bash
PHP=`which php`
$PHP /path/to/php/file.php
Just as a addition. You can find the Catalina Paths in
->RUN->RUN CONFIGURATIONS->APACHE TOMCAT->ARGUMENTS
In the VM Arguments the Paths are listed and changeable
One-liner using TestRestTemplate.exchange function with parameters map.
restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])
The params map initialized like this is a groovy initializer*
Another way(Must Try):
var promise1 = new Promise(function(resolve, reject) {_x000D_
resolve('Success!');_x000D_
});_x000D_
var extraData = 'ImExtraData';_x000D_
promise1.then(function(value) {_x000D_
console.log(value, extraData);_x000D_
// expected output: "Success!" "ImExtraData"_x000D_
}, extraData);
_x000D_
Xcode which is part of the MacOS Developer Tools is a great IDE. There's also NetBeans and Eclipse that can be configured to build and compile C++ projects.
Clion from JetBrains, also is available now, and uses Cmake as project model.
I'm hardly a caching expert, but Mark Nottingham is. Here are his caching docs. He also has excellent links in the References section.
Based on my reading of those docs, it looks like max-age=0
could allow the cache to send a cached response to requests that came in at the "same time" where "same time" means close enough together they look simultaneous to the cache, but no-cache
would not.
Use cut
:
cut -c6-
This prints each line of the input starting at column 6 (the first column is 1).
Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.
Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.
The best documentation you'll find on the topic is the virtual host documentation in the apache manual.
There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.
The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost
line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost
entry for each port.
Assuming you're starting from scratch, this is much simpler than it may seem.
If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.
NameVirtualHost *:80
If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost
directive, and it will be removed in a future version.
Now your vhost definitions:
<VirtualHost *:80>
DocumentRoot "/home/user/site1/"
ServerName site1
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "/home/user/site2/"
ServerName site2
</VirtualHost>
You can run as many sites as you want on the same port. The ServerName
being different is enough to tell Apache which vhost to use. Also, the ServerName
directive is always the domain/hostname and should never include a path.
If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81
Here is what worked for me while sending the file as mult-form data:
public T HttpPostMultiPartFileStream<T>(string requestURL, string filePath, string fileName)
{
string content = null;
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
StreamContent streamContent;
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
streamContent = new StreamContent(fileStream);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
streamContent.Headers.Add("Content-Disposition", string.Format("form-data; name=\"file\"; filename=\"{0}\"", fileName));
form.Add(streamContent, "file", fileName);
using (HttpClient client = GetAuthenticatedHttpClient())
{
HttpResponseMessage response = client.PostAsync(requestURL, form).GetAwaiter().GetResult();
content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
try
{
return JsonConvert.DeserializeObject<T>(content);
}
catch (Exception ex)
{
// Log the exception
}
return default(T);
}
}
}
}
GetAuthenticatedHttpClient used above can be:
private HttpClient GetAuthenticatedHttpClient()
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(<yourBaseURL>));
httpClient.DefaultRequestHeaders.Add("Token, <yourToken>);
return httpClient;
}
You can use this.props.children
to render whatever children the component contains:
const Wrap = ({ children }) => <div>{children}</div>
export default () => <Wrap><h1>Hello word</h1></Wrap>
Default arguments can not be used in Java. Where in C#, C++ and Python, we can use them..
In Java, we must have to use 2 methods (functions) instead of one with default parameters.
Example:
Stash(int size);
Stash(int size, int initQuantity);
If you want to do this in two steps, rather than the three of REVERSE-STUFF-REVERSE, you can have your list separator be one or two spaces. Then use RTRIM to trim the trailing spaces, and REPLACE to replace the double spaces with ','
select REPLACE(RTRIM('a b c d '),' ', ', ')
However, this is not a good idea if your original string can contain internal spaces.
Not sure about performance. Each REVERSE creates a new copy of the string, but STUFF is a third faster than REPLACE.
also see this
Gradle can be added on the Mac by adding the line below to ~/.bash_profile
. If the file doesn't exist, please use touch ~/.bash_profile
. This hidden file can be made visible in Finder by using Command + Shift + .
export PATH=${PATH}:/Applications/Android\ Studio.app/Contents/gradle/gradle-4.6/bin/
Use source ~/.bash_profile
to load the new path directly into your current terminal session.
If the page you are visiting is index.php, then your url should look like
http://localhost/test/content/home/ OR http://localhost/test/content/home/index.php
not the way you specified - http://localhost/test/content/home
Your questions:
Q 1.) I would like to know why it returns all the texts that following the div?
It should not and I think in will not. It returns all div with 'id' attribute value equal 'containter' (and all children of this). But you are printing the results with ele.getText()
Where getText will return all text content of all children of your result.
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
Q 2.) how should I modify the code so it just return first or first few nodes that follow the parent note
This is not really clear what you are looking for.
Example:
<p1> <div/> </p1 <p2/>
The following to parent of the div is p2. This would be:
//div[@id='container'][1]/parent::*/following-sibling::*
or shorter
//div[@id='container'][1]/../following-sibling::*
If you are only looking for the first one extent the expression with an "predicate"
(e.g [1]
- for the first one. or [position() < 4]
for the first three)
If your are looking for the first child of the first div:
//div[@id='container'][1]/*[1]
If there is only one div with id an you are looking for the first child:
//div[@id='container']/*[1]
and so on.
Use:
ii .
which is short for
Invoke-Item .
It is one of the most common things I type at the PowerShell command line.
with the webbrowser module
import webbrowser
webbrowser.open('http://example.com') # Go to example.com
Since there is a method on
SqlCommand.Parameters.AddWithValue(parameterName, value)
it might be more convenient to create a method accepting a parameter (name) to replace and a list of values. It is not on the Parameters level (like AddWithValue) but on command itself so it's better to call it AddParametersWithValues and not just AddWithValues:
query:
SELECT * from TableA WHERE Age IN (@age)
usage:
sqlCommand.AddParametersWithValues("@age", 1, 2, 3);
the extension method:
public static class SqlCommandExtensions
{
public static void AddParametersWithValues<T>(this SqlCommand cmd, string parameterName, params T[] values)
{
var parameterNames = new List<string>();
for(int i = 0; i < values.Count(); i++)
{
var paramName = @"@param" + i;
cmd.Parameters.AddWithValue(paramName, values.ElementAt(i));
parameterNames.Add(paramName);
}
cmd.CommandText = cmd.CommandText.Replace(parameterName, string.Join(",", parameterNames));
}
}
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
Morgan should not be used to log in the way you're describing. Morgan was built to do logging in the way that servers like Apache and Nginx log to the error_log or access_log. For reference, this is how you use morgan:
var express = require('express'),
app = express(),
morgan = require('morgan'); // Require morgan before use
// You can set morgan to log differently depending on your environment
if (app.get('env') == 'production') {
app.use(morgan('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/../morgan.log' }));
} else {
app.use(morgan('dev'));
}
Note the production line where you see morgan called with an options hash {skip: ..., stream: __dirname + '/../morgan.log'}
The stream
property of that object determines where the logger outputs. By default it's STDOUT (your console, just like you want) but it'll only log request data. It isn't going to do what console.log()
does.
If you want to inspect things on the fly use the built in util
library:
var util = require('util');
console.log(util.inspect(anyObject)); // Will give you more details than console.log
So the answer to your question is that you're asking the wrong question. But if you still want to use Morgan for logging requests, there you go.
Just wanted to illustrate, in the context of nested lists, the usefulness of the hidden checkbox <input>
approach @jeffmcneill recommends — a context where each shown/hidden element should hold its state independently of focus and the show/hide state of other elements on the page.
Giving values with a common set of beginning characters to the id
attributes of all the checkboxes used for the shown/hidden elements on the page lets you use an economical [id^=""]
selector scheme for the stylesheet rules that toggle your clickable element’s appearance and the related shown/hidden element’s display
state back and forth. Here, my id
s are ‘expanded-1,’ ‘expanded-2,’ ‘expanded-3.’
Note that I’ve also used @Diepen’s :after
selector idea in order to keep the <label>
element free of content in the html.
Note also that the <input>
<label>
<div class="collapsible">
sequence matters, and the corresponding CSS with +
selector instead of ~
.
.collapse-below {_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
p.collapse-below::after {_x000D_
content: '\000A0\000A0';_x000D_
}_x000D_
_x000D_
p.collapse-below ~ label {_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
p.collapse-below ~ label:hover {_x000D_
color: #ccc;_x000D_
}_x000D_
_x000D_
input.collapse-below,_x000D_
ul.collapsible {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:checked + label::after {_x000D_
content: '\025BE';_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:not(:checked) + label::after {_x000D_
content: '\025B8';_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:checked + label + ul.collapsible {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
input[id^="expanded"]:not(:checked) + label + ul.collapsible {_x000D_
display: none;_x000D_
}
_x000D_
<ul>_x000D_
<li>single item a</li>_x000D_
<li>single item b</li>_x000D_
<li>_x000D_
<p class="collapse-below" title="this expands">multiple item a</p>_x000D_
<input type="checkbox" id="expanded-1" class="collapse-below" name="toggle">_x000D_
<label for="expanded-1" title="click to expand"></label>_x000D_
<ul class="collapsible">_x000D_
<li>sub item a.1</li>_x000D_
<li>sub item a.2</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>single item c</li>_x000D_
<li>_x000D_
<p class="collapse-below" title="this expands">multiple item b</p>_x000D_
<input type="checkbox" id="expanded-2" class="collapse-below" name="toggle">_x000D_
<label for="expanded-2" title="click to expand"></label>_x000D_
<ul class="collapsible">_x000D_
<li>sub item b.1</li>_x000D_
<li>sub item b.2</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>single item d</li>_x000D_
<li>single item e</li>_x000D_
<li>_x000D_
<p class="collapse-below" title="this expands">multiple item c</p>_x000D_
<input type="checkbox" id="expanded-3" class="collapse-below" name="toggle">_x000D_
<label for="expanded-3" title="click to expand"></label>_x000D_
<ul class="collapsible">_x000D_
<li>sub item c.1</li>_x000D_
<li>sub item c.2</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')
like Vincent wrote, you can do something like this:
begin
open :yourCursor
for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
using :someFilterValue;
end;
You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.
Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )
Depending on which access library you use, it might be a royal pain or straight forward.
'[{"event":"inbound","ts":1426249238}]'
is a string, you cannot access any properties there. You will have to parse it to an object, with JSON.parse()
and then handle it like a normal object
I was catching GuzzleHttp\Exception\BadResponseException
as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException
when DNS for domain wasn't available.
So my suggestion is - catch GuzzleHttp\Exception\ConnectException
to be safe about DNS errors as well.
For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45
As administrative command prompt.
I just had this happen to me on a 'plain' CSV file. Some people might call it an invalid formatted file. No escape characters, no double quotes and delimiter was a semicolon.
A sample line from this file would look like this:
First cell; Second " Cell with one double quote and leading space;'Partially quoted' cell;Last cell
the single quote in the second cell would throw the parser off its rails. What worked was:
csv.reader(inputfile, delimiter=';', doublequote='False', quotechar='', quoting=csv.QUOTE_NONE)
Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.
Simplest solution and workaround:
<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">
setToRentControl(value){
this.vm.toRent.updateValue(value);
alert(value); //true/false
}
some sources prefere to use .env.development
and .env.production
but that's not obligatory.
it seems that if your environment variable does not start like that so you will have problems
to include your environment variable just put on your code process.env.REACT_APP_VARIABLE
You don't have to install any external dependency
If you can't use any libraries to encode the value, http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...
Just enter your value "M&M", not the full URL ;-)
(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)
Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.
For subdomains (like www.example.com
) you can use CNAME records pointing to your-app-name.herokuapp.com
. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com
so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)
Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com
is an HTTP redirect to www.example.com
.
Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.
Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):
@ IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.
Remember @
here is a shorthand for the root domain (example.com
). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.
Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.
Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.
I have created an Asset helper of my own.
First I defined the asset types and path in app/config/assets.php
:
return array(
/*
|--------------------------------------------------------------------------
| Assets paths
|--------------------------------------------------------------------------
|
| Location of all application assets, relative to the public folder,
| may be used together with absolute paths or with URLs.
|
*/
'images' => '/storage/images',
'css' => '/assets/css',
'img' => '/assets/img',
'js' => '/assets/js'
);
Then the actual Asset
class:
class Asset
{
private static function getUrl($type, $file)
{
return URL::to(Config::get('assets.' . $type) . '/' . $file);
}
public static function css($file)
{
return self::getUrl('css', $file);
}
public static function img($file)
{
return self::getUrl('img', $file);
}
public static function js($file)
{
return self::getUrl('js', $file);
}
}
So in my view I can do this to show an image:
{{ HTML::image(Asset::img('logo.png'), "My logo")) }}
Or like this to implement a Java script:
{{ HTML::script(Asset::js('my_script.js')) }}
A hacky way of doing JSON_UNESCAPED_UNICODE in PHP 5.3. Really disappointed by PHP json support. Maybe this will help someone else.
$array = some_json();
// Encode all string children in the array to html entities.
array_walk_recursive($array, function(&$item, $key) {
if(is_string($item)) {
$item = htmlentities($item);
}
});
$json = json_encode($array);
// Decode the html entities and end up with unicode again.
$json = html_entity_decode($rson);
I have this same requirement - we want to put logs in a specific root directory that should exist within the environment.
public static readonly string DefaultLogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
If I want to combine this with a sub-directory, I should be able to use Path.Combine( ... )
.
The GetFolderPath
method has an overload for special folder options which allows you to control whether the specified path be created or simply verified.
Try this:
$("a").each(function() {
if ($('[href$="?"]', this).length()) {
alert("Contains questionmark");
}
});
In Preferences -> General -> Web Browser, there is the option "Use internal web browser". Select "Use external web browser" instead and check "Firefox".
partition() may be better then split() for this purpose as it has the better predicable results for situations you have no delimiter or more delimiters.
For retrieving the screen resolution, you're going to want to use the System.Windows.Forms.Screen
class. The Screen.AllScreens
property can be used to access a collection of all of the displays on the system, or you can use the Screen.PrimaryScreen
property to access the primary display.
The Screen
class has a property called Bounds
, which you can use to determine the resolution of the current instance of the class. For example, to determine the resolution of the current screen:
Rectangle resolution = Screen.PrimaryScreen.Bounds;
For changing the resolution, things get a little more complicated. This article (or this one) provides a detailed implementation and explanation. Hope this helps.
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[@type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
window.onload = prepareButton;
function prepareButton()
{
document.getElementById('foo').onclick = function()
{
alert('you clicked me');
}
}
<input id="foo" value="Click Me!" type="button" />
Either as most people answered: the file doesn't exist / you're not specifying the path correctly.
Or, you're simply writing the syntax wrong (which you can't know unless you know what it should be like, right?, especially when in the "help" itself, it's wrong).
For gnuplot 4.6.0 on windows 7, terminal type set to windows
Make sure you specify the file's whole path to avoid looking for it where it's not (default seems to be "documents")
Make sure you use this syntax:
plot 'path\path\desireddatafile.txt'
NOT
plot "< path\path\desireddatafile.txt>"
NOR
plot "path\path\desireddatafile.txt"
also make sure your file is in the right format, like for .txt file format ANSI, not Unicode and such.
As Obama says "Yes We Can". Here is the link to it. developers.google.com/#jquery
You need to use
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/jquery-ui.min.js
ajax.googleapis.com/ajax/libs/jqueryui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
jQuery CDN
code.jquery.com/ui/[VERSION NO]/jquery-ui.min.js
code.jquery.com/ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Microsoft
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/jquery-ui.min.js
ajax.aspnetcdn.com/ajax/jquery.ui/[VERSION NO]/themes/[THEME NAME]/jquery-ui.min.css
Find theme names here http://jqueryui.com/themeroller/ in gallery subtab
.
But i would not recommend you hosting from cdn for the following reasons
http://zoompf.com/blog/2010/01/should-you-use-javascript-library-cdns
Just install libpq-dev
$ sudo apt-get install libpq-dev
One more thing that could cause this is having incorrect version
of the <parent>
project.
In my case it was pointing to a non-existing project and for some reason IntelliJ downgraded version in settings to 1.5 and later when I fixed it, it was still interpreting target code version as 5 (despite setting it to 11).
var listItems= "";
var jsonData = jsonObj.d;
for (var i = 0; i < jsonData.Table.length; i++){
listItems+= "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
$("#<%=DLState.ClientID%>").html(listItems);
Example
<html>
<head></head>
<body>
<select id="DLState">
</select>
</body>
</html>
/*javascript*/
var jsonList = {"Table" : [{"stateid" : "2","statename" : "Tamilnadu"},
{"stateid" : "3","statename" : "Karnataka"},
{"stateid" : "4","statename" : "Andaman and Nicobar"},
{"stateid" : "5","statename" : "Andhra Pradesh"},
{"stateid" : "6","statename" : "Arunachal Pradesh"}]}
$(document).ready(function(){
var listItems= "";
for (var i = 0; i < jsonList.Table.length; i++){
listItems+= "<option value='" + jsonList.Table[i].stateid + "'>" + jsonList.Table[i].statename + "</option>";
}
$("#DLState").html(listItems);
});
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
If you want to update to latest version and you don't know what is the latest version you can type.
pip install MySQL_python --upgrade
This will update the MySQL_python for latest version available, you can use for any other package version.
All commands must be executed while connected to the right database in the right database cluster. Make sure of it.
The user needs access to the database, obviously:
GRANT CONNECT ON DATABASE my_db TO my_user;
And (at least) the USAGE
privilege on the schema:
GRANT USAGE ON SCHEMA public TO my_user;
Or grant USAGE
on all custom schemas:
DO
$$
BEGIN
-- RAISE NOTICE '%', ( -- use instead of EXECUTE to see generated commands
EXECUTE (
SELECT string_agg(format('GRANT USAGE ON SCHEMA %I TO my_user', nspname), '; ')
FROM pg_namespace
WHERE nspname <> 'information_schema' -- exclude information schema and ...
AND nspname NOT LIKE 'pg\_%' -- ... system schemas
);
END
$$;
Then, all permissions for all tables (requires Postgres 9.0 or later).
And don't forget sequences (if any):
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO my_user;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO my_user;
For older versions you could use the "Grant Wizard" of pgAdmin III (the default GUI).
There are some other objects, the manual for GRANT
has the complete list as of Postgres 12:
privileges on a database object (table, column, view, foreign table, sequence, database, foreign-data wrapper, foreign server, function, procedure, procedural language, schema, or tablespace)
But the rest is rarely needed. More details:
Consider upgrading to a current version.
Try this
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside).
Just add parenthesis with name of method.
Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'
This is worked for me, anyone can try it
$("#myModal").on("hidden.bs.modal", function () {
for (instance in CKEDITOR.instances)
CKEDITOR.instances[instance].destroy();
$('#myModal .modal-body').html('');
});
you can open ckEditor in Modal window
You have more static resources that the cache has room for. You can do one of the following:
For more details see the documentation for these configuration options.
you can download bjam for OSX (or any other OS) here
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
If you include all files of *.js in directory example ("app/lib/*.js"):
example.js:
module.exports = function (example) { }
example-2.js:
module.exports = function (example2) { }
index.js:
module.exports = require('./app/lib');
The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.
Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:
See if you can get away with just #1, since the second requires a bit of command line work.
To add the custom header in #1:
If you need to continue and do #2, then you'll need a command line with CURL
curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0
From the results returned, extract the values for X-Auth-Token and X-Storage-Url
curl -X POST \
-H "Content-Type: font/woff" \
--header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff
curl -X POST \
-H "Content-Type: font/ttf" \
--header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf
Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).
If you don't know the order of the min/max values
Date a, b; // assume these are set to something
Date d; // the date in question
return a.compareTo(d) * d.compareTo(b) > 0;
If you want the range to be inclusive
return a.compareTo(d) * d.compareTo(b) >= 0;
You can actually disable all database constraints in a single SQL command and the re-enable them calling another single command. See:
I am currently working with SQL Server 2005 but I am almost sure that this approach worked with SQL 2000 as well
I fond this YouTube video from Google where are some tips and tricks for it. The video also includes advantages and disadvantages of suggested changes.
Improving Android Studio Performance on Memory-Constrained Machines
This is more Effective way to count frequency of characters in a string
public class demo {
public static void main(String[] args) {
String s = "babdcwertyuiuygf";
Map<Character, Integer> map = new TreeMap<>();
s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
StringBuffer myValue = new StringBuffer();
String myMapKeyValue = "";
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
myMapKeyValue = Character.toString(entry.getKey()).concat(
Integer.toString(entry.getValue()));
myValue.append(myMapKeyValue);
}
System.out.println(myValue);
}
}
This worked for me:
location / {
alias /path/to/my/indexfile/;
try_files $uri /index.html;
}
This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build
will be found if they are in the same directory as index.html
.
If the static files were in another directory, for some reason, you'd also need something like:
# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
alias /path/to/my/staticfiles/;
}
var coordinates = [jsonObject[3][0],
jsonObject[3][0],
jsonObject[4][1],
jsonObject[4][1]];
Maybe this is helpful, too.
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:
using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
{
SPList oList = oWeb.Lists["Announcements"];
// You may also use
// SPList oList = oWeb.GetList("/Lists/Announcements");
// to avoid querying all of the sites' lists
SPListItem oListItem = oList.Items.Add();
oListItem["Title"] = "My Item";
oListItem["Created"] = new DateTime(2004, 1, 23);
oListItem["Modified"] = new DateTime(2005, 10, 1);
oListItem["Author"] = 3;
oListItem["Editor"] = 3;
oListItem.Update();
}
}
Source: SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.
Your regex pattern needs to be in delimiters:
$numpattern="/^([0-9]+)$/";
If you using v1.3.3 then use following property
autoPlay : 5000
Or using latest version then use following property
autoPlay : true
You can use jQuery plugin with the inview
event like this :
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
In Java reading and writing fields of all types except long and double occurs atomically, and if the field is declared with the volatile modifier, even long and double are atomically read and written. That is, we get 100% either what was there, or what happened there, nor can there be any intermediate result in the variables.
If the way you determine whether or not an entity has a profile is a deterministic function, and doesn't require any access to another table, you could write a stored function and define a computed, persisted field which would store that value for you and not have to re-compute it over and over again.
If you need to query a separate table (to e.g. check the existance of a row), you could still make this "HasProfile" a column in your entity table and just compute that field on a regular basis, e.g. every night or so. If you have the value stored as an atomic value, you don't need the computation every time. This works as long as that fact - has a profile or not - doesn't change too frequently.
To add a column to check whether or not EntityProfile
is empty, do something like this:
CREATE FUNCTION CheckHasProfile(@Field VARCHAR(MAX))
RETURNS BIT
WITH SCHEMABINDING
AS BEGIN
DECLARE @Result BIT
IF @Field IS NULL OR LEN(@Field) <= 0
SET @Result = 0
ELSE
SET @Result = 1
RETURN @Result
END
and then add a new computed column to your table Entity
:
ALTER TABLE dbo.Entity
ADD HasProfile AS dbo.CheckHasProfile(EntityProfile) PERSISTED
Now you have a BIT column and it's persisted, e.g. doesn't get computed every time to access the row, and should perform just fine!
If you want multiple string replacement:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
In react-router v2.4.0
or above and before v4
there are several options
<Route
path="/home"
onEnter={ auth }
onLeave={ showConfirm }
component={ Home }
>
You can prevent a transition from happening or prompt the user before leaving a route with a leave hook.
const Home = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
},
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
// return `null` or nothing to let other hooks to be executed
//
// NOTE: if you return true, other hooks will not be executed!
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
},
// ...
})
)
Note that this example makes use of the withRouter
higher-order component introduced in v2.4.0.
However these solution doesn't quite work perfectly when changing the route in URL manually
In the sense that
For react-router v4
using Prompt or custom history:
However in react-router v4
, its rather easier to implement with the help of Prompt
from'react-router
According to the documentation
Prompt
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a
<Prompt>
.import { Prompt } from 'react-router' <Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?" />
message: string
The message to prompt the user with when they try to navigate away.
<Prompt message="Are you sure you want to leave?"/>
message: func
Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
<Prompt message={location => ( `Are you sure you want to go to ${location.pathname}?` )}/>
when: bool
Instead of conditionally rendering a
<Prompt>
behind a guard, you can always render it but passwhen={true}
orwhen={false}
to prevent or allow navigation accordingly.
In your render method you simply need to add this as mentioned in the documentation according to your need.
UPDATE:
In case you would want to have a custom action to take when user is leaving page, you can make use of custom history and configure your Router like
history.js
import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()
...
import { history } from 'path/to/history';
<Router history={history}>
<App/>
</Router>
and then in your component you can make use of history.block
like
import { history } from 'path/to/history';
class MyComponent extends React.Component {
componentDidMount() {
this.unblock = history.block(targetLocation => {
// take your action here
return false;
});
}
componentWillUnmount() {
this.unblock();
}
render() {
//component render here
}
}
If you're interested in producing HTML5 hybrid applications (web apps wrapped in a native container giving access to device functions), the Nomad Visual Studio extension supports building for android devices.
This is to help lodash
users. check if your key is present by doing:
hideSelectedCompany(yourKey) {
return _.findIndex(yourArray, n => n === yourKey) === -1;
}
Adding on to Josh's answer,
SELECT COUNT(CASE WHEN myColumn=1 THEN AD_CurrentView.PrimaryKeyColumn ELSE NULL END)
FROM AD_CurrentView
Worked well for me (in SQL Server 2012) without changing the 'count' to a 'sum' and the same logic is portable to other 'conditional aggregates'. E.g., summing based on a condition:
SELECT SUM(CASE WHEN myColumn=1 THEN AD_CurrentView.NumberColumn ELSE 0 END)
FROM AD_CurrentView
If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?
In SQL2008 BOL they say that in next releases semicolons will be required. Therefore, always use it.
Reference:
There are many anwers in this question, probably all will give you the answer you are looking for. But as @TallGreenTree mentions, there is a function for this.
But the problem of the answer of @TallGreenTree is that it doesn't round up, it rounds to the nearest 10. To solve this, add +5
to your number in order to round up. If you want to round down, do -5
.
So in code:
round($num + 5, -1);
You can't use the round mode
for rounding up, because that only rounds up fractions and not whole numbers.
If you want to round up to the nearest 100
, you shoud use +50
.
use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.
Also, explorer will stop if there is a particular problem with a file,
This is alternative of brad anser - you can use comma as follows
onclick="funA(), funB(), ..."
however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).
function funA() {_x000D_
console.log('A');_x000D_
}_x000D_
_x000D_
function funB(clickedElement) {_x000D_
console.log('B: ' + clickedElement.innerText);_x000D_
}_x000D_
_x000D_
function funC(cilckEvent) {_x000D_
console.log('C: ' + cilckEvent.timeStamp);_x000D_
}
_x000D_
div {cursor:pointer}
_x000D_
<div onclick="funA(), funB(this), funC(event)">Click me</div>
_x000D_
Just in case any one interested in the one line version. :)
//or in typescript: import * as fs from 'fs';
const fs = require('fs');
!fs.existsSync(dir) && fs.mkdirSync(dir);
Adding the below code helped me overcome the issue.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
I am using Ubuntu and my sessions are stored in /var/lib/php5.
I did not like having to add in the 1 second stall to all of the PerformanceCounter
solutions. Instead I chose to use a WMI
solution. The reason the 1 second wait/stall exists is to allow the reading to be accurate when using a PerformanceCounter
. However if you calling this method often and refreshing this information, I'd advise not to constantly have to incur that delay... even if thinking of doing an async process to get it.
I started with the snippet from here Returning CPU usage in WMI using C# and added a full explanation of the solution on my blog post below:
This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.
pros:
cons:
Commented and runable example of batch-ps-script.cmd:
<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script
# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"
# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
Write-Host "Exit script..."
break
}
# example: call standard powershell command
Get-Item .
Snippet for .cmd file:
<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
The conversion to list
that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:
sum(1 for x in generator)
Of course, be aware that this might be slower than len(list(generator))
in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).
Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.
If you use InnoDB and defined FK's you could query the information_schema database e.g.:
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';
The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option "Redirect input from" and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error "no module named x":
When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:
I found this question looking to change the timezone in my Django project's settings.py
file to the United Kingdom.
Using the tz database in jfs' solution I found the answer:
TIME_ZONE = 'Europe/London'
In my case I needed to raise an exception so I did:
class UnableToStripEnd(Exception):
"""A Exception type to indicate that the suffix cannot be removed from the text."""
@staticmethod
def get_exception(text, suffix):
return UnableToStripEnd("Could not find suffix ({0}) on text: {1}."
.format(suffix, text))
def strip_end(text, suffix):
"""Removes the end of a string. Otherwise fails."""
if not text.endswith(suffix):
raise UnableToStripEnd.get_exception(text, suffix)
return text[:len(text)-len(suffix)]
As stated in other answers, label is an inline element. However, you can apply display: inline-block
to the label and then center with text-align
.
#name_label {
display: inline-block;
width: 90%;
text-align: right;
}
Why display: inline-block
and not display: inline
? For the same reason that you can't align label
, it's inline.
Why display: inline-block
and not display: block
? You could use display: block
, but it will be on another line. display: inline-block
combines the properties of inline
and block
. It's inline, but you can also give it a width, height, and align it.
Given a dataset
df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'),
occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )
you can subset rows
df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts
etc.
If you want to get number of rows, just call the function nrow
such as
nrow(df[df$sex == 'M',])
I find the small utility AsmSpy an invaluable tool to for resolving issues with loading assemblies. It lists all assembly references of managed assemblies including assembly versions.
Run it in a command prompt in the directory of the .dll
with the following arguments:
asmspy . all
Install it quickly with Chocolatey:
choco install asmspy
As you have already marked everything as a module, there's no need to use the relative reference if you launch as python module.
Instead of
from ..components.core import GameLoopEvents
simply
from pkg.components.core import GameLoopEvents
When you run from the parent of pkg, use the following
python -m pkg.tests.core_test
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
I think this comes closest to what you wish:
(From IntelliJ IDEA Q&A for Eclipse Users):
The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.
Things to do:
Switch to 'Problems' view in the Project pane:
Enable the setting to compile the project automatically :
Finally, look at the Problems view:
Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:
Relevant Links:
The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122
i had the same problem i resolve it by removing files that i added in the assets folder and those files name contains insupported characteres like "é" , " ", "ï" "è"... by renaming those name files or removing them you will have no problem.
Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.
So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.
Typically you add a class selector to the :not()
pseudo-class like so:
:not(.printable) {
/* Styles */
}
:not([attribute]) {
/* Styles */
}
But if you need better browser support (IE8 and older don't support :not()
), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.
Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable
, or otherwise affect them one way or another. For example, although display
is not inherited, setting display: none
on a :not(.printable)
will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden
instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
Try redis, it is one of the cleanest and easiest solutions for applications to share data in a atomic way or if you have got some web server platform. Its very easy to setup, you will need a python redis client http://pypi.python.org/pypi/redis
You can use
window.top
see the following.
<head>
<script>
function abc() {
alert("sss");
}
</script>
</head>
<body>
<iframe id="myFrame">
<a onclick="window.top.abc();" href="#">Click Me</a>
</iframe>
</body>
Other answers already explained that this isn't possible using the encoding/json
package features directly.
Instead, I'd like to offer an alternative solution using a third-party library. Disclaimer: I am the author of the library.
https://github.com/wI2L/jettison
Jettison is a faster and flexible alternative to encoding/json, while still retaining a behavior identical to the standard library by default.
You can use the DenyList
option to filter-out fields that should be omitted from the result. Note that the feature is limited, and only works for 1st-level fields.
Flex answer
.div1 {
width:300px;
background-color: grey;
border:1px solid;
overflow:auto;
display: flex;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
}
Check the fiddle at http://jsfiddle.net/germangonzo/E4Zgj/575/
You don't have to change it in the jquery-ui css file (it can be confusing if you change the default files), it is enough if you add
div.ui-datepicker{
font-size:10px;
}
in a stylesheet loaded after the ui-files
div.ui-datepicker is needed in case ui-widget is mentioned after ui-datepicker in the declaration
As I understand, if have id's: 1,2,4,5 it should return 3.
SELECT t1.id + 1
FROM theTable t1
WHERE NOT EXISTS (
SELECT *
FROM theTable t2
WHERE t2.id = t1.id + 1
)
LIMIT 1
This task can also be solved with a different approach. Instead of programming a converter and enlarging the code in the XAML, you can also aggregate the various parameters in the ViewModel. As a result, the ViewModel then has one more property that contains all parameters.
An example of my current application, which also let me deal with the topic. A generic RelayCommand is required: https://stackoverflow.com/a/22286816/7678085
The ViewModelBase is extended here by a command SaveAndClose. The generic type is a named tuple that represents the various parameters.
public ICommand SaveAndCloseCommand => saveAndCloseCommand ??= new RelayCommand<(IBaseModel Item, Window Window)>
(execute =>
{
execute.Item.Save();
execute.Window?.Close(); // if NULL it isn't closed.
},
canExecute =>
{
return canExecute.Item?.IsItemValide ?? false;
});
private ICommand saveAndCloseCommand;
Then it contains a property according to the generic type:
public (IBaseModel Item, Window Window) SaveAndCloseParameter
{
get => saveAndCloseParameter ;
set
{
SetProperty(ref saveAndCloseParameter, value);
}
}
private (IBaseModel Item, Window Window) saveAndCloseParameter;
The XAML code of the view then looks like this: (Pay attention to the classic click event)
<Button
Command="{Binding SaveAndCloseCommand}"
CommandParameter="{Binding SaveAndCloseParameter}"
Click="ButtonApply_Click"
Content="Apply"
Height="25" Width="100" />
<Button
Command="{Binding SaveAndCloseCommand}"
CommandParameter="{Binding SaveAndCloseParameter}"
Click="ButtonSave_Click"
Content="Save"
Height="25" Width="100" />
and in the code behind of the view, then evaluating the click events, which then set the parameter property.
private void ButtonApply_Click(object sender, RoutedEventArgs e)
{
computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, null);
}
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
computerViewModel.SaveAndCloseParameter = (computerViewModel.Computer, this);
}
Personally, I think that using the click events is not a break with the MVVM pattern. The program flow control is still located in the area of ??the ViewModel.
IF you are using Gradle you can use the build.gradle file to programmatically add value to the xml resources at compile time.
Example Code extracted from: https://medium.com/@manas/manage-your-android-app-s-versioncode-versionname-with-gradle-7f9c5dcf09bf
buildTypes {
debug {
versionNameSuffix ".debug"
resValue "string", "app_version", "${defaultConfig.versionName}${versionNameSuffix}"
}
release {
resValue "string", "app_version", "${defaultConfig.versionName}"
}
}
now use @string/app_version
as needed in XML
It will add .debug
to the version name as describe in the linked article when in debug mode.
Centralized DLL library.
With .Net Core it is now very easy:
You'll want to use the GetExtensionName method on the FileSystemObject object.
Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")
In your example, try using this
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
It isn't exactly a ZIP, but the only way to compress a file using Windows tools is:
makecab <source> <dest>.cab
To decompress:
expand <source>.cab <dest>
Advanced example (from ss64.com):
Create a self extracting archive containing movie.mov:
C:\> makecab movie.mov "temp.cab"
C:\> copy /b "%windir%\system32\extrac32.exe"+"temp.cab" "movie.exe"
C:\> del /q /f "temp.cab"
More information: makecab, expand, makecab advanced uses
In the endpoint tag you need to include the property address=""
<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />
Even though this question asked is old, note that changing a UUID on a virtual HDD in a windows system will make windows treat it as a not activated machine (as it notices the disk change) and will ask for reactivation !
With my pymongo version: 3.2.2 I had do the following
from bson.objectid import ObjectId
import pymongo
client = pymongo.MongoClient("localhost", 27017)
db = client.mydbname
db.ProductData.update_one({
'_id': ObjectId(p['_id']['$oid'])
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False)
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
For WinRT (Windows Store App)
using Windows.UI;
using Windows.UI.Xaml.Media;
public static Brush ColorToBrush(string color) // color = "#E7E44D"
{
color = color.Replace("#", "");
if (color.Length == 6)
{
return new SolidColorBrush(ColorHelper.FromArgb(255,
byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
}
else
{
return null;
}
}
If you are using PHP, try using <?php flush(); ?>
after </head>
and before </body>
or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.
An alternative to the answer provided by @Marc
SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
CHARINDEX(';', YOUR_FIELD) > 0;
This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.
For those doing video I cobbled the following based on @tsh :
import cv2 as cv
import numpy as np
def nothing(x):pass
cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)
while(True):
ret, frame = cap.read()
vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
thresh = cv.getTrackbarPos('T','videoUI');
vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]
cv.imshow('videoUI',cv.flip(vid_bw,1))
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Results in:
Using empty
is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE
.
Check for the value of the parameter:
// .NET < 4.0
if (string.IsNullOrEmpty(Request.QueryString["aspxerrorpath"]))
{
// not there!
}
// .NET >= 4.0
if (string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"]))
{
// not there!
}
If it does not exist, the value will be null
, if it does exist, but has no value set it will be an empty string.
I believe the above will suit your needs better than just a test for null
, as an empty string is just as bad for your specific situation.
(for fellow googlers)
If you are building a serious pipeline with the Build Flow Plugin, you can pass parameters between jobs with the DSL like this :
Supposing an available string parameter "CVS_TAG", in order to pass it to other jobs :
build("pipeline_begin", CVS_TAG: params['CVS_TAG'])
parallel (
// will be scheduled in parallel.
{ build("pipeline_static_analysis", CVS_TAG: params['CVS_TAG']) },
{ build("pipeline_nonreg", CVS_TAG: params['CVS_TAG']) }
)
// will be triggered after previous jobs complete
build("pipeline_end", CVS_TAG: params['CVS_TAG'])
Hint for displaying available variables / params :
// output values
out.println '------------------------------------'
out.println 'Triggered Parameters Map:'
out.println params
out.println '------------------------------------'
out.println 'Build Object Properties:'
build.properties.each { out.println "$it.key -> $it.value" }
out.println '------------------------------------'
if you want that not contains any of a-z and A-Z:
SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')
something like:
"98763045098" or "!%436%$7%$*#"
or other languages like persian, arabic and ... like this:
"???? ????"
Not straightforward, but it works:
> t(sapply(a, unlist))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.