Programs & Examples On #Cron

Cron is a time-based job scheduler running as a daemon process in Unix-like computer operating systems.

Cron job every three days

Because cron is "stateless", it cannot accurately express "frequencies", only "patterns" which it (apparently) continuously matches against the current time.

Rephrasing your question makes this more obvious: "is it possible to run a cronjob at 00:01am every night except skip nights when it had run within 2 nights?" When cron is comparing the current time to job request time patterns, there's no way cron can know if it ran your job in the past.

(it certainly is possible to write a stateful cron that records past jobs and thus includes patterns for matching against this state, but that's not the standard cron included in most operating systems. Such a system would get complicated by requiring the introduction of the concept of when such patterns "reset". For example, is the pattern reset when the time is changed (i.e. the crontab entry is revised)? Look to your favorite calendar app to see how complicated it can get to express Repeating patterns of scheduled events, and note that they don't have the reset problem because the starting calendar event has a natural "start" a/k/a "reset" date. Try rescheduling an every-other-week recurring calendar event to postpone by a week, over christmas for example. Usually you have to terminate that recurring event and restart a completely new one; this illustrates the limited expressivity of how even complicated calendar apps represent repeating patterns. And of course Calendars have a lot of state-- each individual event can be deleted or rescheduled independently [in most calendar apps]).

Further, you probably want to do your job every 3rd night if successful, but if the last one failed, to try again immediately, perhaps the next night (not wait 3 more days) or even sooner, like an hour later (but stop retrying upon morning's arrival). Clearly, cron couldn't possibly know if your job succeeded and the pattern can't also express an alternate more frequent "retry" schedule.

ANYWAY-- You can do what you want yourself. Write a script, tell cron to run it nightly at 00:01am. This script could check the timestamp of something* which records the "last run", and if it was >3 days ago**, perform the job and reset the "last run" timestamp.

(*that timestamped indicator is a bit of persisted state which you can manipulate and examine, but which cron cannot)

**be careful with time arithmetic if you're using human-readable clock time-- twice a year, some days have 23 or 25 hours in their day, and 02:00-02:59 occurs twice in one day or not at all. Use UTC to avoid this.

What is the Windows version of cron?

Not exactly a Windows version, however you can use Cygwin's crontab. For install instructions, see here: here.

Running a cron every 30 seconds

No need for two cron entries, you can put it into one with:

* * * * * /bin/bash -l -c "/path/to/executable; sleep 30 ; /path/to/executable"

so in your case:

* * * * * /bin/bash -l -c "cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'' ; sleep 30 ; cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''"

Spring cron expression for every after 30 minutes

Graphically, the cron syntax for Quarz is (source):

+-------------------- second (0 - 59)
|  +----------------- minute (0 - 59)
|  |  +-------------- hour (0 - 23)
|  |  |  +----------- day of month (1 - 31)
|  |  |  |  +-------- month (1 - 12)
|  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
|  |  |  |  |  |  +-- year [optional]
|  |  |  |  |  |  |
*  *  *  *  *  *  * command to be executed 

So if you want to run a command every 30 minutes you can say either of these:

0 0/30 * * * * ?
0 0,30 * * * * ?

You can check crontab expressions using either of these:

  • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
  • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

Run cron job only if it isn't already running

I do this for a print spooler program that I wrote, it's just a shell script:

#!/bin/sh
if ps -ef | grep -v grep | grep doctype.php ; then
        exit 0
else
        /home/user/bin/doctype.php >> /home/user/bin/spooler.log &
        #mailing program
        /home/user/bin/simplemail.php "Print spooler was not running...  Restarted." 
        exit 0
fi

It runs every two minutes and is quite effective. I have it email me with special information if for some reason the process is not running.

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

Spring cron expression for every day 1:01:am

For my scheduler, I am using it to fire at 6 am every day and my cron notation is:

0 0 6 * * *

If you want 1:01:am then set it to

0 1 1 * * *

Complete code for the scheduler

@Scheduled(cron="0 1 1 * * *")
public void doScheduledWork() {
    //complete scheduled work
}

** VERY IMPORTANT

To be sure about the firing time correctness of your scheduler, you have to set zone value like this (I am in Istanbul):

@Scheduled(cron="0 1 1 * * *", zone="Europe/Istanbul")
public void doScheduledWork() {
    //complete scheduled work
}

You can find the complete time zone values from here.

Note: My Spring framework version is: 4.0.7.RELEASE

Linux shell script for database backup

Here is my mysql backup script for ubuntu in case it helps someone.

#Mysql back up script

start_time="$(date -u +%s)"

now(){
date +%d-%B-%Y_%H-%M-%S
}

ip(){
/sbin/ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'
}

filename="`now`".zip
backupfolder=/path/to/any/folder
fullpathbackupfile=$backupfolder/$filename
db_user=xxx
db_password=xxx
db_name=xxx

printf "\n\n"
printf "******************************\n"
printf "Started Automatic Mysql Backup\n"
printf "******************************\n"
printf "TIME: `now`\n"
printf "IP_ADDRESS: `ip` \n"
printf "DB_SERVER_NAME: DB-SERVER-1\n"

printf "%sBACKUP_FILE_PATH $fullpathbackupfile\n"

printf "Starting Mysql Dump \n"

mysqldump -u $db_user -p$db_password $db_name| pv | zip > $fullpathbackupfile

end_time="$(date -u +%s)"

elapsed=$(($end_time-$start_time))

printf "%sMysql Dump Completed In $elapsed seconds\n"

printf "******************************\n"

PS: Rememember to install pv and zip in your ubuntu

sudo apt install pv
sudo apt install zip

Here is how I set crontab by using crontab -e in ubuntu to run every 6 hours

0 */6 * * * sh /path/to/shfile/backup-mysql.sh >> /path/to/logs/backup-mysql.log 2>&1

Cool thing is it will create a zip file which is easier to unzip from anywhere

How to run a Python script in the background even after I logout SSH?

If you've already started the process, and don't want to kill it and restart under nohup, you can send it to the background, then disown it.

Ctrl+Z (suspend the process)

bg (restart the process in the background

disown %1 (assuming this is job #1, use jobs to determine)

How do I set up cron to run a file just once at a specific time?

Try this out to execute a command on 30th March 2011 at midnight:

0 0 30 3 ? 2011  /command

WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.

CronJob not running

I found useful debugging information on an Ubuntu 16.04 server by running:

systemctl status cron.service

In my case I was kindly informed I had left a comment '#' off of a remark line:

Aug 18 19:12:01 is-feb19 cron[14307]: Error: bad minute; while reading /etc/crontab
Aug 18 19:12:01 is-feb19 cron[14307]: (*system*) ERROR (Syntax error, this crontab file will be ignored)

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Does WGET timeout?

Since in your question you said it's a PHP script, maybe the best solution could be to simply add in your script:

ignore_user_abort(TRUE);

In this way even if wget terminates, the PHP script goes on being processed at least until it does not exceeds max_execution_time limit (ini directive: 30 seconds by default).

As per wget anyay you should not change its timeout, according to the UNIX manual the default wget timeout is 900 seconds (15 minutes), whis is much larger that the 5-6 minutes you need.

How do I create a crontab through a script

Well /etc/crontab just an ascii file so the simplest is to just

 echo "*/15 * * * *   root     date" >> /etc/crontab

which will add a job which will email you every 15 mins. Adjust to taste, and test via grep or other means whether the line was already added to make your script idempotent.

On Ubuntu et al, you can also drop files in /etc/cron.* which is easier to do and test for---plus you don't mess with (system) config files such as /etc/crontab.

A cron job for rails: best practices?

Using something Sidekiq or Resque is a far more robust solution. They both support retrying jobs, exclusivity with a REDIS lock, monitoring, and scheduling.

Keep in mind that Resque is a dead project (not actively maintained), so Sidekiq is a way better alternative. It also is more performant: Sidekiq runs several workers on a single, multithread process while Resque runs each worker in a separate process.

Restarting cron after changing crontab file?

try this one for centos 7 : service crond reload

How to create a Java cron job

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

Setting up a cron job in Windows

  1. Make sure you logged on as an administrator or you have the same access as an administrator.
  2. Start->Control Panel->System and Security->Administrative Tools->Task Scheduler
  3. Action->Create Basic Task->Type a name and Click Next
  4. Follow through the wizard.

How do I list all cron jobs for all users?

A small refinement of Kyle Burton's answer with improved output formatting:

#!/bin/bash
for user in $(cut -f1 -d: /etc/passwd)
do echo $user && crontab -u $user -l
echo " "
done

How to schedule a function to run every hour on Flask?

I've tried using flask instead of a simple apscheduler what you need to install is

pip3 install flask_apscheduler

Below is the sample of my code:

from flask import Flask
from flask_apscheduler import APScheduler

app = Flask(__name__)
scheduler = APScheduler()

def scheduleTask():
    print("This test runs every 3 seconds")

if __name__ == '__main__':
    scheduler.add_job(id = 'Scheduled Task', func=scheduleTask, trigger="interval", seconds=3)
    scheduler.start()
    app.run(host="0.0.0.0")

How to install cron

Do you have a Windows machine or a Linux machine?

Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.

Under Linux you can create a crontab for your current user by typing:

crontab -e [username]

If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:

sudo apt-get update
sudo apt-get install cron

If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:

*/5 * * * *  /home/user/test.pl

The syntax is basically this:

.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed

Read more about it on the following pages: Wikipedia: crontab

How to run a cron job inside a docker container?

Define the cronjob in a dedicated container which runs the command via docker exec to your service.

This is higher cohesion and the running script will have access to the environment variables you have defined for your service.

#docker-compose.yml
version: "3.3"
services:
    myservice:
      environment:
        MSG: i'm being cronjobbed, every minute!
      image: alpine
      container_name: myservice
      command: tail -f /dev/null

    cronjobber:
     image: docker:edge
     volumes:
      - /var/run/docker.sock:/var/run/docker.sock
     container_name: cronjobber
     command: >
          sh -c "
          echo '* * * * * docker exec myservice printenv | grep MSG' > /etc/crontabs/root
          && crond -f"

Scheduling Python Script to run every hour accurately

Probably you got the solution already @lukik, but if you wanna remove a scheduling, you should use:

job = scheduler.add_job(myfunc, 'interval', minutes=2)
job.remove()

or

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
scheduler.remove_job('my_job_id')

if you need to use a explicit job ID

For more information, you should check: https://apscheduler.readthedocs.io/en/stable/userguide.html#removing-jobs

libclntsh.so.11.1: cannot open shared object file.

Just pass your Oracle path variables before you run any scripts:
Like for perl you can do add below in beginning of your script:

BEGIN {
   my $ORACLE_HOME     = "/usr/lib/oracle/11.2/client64";
   my $LD_LIBRARY_PATH = "$ORACLE_HOME/lib";
   if ($ENV{ORACLE_HOME} ne $ORACLE_HOME
   || $ENV{LD_LIBRARY_PATH} ne $LD_LIBRARY_PATH
   ) {
      $ENV{ORACLE_HOME}     = "/usr/lib/oracle/11.2/client64";
      $ENV{LD_LIBRARY_PATH} = "$ORACLE_HOME/lib";
      exec { $^X } $^X, $0, @ARGV;
   }
}

CRON job to run on the last day of the month

55 23 28-31 * * echo "[ $(date -d +1day +%d) -eq 1 ] && my.sh" | /bin/bash 

What is the curl error 52 "empty reply from server"?

In my case it was server redirection; curl -L solved my problem.

How do I schedule jobs in Jenkins?

Jenkins uses Cron format on scheduling. You can refer this link for more detailhttps://en.wikipedia.org/wiki/Cron. One more thing, Jenkins provide us a very useful preview. Please take a look on the screenshot. enter image description here

I hope this help. Thanks

How would I get a cron job to run every 30 minutes?

If your cron job is running on Mac OS X only, you may want to use launchd instead.

From Scheduling Timed Jobs (official Apple docs):

Note: Although it is still supported, cron is not a recommended solution. It has been deprecated in favor of launchd.

You can find additional information (such as the launchd Wikipedia page) with a simple web search.

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

Bash script to run php script

#!/usr/bin/env bash
PHP=`which php`
$PHP /path/to/php/file.php

Run a PHP file in a cron job using CPanel

>/dev/null stops cron from sending mails.

actually to my mind it's better to make php script itself to care about it's logging rather than just outputting something to cron

How to run cron job every 2 hours

Just do:

0 */2 * * *  /home/username/test.sh 

The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)

Don't forget, you can check syslog to see if it ever actually ran!

Cron and virtualenv

Running source from a cronfile won't work as cron uses /bin/sh as its default shell, which doesn't support source. You need to set the SHELL environment variable to be /bin/bash:

SHELL=/bin/bash
*/10 * * * * root source /path/to/virtualenv/bin/activate && /path/to/build/manage.py some_command > /dev/null

It's tricky to spot why this fails as /var/log/syslog doesn't log the error details. Best to alias yourself to root so you get emailed with any cron errors. Simply add yourself to /etc/aliases and run sendmail -bi.

More info here: http://codeinthehole.com/archives/43-Running-django-cronjobs-within-a-virtualenv.html

the link above is changed to: https://codeinthehole.com/tips/running-django-cronjobs-within-a-virtualenv/

How to write a cron that will run a script every day at midnight?

Sometimes you'll need to specify PATH and GEM_PATH using crontab with rvm.

Like this:

# top of crontab file
PATH=/home/user_name/.rvm/gems/ruby-2.2.0/bin:/home/user_name/.rvm/gems/ruby-2.2.0@global/bin:/home/user_name/.rvm/rubies/ruby-2.2.$
GEM_PATH=/home/user_name/.rvm/gems/ruby-2.2.0:/home/user_name/.rvm/gems/ruby-2.2.0@global

# jobs
00 00 * * * ruby path/to/your/script.rb
00 */4 * * * ruby path/to/your/script2.rb
00 8,12,22 * * * ruby path/to/your/script3.rb

How to set a cron job to run every 3 hours

Change Minute to be 0. That's it :)

Note: you can check your "crons" in http://cronchecker.net/

Example

Running a cron job on Linux every six hours

You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.

It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

Execute PHP script in cron job

I had the same problem... I had to run it as a user.

00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php

CRON command to run URL address every 5 minutes

Nothing worked for me on my linux hosting. The only possible commands they provide are:

/usr/local/bin/php absolute/path/to/cron/script

and

/usr/local/bin/ea-php56 absolute/domain_path/path/to/cron/script 

This is how I made it to work: 1. I created simple test.php file with the following content:

echo file_get_contents('http://example.com/check/');

2. I set the cronjob with the option server gived me using absolute inner path :)

/usr/local/bin/php absolute/path/to/public_html/test.php

How to create a cron job using Bash automatically without the interactive editor?

script function to add cronjobs. check duplicate entries,useable expressions * > "

cronjob_creator () {         
# usage: cronjob_creator '<interval>' '<command>'

  if [[ -z $1 ]] ;then
    printf " no interval specified\n"
elif [[ -z $2 ]] ;then
    printf " no command specified\n"
else
    CRONIN="/tmp/cti_tmp"
    crontab -l | grep -vw "$1 $2" > "$CRONIN"
    echo "$1 $2" >> $CRONIN
    crontab "$CRONIN"
    rm $CRONIN
fi
}

tested :

$ ./cronjob_creator.sh '*/10 * * * *' 'echo "this is a test" > export_file'
$ crontab  -l
$ */10 * * * * echo "this is a test" > export_file

source : my brain ;)

Test a weekly cron job

A wee bit beyond the scope of your question... but here's what I do.

The "how do I test a cron job?" question is closely connected to "how do I test scripts that run in non-interactive contexts launched by other programs?" In cron, the trigger is some time condition, but lots of other *nix facilities launch scripts or script fragments in non-interactive ways, and often the conditions in which those scripts run contain something unexpected and cause breakage until the bugs are sorted out. (See also: https://stackoverflow.com/a/17805088/237059 )

A general approach to this problem is helpful to have.

One of my favorite techniques is to use a script I wrote called 'crontest'. It launches the target command inside a GNU screen session from within cron, so that you can attach with a separate terminal to see what's going on, interact with the script, even use a debugger.

To set this up, you would use "all stars" in your crontab entry, and specify crontest as the first command on the command line, e.g.:

* * * * * crontest /command/to/be/tested --param1 --param2

So now cron will run your command every minute, but crontest will ensure that only one instance runs at a time. If the command takes time to run, you can do a "screen -x" to attach and watch it run. If the command is a script, you can put a "read" command at the top to make it stop and wait for the screen attachment to complete (hit enter after attaching)

If your command is a bash script, you can do this instead:

* * * * * crontest --bashdb /command/to/be/tested --param1 --param2

Now, if you attach with "screen -x", you'll be facing an interactive bashdb session, and you can step through the code, examine variables, etc.

#!/bin/bash

# crontest
# See https://github.com/Stabledog/crontest for canonical source.

# Test wrapper for cron tasks.  The suggested use is:
#
#  1. When adding your cron job, use all 5 stars to make it run every minute
#  2. Wrap the command in crontest
#        
#
#  Example:
#
#  $ crontab -e
#     * * * * * /usr/local/bin/crontest $HOME/bin/my-new-script --myparams
#
#  Now, cron will run your job every minute, but crontest will only allow one
#  instance to run at a time.  
#
#  crontest always wraps the command in "screen -d -m" if possible, so you can
#  use "screen -x" to attach and interact with the job.   
#
#  If --bashdb is used, the command line will be passed to bashdb.  Thus you
#  can attach with "screen -x" and debug the remaining command in context.
#
#  NOTES:
#   - crontest can be used in other contexts, it doesn't have to be a cron job.
#       Any place where commands are invoked without an interactive terminal and
#       may need to be debugged.
#
#   - crontest writes its own stuff to /tmp/crontest.log
#
#   - If GNU screen isn't available, neither is --bashdb
#

crontestLog=/tmp/crontest.log
lockfile=$(if [[ -d /var/lock ]]; then echo /var/lock/crontest.lock; else echo /tmp/crontest.lock; fi )
useBashdb=false
useScreen=$( if which screen &>/dev/null; then echo true; else echo false; fi )
innerArgs="$@"
screenBin=$(which screen 2>/dev/null)

function errExit {
    echo "[-err-] $@" | tee -a $crontestLog >&2
}

function log {
    echo "[-stat-] $@" >> $crontestLog
}

function parseArgs {
    while [[ ! -z $1 ]]; do
        case $1 in
            --bashdb)
                if ! $useScreen; then
                    errExit "--bashdb invalid in crontest because GNU screen not installed"
                fi
                if ! which bashdb &>/dev/null; then
                    errExit "--bashdb invalid in crontest: no bashdb on the PATH"
                fi

                useBashdb=true
                ;;
            --)
                shift
                innerArgs="$@"
                return 0
                ;;
            *)
                innerArgs="$@"
                return 0
                ;;
        esac
        shift
    done
}

if [[ -z  $sourceMe ]]; then
    # Lock the lockfile (no, we do not wish to follow the standard
    # advice of wrapping this in a subshell!)
    exec 9>$lockfile
    flock -n 9 || exit 1

    # Zap any old log data:
    [[ -f $crontestLog ]] && rm -f $crontestLog

    parseArgs "$@"

    log "crontest starting at $(date)"
    log "Raw command line: $@"
    log "Inner args: $@"
    log "screenBin: $screenBin"
    log "useBashdb: $( if $useBashdb; then echo YES; else echo no; fi )"
    log "useScreen: $( if $useScreen; then echo YES; else echo no; fi )"

    # Were building a command line.
    cmdline=""

    # If screen is available, put the task inside a pseudo-terminal
    # owned by screen.  That allows the developer to do a "screen -x" to
    # interact with the running command:
    if $useScreen; then
        cmdline="$screenBin -D -m "
    fi

    # If bashdb is installed and --bashdb is specified on the command line,
    # pass the command to bashdb.  This allows the developer to do a "screen -x" to
    # interactively debug a bash shell script:
    if $useBashdb; then
        cmdline="$cmdline $(which bashdb) "
    fi

    # Finally, append the target command and params:
    cmdline="$cmdline $innerArgs"

    log "cmdline: $cmdline"


    # And run the whole schlock:
    $cmdline 

    res=$?

    log "Command result: $res"


    echo "[-result-] $(if [[ $res -eq 0 ]]; then echo ok; else echo fail; fi)" >> $crontestLog

    # Release the lock:
    9<&-
fi

How to set a cron job to run at a exact time?

You can also specify the exact values for each gr

0 2,10,12,14,16,18,20 * * *

It stands for 2h00, 10h00, 12h00 and so on, till 20h00.

From the above answer, we have:

The comma, ",", means "and". If you are confused by the above line, remember that spaces are the field separators, not commas.

And from (Wikipedia page):

*    *    *    *    *  command to be executed
-    -    -    -    -
¦    ¦    ¦    ¦    ¦
¦    ¦    ¦    ¦    ¦
¦    ¦    ¦    ¦    +----- day of week (0 - 7) (0 or 7 are Sunday, or use names)
¦    ¦    ¦    +---------- month (1 - 12)
¦    ¦    +--------------- day of month (1 - 31)
¦    +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)

Hope it helps :)

--

EDIT:

  • don't miss the 1st 0 (zero) and the following space: it means "the minute zero", you can also set it to 15 (the 15th minute) or expressions like */15 (every minute divisible by 15, i.e. 0,15,30)

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

How to get CRON to call in the correct PATHs

Setting PATH right before the command line in my crontab worked for me:

* * * * * PATH=$PATH:/usr/local/bin:/path/to/some/thing

How to create cron job using PHP?

why you not use curl? logically, if you execute php file, you will execute that by url on your browser. its very simple if you run curl

while(true)
{
    sleep(60); // sleep for 60 sec = 1 minute

    $s = curl_init();
    curl_setopt($s,CURLOPT_URL, $your_php_url_to_cron); 
    curl_exec($s); 
    curl_getinfo($s,CURLINFO_HTTP_CODE); 
    curl_close($s);
}

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

Why I've got no crontab entry on OS X when using vim?

NOTE: the answer that says to use the ZZ command doesn't work for me on my Mavericks system, but this is probably due to something in my vim configuration because if I start with a pristine .vimrc, the accepted answer works. My answer might work for you if the other solution doesn't.

On MacOS X, according to the crontab manpage, the crontab temporary file that gets created with crontab -e needs to be edited in-place. Vim doesn't edit in-place by default (but it might do some special case to support crontab -e), so if your $EDITOR environment variable is set to vi (the default) or vim, editing the crontab will always fail.

To get Vim to edit the file in-place, you need to do:

:setlocal nowritebackup

That should enable you to update the crontab when you do crontab -e with the :wq or ZZ commands.

You can add an autocommand in your .vimrc to make this automatically work when editing crontabs:

autocmd FileType crontab setlocal nowritebackup

Another way is to add the setlocal nowritebackup to ~/.vim/after/ftplugin/crontab.vim, which will be loaded by Vim automatically when you're editing a crontab file if you have the Filetype plugin enabled. You can also check for the OS if you're using your vim files across multiple platforms:

""In ~/.vim/after/ftplugin/crontab.vim
if has("mac")
  setlocal nowritebackup
endif

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

Using WGET to run a cronjob PHP

you can just use this code to hit the script using cron job using cpanel:

wget https://www.example.co.uk/unique-code

How to get a unix script to run every 15 seconds?

To avoid possible overlapping of execution, use a locking mechanism as described in that thread.

Running a simple shell script as a cronjob

Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:

#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir

And crontab command is

* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh

It worked for me.

How to log cron jobs?

If you'd still like to check your cron jobs you should provide a valid email account when setting the Cron jobs in cPanel.

When you specify a valid email you will receive the output of the cron job that is executed. Thus you will be able to check it and make sure everything has been executed correctly. Note that you will not receive an email if there is no output from the cron job command.

Please bear in mind that you will receive an email for each of the executed cron jobs. This may flood your inbox in case your crons run too often

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

How to set up a cron job to run an executable every hour?

Since I could not run the C executable that way, I wrote a simple shell script that does the following

cd /..path_to_shell_script
./c_executable_name

In the cron jobs list, I call the shell script.

How do you run a crontab in Cygwin on Windows?

Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.

cygrunsrv -I cron -p /usr/sbin/cron -a -n

How to run a cronjob every X minutes?

In a crontab file, the fields are:

  • minute of the hour.
  • hour of the day.
  • day of the month.
  • month of the year.
  • day of the week.

So:

10 * * * * blah

means execute blah at 10 minutes past every hour.

If you want every five minutes, use either:

*/5 * * * * blah

meaning every minute but only every fifth one, or:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah

for older cron executables that don't understand the */x notation.

If it still seems to be not working after that, change the command to something like:

date >>/tmp/debug_cron_pax.txt

and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

Running a cron job at 2:30 AM everyday

  1. To edit:

    crontab -e
    
  2. Add this command line:

    30 2 * * * /your/command
    
    • Crontab Format:

      MIN HOUR DOM MON DOW CMD

    • Format Meanings and Allowed Value:
    • MIN Minute field 0 to 59
    • HOUR Hour field 0 to 23
    • DOM Day of Month 1-31
    • MON Month field 1-12
    • DOW Day Of Week 0-6
    • CMD Command Any command to be executed.
  3. Restart cron with latest data:

    service crond restart
    

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Many developers include files by pointing to a remote URL, even if the file is within the local system. For example:

<php include("http://example.com/includes/example_include.php"); ?>

With allow_url_include disabled, this method does not work. Instead, the file must be included with a local path, and there are three methods of doing this:

By using a relative path, such as ../includes/example_include.php. By using an absolute path (also known as relative-from-root), such as /home/username/example.com/includes/example_include.php.

By using the PHP environment variable $_SERVER['DOCUMENT_ROOT'], which returns the absolute path to the web root directory. This is by far the best (and most portable) solution. The following example shows the environment variable in action.

Example Include

<?php include($_SERVER['DOCUMENT_ROOT']."/includes/example_include.php"); ?>

cast a List to a Collection

First Collection is class Interface and you can not instantiate. Collection API

List Ver APi is also an interface class.

It may be so

List list = Collections.synchronizedList(new ArrayList(...)); 

ver enter link description here

Collection collection= Collections.synchronizedList(new ArrayList(...)); 

Getting a link to go to a specific section on another page

I tried the above answer - using page.html#ID_name it gave me a 404 page doesn't exist error.

Then instead of using .html, I simply put a slash / before the # and that worked fine. So my example on the sending page between the link tags looks like:

<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>

Just use / instead of .html.

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

Server Error in '/' Application. ASP.NET

  • right-click virtual directory (e.g. MyVirtualDirectory)

  • click convert to application.

How to add calendar events in Android?

if you have a given Date string with date and time .

for e.g String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */

use the following code to add an event with date and time to the calendar

Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", " Test Title");
startActivity(intent);

How to decompile to java files intellij idea

Some time ago I used JAD (JAva Decompiler) to achieve this - I do not think IntelliJ's decompiler was incorporated with exporting in mind. It is more of a tool to help look through classes where sources are not available.

JAD is still available for download, but I do not think anyone maintains it anymore: http://varaneckas.com/jad/

There were numerous plugins for it, namely Jadclipse (you guessed it, a way to use JAD in Eclipse - see decompiled classes where code is not available :)).

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

ISO C90 forbids mixed declarations and code in C

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

Eclipse count lines of code

Another tool is Google Analytix, which will also allow you to run metrics even if you can`t build the project in case of errors

How to set URL query params in Vue with Vue-Router

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

Activity transition in Android

You cannot use overridePendingTransition in Android 1.5. overridePendingTransistion came to Android 2.0.

If you're gonna go through this without any error you have to compile for the target (1.5 or higher) using the ordinary animations (or you own) or you have to compile for the target (2.0 or higher) using overridePendingTransistion.

Summary: You cannot use overridePendingTransistion in Android 1.5.

You can though use the built-in animations in the OS.

Using SED with wildcard

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.

Add event handler for body.onload by javascript within <body> part

Simply wrap the code you want to execute into the onload event of the window object:

window.onload = function(){ 
   // your code here
}

Non-recursive depth first search algorithm

http://www.youtube.com/watch?v=zLZhSSXAwxI

Just watched this video and came out with implementation. It looks easy for me to understand. Please critique this.

visited_node={root}
stack.push(root)
while(!stack.empty){
  unvisited_node = get_unvisited_adj_nodes(stack.top());
  If (unvisited_node!=null){
     stack.push(unvisited_node);  
     visited_node+=unvisited_node;
  }
  else
     stack.pop()
}

Module is not available, misspelled or forgot to load (but I didn't)

make sure that you insert your module and controller in your index.html first. then use this code in your module var app = angular.module("MesaViewer", []);

Best way to reset an Oracle sequence to the next value in an existing column?

With oracle 10.2g:

select  level, sequence.NEXTVAL
from  dual 
connect by level <= (select max(pk) from tbl);

will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

How do I find the data directory for a SQL Server instance?

Alex's answer is the right one, but for posterity here's another option: create a new empty database. If you use CREATE DATABASE without specifying a target dir you get... the default data / log directories. Easy.

Personally however I'd probably either:

  • RESTORE the database to the developer's PC, rather than copy/attach (backups can be compressed, exposed on a UNC), or
  • Use a linked server to avoid doing this in the first place (depends how much data goes over the join)

ps: 20gb is not huge, even in 2015. But it's all relative.

How to jump to top of browser page

Without animation, you can use plain JS:

scroll(0,0)

With animation, check Nick's answer.

Move view with keyboard using Swift

Here is my solution (actually this code is for the case when you have few textfields in your view, this works also for the case when you have one textfield)

class MyViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!

var activeTextField: UITextField!
var viewWasMoved: Bool = false


override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PrintViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PrintViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}

override func viewDidDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func textFieldDidBeginEditing(textField: UITextField) {
    self.activeTextField = textField
}

func textFieldDidEndEditing(textField: UITextField) {
    self.activeTextField = nil
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}


func keyboardWillShow(notification: NSNotification) {

    let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()

    var aRect: CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height

    let activeTextFieldRect: CGRect? = activeTextField?.frame
    let activeTextFieldOrigin: CGPoint? = activeTextFieldRect?.origin

    if (!CGRectContainsPoint(aRect, activeTextFieldOrigin!)) {
        self.viewWasMoved = true
        self.view.frame.origin.y -= keyboardSize!.height
    } else {
        self.viewWasMoved = false
    }
}

func keyboardWillHide(notification: NSNotification) {
    if (self.viewWasMoved) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

How to tag docker image with docker-compose

you can try:

services:
  nameis:
    container_name: hi_my
    build: .
    image: hi_my_nameis:v1.0.0

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

How to install Openpyxl with pip

  1. go to command prompt, and run as Administrator
  2. in c:/> prompt -> pip install openpyxl
  3. once you run in CMD you will get message like, Successfully installed et-xmlfile-1.0.1 jdcal-1.4.1 openpyxl-3.0.5
  4. go to python interactive shell and run openpyxl module
  5. openpyxl will work

Rails DateTime.now without Time

What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")

Stopping a thread after a certain amount of time

If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.

If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).

Parsing JSON in Java without knowing JSON format

Take a look at Jacksons built-in tree model feature.

And your code will be:

public void parse(String json)  {
       JsonFactory factory = new JsonFactory();

       ObjectMapper mapper = new ObjectMapper(factory);
       JsonNode rootNode = mapper.readTree(json);  

       Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
       while (fieldsIterator.hasNext()) {

           Map.Entry<String,JsonNode> field = fieldsIterator.next();
           System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
       }
}

disable all form elements inside div

Simply this line of code will disable all input elements

$('#yourdiv *').prop('disabled', true);

Rails: How to list database tables/objects using the Rails console?

To get a list of all model classes, you can use ActiveRecord::Base.subclasses e.g.

ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

How do I concatenate two arrays in C#?

Sorry to revive an old thread, but how about this:

static IEnumerable<T> Merge<T>(params T[][] arrays)
{
    var merged = arrays.SelectMany(arr => arr);

    foreach (var t in merged)
        yield return t;
}

Then in your code:

int[] x={1, 2, 3};
int[] y={4, 5, 6};

var z=Merge(x, y);  // 'z' is IEnumerable<T>

var za=z.ToArray(); // 'za' is int[]

Until you call .ToArray(), .ToList(), or .ToDictionary(...), the memory is not allocated, you are free to "build your query" and either call one of those three to execute it or simply go through them all by using foreach (var i in z){...} clause which returns an item at a time from the yield return t; above...

The above function can be made into an extension as follows:

static IEnumerable<T> Merge<T>(this T[] array1, T[] array2)
{
    var merged = array1.Concat(array2);

    foreach (var t in merged)
        yield return t;
}

So in the code, you can do something like:

int[] x1={1, 2, 3};
int[] x2={4, 5, 6};
int[] x3={7, 8};

var z=x1.Merge(x2).Merge(x3);   // 'z' is IEnumerable<T>

var za=z.ToArray(); // 'za' is int[]

The rest is the same as before.

One other improvement to this would be changing T[] into IEnumerable<T> (so the params T[][] would become params IEnumerable<T>[]) to make these functions accept more than just arrays.

Hope this helps.

How to catch exception output from Python subprocess.check_output()?

I don't think the accepted solution handles the case where the error text is reported on stderr. From my testing the exception's output attribute did not contain the results from stderr and the docs warn against using stderr=PIPE in check_output(). Instead, I would suggest one small improvement to J.F Sebastian's solution by adding stderr support. We are, after all, trying to handle errors and stderr is where they are often reported.

from subprocess import Popen, PIPE

p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0: 
   print("bitcoin failed %d %s %s" % (p.returncode, output, error))

Rails 4: how to use $(document).ready() with turbo-links

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

Unused arguments in R

The R.utils package has a function called doCall which is like do.call, but it does not return an error if unused arguments are passed.

multiply <- function(a, b) a * b

# these will fail
multiply(a = 20, b = 30, c = 10)
# Error in multiply(a = 20, b = 30, c = 10) : unused argument (c = 10)
do.call(multiply, list(a = 20, b = 30, c = 10))
# Error in (function (a, b)  : unused argument (c = 10)

# R.utils::doCall will work
R.utils::doCall(multiply, args = list(a = 20, b = 30, c = 10))
# [1] 600
# it also does not require the arguments to be passed as a list
R.utils::doCall(multiply, a = 20, b = 30, c = 10)
# [1] 600

How to get root view controller?

Unless you have a good reason, in your root controller do this:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(onTheEvent:)
                                             name:@"ABCMyEvent"
                                           object:nil];

And when you want to notify it:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ABCMyEvent"
                                                object:self];                

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

List all tables in postgresql information_schema

\dt information_schema.

from within psql, should be fine.

How do I sort a VARCHAR column in SQL server that contains numbers?

you can always convert your varchar-column to bigint as integer might be too short...

select cast([yourvarchar] as BIGINT)

but you should always care for alpha characters

where ISNUMERIC([yourvarchar] +'e0') = 1

the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber

this would lead to your statement

SELECT
  *
FROM
  Table
ORDER BY
   ISNUMERIC([yourvarchar] +'e0') DESC
 , LEN([yourvarchar]) ASC

the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)

this leads to the second version:

SELECT
      *
    FROM
      Table
    ORDER BY
       ISNUMERIC([yourvarchar] +'e0') DESC
     , RIGHT('00000000000000000000'+[yourvarchar], 20) ASC

the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)

so third version:

 SELECT
          *
        FROM
          Table
        ORDER BY
           ISNUMERIC([yourvarchar] +'e0') DESC
         , CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
                THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
                ELSE LTRIM(RTRIM([yourvarchar]))
           END ASC

now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I've searched and tried different things for hours.. To summarize, I had to take into consideration the following points:

  1. Use smtp.gmail.com instead of smtp.google.com
  2. Use port 587
  3. Set client.UseDefaultCredentials = false; before setting credentials
  4. Turn on the Access for less secure apps
  5. Set client.EnableSsl = true;

If these steps didn't help, check this answer.
Perhaps, you can find something useful on this System.Net.Mail FAQ too.

How to define a circle shape in an Android XML drawable file?

Here's a simple circle_background.xml for pre-material:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="@color/color_accent_dark" />
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/color_accent" />
        </shape>
    </item>
</selector>

You can use with the attribute 'android:background="@drawable/circle_background" in your button's layout definition

How to get Current Directory?

The question is not clear whether the current working directory is wanted or the path of the directory containing the executable.

Most answers seem to answer the latter.

But for the former, and for the second part of the question of creating the file, the C++17 standard now incorporates the filesystem library which simplifies this a lot:

#include <filesystem>
#include <iostream>

std::filesystem::path cwd = std::filesystem::current_path() / "filename.txt";
std::ofstream file(cwd.string());
file.close();

This fetches the current working directory, adds the filename to the path and creates an empty file. Note that the path object takes care of os dependent path handling, so cwd.string() returns an os dependent path string. Neato.

How to test Spring Data repositories?

tl;dr

To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.

Details

We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
    </div>
</div>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->
 ....

  <button type="submit">Submit</button>
</form>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   }
   else {
        alert('Not all fields valid! Do something...');
    }

 }

Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
!myForm.username.$pristine

You could also use:
myForm.username.$dirty

How can I create a dynamically sized array of structs?

Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.

How can I create a temp file with a specific extension with .NET?

I think you should try this:

string path = Path.GetRandomFileName();
path = Path.Combine(@"c:\temp", path);
path = Path.ChangeExtension(path, ".tmp");
File.Create(path);

It generates a unique filename and creates a file with that file name at a specified location.

Escape a string for a sed replace pattern

If the case happens to be that you are generating a random password to pass to sed replace pattern, then you choose to be careful about which set of characters in the random string. If you choose a password made by encoding a value as base64, then there is is only character that is both possible in base64 and is also a special character in sed replace pattern. That character is "/", and is easily removed from the password you are generating:

# password 32 characters log, minus any copies of the "/" character.
pass=`openssl rand -base64 32 | sed -e 's/\///g'`;

Override devise registrations controller

You can generate views and controllers for devise customization.

Use

rails g devise:controllers users -c=registrations

and

rails g devise:views 

It will copy particular controllers and views from gem to your application.

Next, tell the router to use this controller:

devise_for :users, :controllers => {:registrations => "users/registrations"}

How to use null in switch

switch(i) will throw a NullPointerException if i is null, because it will try to unbox the Integer into an int. So case null, which happens to be illegal, would never have been reached anyway.

You need to check that i is not null before the switch statement.

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Conversion failed when converting the varchar value to data type int in sql

Try this one -

CREATE PROC [dbo].[getVoucherNo]
AS BEGIN

     DECLARE 
            @Prefix VARCHAR(10) = 'J'
          , @startFrom INT = 1
          , @maxCode VARCHAR(100)
          , @sCode INT

     IF EXISTS(
          SELECT 1 
          FROM dbo.Journal_Entry
     ) BEGIN

          SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100)) 
          FROM dbo.Journal_Entry;

          SELECT @Prefix + 
               CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
               CAST(@maxCode AS VARCHAR(100))

     END
     ELSE BEGIN

          SELECT (@Prefix + CAST(@startFrom AS VARCHAR)) 

     END

END

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

Of Countries and their Cities

Check this out:

Cities of the world database donated by MaxMind.com

The company MaxMind.com1 has agreed to release their cities of the world database under the GPL. The database contains locations by country, city, latitude and longitude. There are over 3,047,000 records in the database. For those of you who have tried the location.module with the zipcodes database from CivicSpace, you will recognize how cool it is and how well this fits with that project and therefore Drupal.

Here's another free one that might help you get started.

Creating and maintaining such a database is quite a bit of work - so anyone who's done it is likely keeping it to themselves, or offering it for a fee.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

String replacement in Objective-C

NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

How to POST raw whole JSON in the body of a Retrofit request?

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Your Interface

public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

Activity

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

Two HTML tables side by side, centered on the page

<style>
#outer { text-align: center; }
#inner { width:500px; text-align: left; margin: 0 auto; }
.t { float: left; width:240px; border: 1px solid black;}
#clearit { clear: both; }
</style>

The type is defined in an assembly that is not referenced, how to find the cause?

I have a similar problem, and I remove the RuntimeFrameworkVersion, and the problem was fixed.

Try to remove 1.1.1 or

How to squash all git commits into one?

To do this, you can reset you local git repository to the first commit hashtag, so all your changes after that commit will be unstaged, then you can commit with --amend option.

git reset your-first-commit-hashtag
git add .
git commit --amend

And then edit the first commit nam if needed and save file.

What is the size of a boolean variable in Java?

The boolean values are compiled to int data type in JVM. See here.

Display the binary representation of a number in C?

You have to write your own transformation. Only decimal, hex and octal numbers are supported with format specifiers.

How to set ANDROID_HOME path in ubuntu?

you can edit the environment variable file in Ubuntu to set android home globally.

[1] run this command in terminal

sudo -H gedit /etc/environment

[2] your envirmnent file content will look like the below one

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

[3] in environment file add android sdk path as follows:-

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
ANDROID_HOME="/home/yourPathTo/Android/Sdk"

[4] then you can check the Android home path in the terminal with the following command:-

echo $ANDROID_HOME

If path is still not set then restart the system to get the applied changes.

Do checkbox inputs only post data if they're checked?

Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.

The default value is always "on", this should be consistent across browsers.

This is covered in the W3C HTML 4 recommendation:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

How to print to console in pytest?

Using -s option will print output of all functions, which may be too much.

If you need particular output, the doc page you mentioned offers few suggestions:

  1. Insert assert False, "dumb assert to make PyTest print my stuff" at the end of your function, and you will see your output due to failed test.

  2. You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    

    You can open the out and err files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt shell command to run your test.

That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).

How to check variable type at runtime in Go language

quux00's answer only tells about comparing basic types.

If you need to compare types you defined, you shouldn't use reflect.TypeOf(xxx). Instead, use reflect.TypeOf(xxx).Kind().

There are two categories of types:

  • direct types (the types you defined directly)
  • basic types (int, float64, struct, ...)

Here is a full example:

type MyFloat float64
type Vertex struct {
    X, Y float64
}

type EmptyInterface interface {}

type Abser interface {
    Abs() float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (f MyFloat) Abs() float64 {
    return math.Abs(float64(f))
}

var ia, ib Abser
ia = Vertex{1, 2}
ib = MyFloat(1)
fmt.Println(reflect.TypeOf(ia))
fmt.Println(reflect.TypeOf(ia).Kind())
fmt.Println(reflect.TypeOf(ib))
fmt.Println(reflect.TypeOf(ib).Kind())

if reflect.TypeOf(ia) != reflect.TypeOf(ib) {
    fmt.Println("Not equal typeOf")
}
if reflect.TypeOf(ia).Kind() != reflect.TypeOf(ib).Kind() {
    fmt.Println("Not equal kind")
}

ib = Vertex{3, 4}
if reflect.TypeOf(ia) == reflect.TypeOf(ib) {
    fmt.Println("Equal typeOf")
}
if reflect.TypeOf(ia).Kind() == reflect.TypeOf(ib).Kind() {
    fmt.Println("Equal kind")
}

The output would be:

main.Vertex
struct
main.MyFloat
float64
Not equal typeOf
Not equal kind
Equal typeOf
Equal kind

As you can see, reflect.TypeOf(xxx) returns the direct types which you might want to use, while reflect.TypeOf(xxx).Kind() returns the basic types.


Here's the conclusion. If you need to compare with basic types, use reflect.TypeOf(xxx).Kind(); and if you need to compare with self-defined types, use reflect.TypeOf(xxx).

if reflect.TypeOf(ia) == reflect.TypeOf(Vertex{}) {
    fmt.Println("self-defined")
} else if reflect.TypeOf(ia).Kind() == reflect.Float64 {
    fmt.Println("basic types")
}

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Just in case anyone hits the same problem whilst using WPF (rather than WCF or Silverlight):

I had this error, when connecting to a Web Service. When my code was in the "main" WPF Application solution, no problem, it worked perfectly. But when I moved the code to the more sensible DAL-layer solution, it would throw the exception.

Could not find default endpoint element that references contract 'MyWebService.MyServiceSoap' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

As has been stated by "Sprite" in this thread, you need to manually copy the tag.

For WPF apps, this means copying the tag from the app.config in my DAL solution to the app.config in the main WPF Application solution.

html <input type="text" /> onchange event not working

Firstly, what 'doesn't work'? Do you not see the alert?

Also, Your code could be simplified to this

<input type="text" id="num1" name="num1" onkeydown="checkInput(this);" /> <br />

function checkInput(obj) {
    alert(obj.value); 
}

How to match "any character" in regular expression?

Use the pattern . to match any character once, .* to match any character zero or more times, .+ to match any character one or more times.

Shell script to capture Process ID and kill it if exist

You probably wanted to write

`ps -ef | grep syncapp | awk '{print $2}'`

but I will endorse @PaulR's answer - killall -9 syncapp is a much better alternative.

How do I access an access array item by index in handlebars?

If undocumented features aren't your game, the same can be accomplished here:

Handlebars.registerHelper('index_of', function(context,ndx) {
  return context[ndx];
});

Then in a template

{{#index_of this 1}}{{/index_of}}   

I wrote the above before I got a hold of

this.[0]

I can't see one getting too far with handlebars without writing your own helpers.

Delete last N characters from field in a SQL Server database

You could do it using SUBSTRING() function:

UPDATE table SET column = SUBSTRING(column, 0, LEN(column) + 1 - N)

Removes the last N characters from every row in the column

How to convert comma-separated String to List?

This code will help,

String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

Following the exceedingly simple method from Andralor here fixed the issue for me: https://github.com/fancyapps/fancyBox/issues/766

Essentially, call the iframe again onUpdate:

$('a.js-fancybox-iframe').fancybox({
    type: 'iframe',
    scrolling : 'visible',
    autoHeight: true,
    onUpdate: function(){
     $("iframe.fancybox-iframe");
   }
 });

You are trying to add a non-nullable field 'new_field' to userprofile without a default

Do you already have database entries in the table UserProfile? If so, when you add new columns the DB doesn't know what to set it to because it can't be NULL. Therefore it asks you what you want to set those fields in the column new_fields to. I had to delete all the rows from this table to solve the problem.

(I know this was answered some time ago, but I just ran into this problem and this was my solution. Hopefully it will help anyone new that sees this)

What does ECU units, CPU core and memory mean when I launch a instance

For linuxes I've figured out that ECU could be measured by sysbench:

sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run

Total time (t) should be calculated by formula:

ECU=1925/t

And my example test results:

|   instance type   |   time   |   ECU   |
|-------------------|----------|---------|
| m1.small          |  1735,62 |       1 |
| m3.xlarge         |   147,62 |      13 |
| m3.2xlarge        |    74,61 |      26 |
| r3.large          |   295,84 |       7 |
| r3.xlarge         |   148,18 |      13 |
| m4.xlarge         |   146,71 |      13 |
| m4.2xlarge        |    73,69 |      26 |
| c4.xlarge         |   123,59 |      16 |
| c4.2xlarge        |    61,91 |      31 |
| c4.4xlarge        |    31,14 |      62 |

How can I make a button have a rounded border in Swift?

import UIKit

@IBDesignable
class RoundedButton: UIButton {
    
    @IBInspectable var cornerRadius: CGFloat = 8
    @IBInspectable var borderColor: UIColor? = .lightGray
    
    override func draw(_ rect: CGRect) {
        layer.cornerRadius = cornerRadius
        layer.masksToBounds = true
        layer.borderWidth = 1
        layer.borderColor = borderColor?.cgColor
        
    }
    
    
}

javax vs java package

I think it's a historical thing - if a package is introduced as an addition to an existing JRE, it comes in as javax. If it's first introduced as part of a JRE (like NIO was, I believe) then it comes in as java. Not sure why the new date and time API will end up as javax following this logic though... unless it will also be available separately as a library to work with earlier versions (which would be useful). Note from many years later: it actually ended up being in java after all.

I believe there are restrictions on the java package - I think classloaders are set up to only allow classes within java.* to be loaded from rt.jar or something similar. (There's certainly a check in ClassLoader.preDefineClass.)

EDIT: While an official explanation (the search orbfish suggested didn't yield one in the first page or so) is no doubt about "core" vs "extension", I still suspect that in many cases the decision for any particular package has an historical reason behind it too. Is java.beans really that "core" to Java, for example?

Changing Tint / Background color of UITabBar

Following is the perfect solution for this. This works fine with me for iOS5 and iOS4.

//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar]; 

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}

How to play a notification sound on websites?

How about the yahoo's media player Just embed yahoo's library

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

<a id="beep" href="song.mp3">Play Song</a>

To autostart

$(function() { $("#beep").click(); });

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

I have adapted the solution of Biju:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";

    private ObjectMapper om = new ObjectMapper();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonBody = getRequestBody(webRequest);

        JsonNode rootNode = om.readTree(jsonBody);
        JsonNode node = rootNode.path(parameter.getParameterName());    

        return om.readValue(node.toString(), parameter.getParameterType());
    }


    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

        String jsonBody = (String) webRequest.getAttribute(JSONBODYATTRIBUTE, NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody==null){
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute(JSONBODYATTRIBUTE, jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return jsonBody;

    }

}

What's the different:

  • I'm using Jackson to convert json
  • I don't need a value in the annotation, you can read the name of the parameter out of the MethodParameter
  • I also read the type of the parameter out of the Methodparameter => so the solution should be generic (i tested it with string and DTOs)

BR

Is there a function in python to split a word into a list?

The easiest option is to just use the list() command. However, if you don't want to use it or it dose not work for some bazaar reason, you can always use this method.

word = 'foo'
splitWord = []

for letter in word:
    splitWord.append(letter)

print(splitWord) #prints ['f', 'o', 'o']

Optional query string parameters in ASP.NET Web API

Use initial default values for all parameters like below

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

How to scroll to top of a div using jQuery?

Special thanks to Stoic for

   $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});

How to remove item from a python list in a loop?

This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.

Workaround could be:

x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
    if len(item) != 2:
        print "length of %s is: %s" %(item, len(item))
        x.remove(item)

Importing csv file into R - numeric values read as characters

Whatever algebra you are doing in Excel to create the new column could probably be done more effectively in R.

Please try the following: Read the raw file (before any excel manipulation) into R using read.csv(... stringsAsFactors=FALSE). [If that does not work, please take a look at ?read.table (which read.csv wraps), however there may be some other underlying issue].

For example:

   delim = ","  # or is it "\t" ?
   dec = "."    # or is it "," ?
   myDataFrame <- read.csv("path/to/file.csv", header=TRUE, sep=delim, dec=dec, stringsAsFactors=FALSE)

Then, let's say your numeric columns is column 4

   myDataFrame[, 4]  <- as.numeric(myDataFrame[, 4])  # you can also refer to the column by "itsName"


Lastly, if you need any help with accomplishing in R the same tasks that you've done in Excel, there are plenty of folks here who would be happy to help you out

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

One possibility that the above answers don't address is that you may not have an ssh access from your shell. That is, you may be in a network (some college networks do this) where ssh service is blocked.In that case you will not only be able to get github services but also any other ssh services. You can test if this is the problem by trying to use any other ssh service.This was the case with me.

WCF change endpoint address at runtime

This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.

var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
    <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
    <div class='error'><?php echo $userError;?></div>
    <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
    <div class='error'><?php echo $passError;?></div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>

Does HTML5 <video> playback support the .avi format?

There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.

Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.

Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.

How to tell if a string contains a certain character in JavaScript?

Try this:

if ('Hello, World!'.indexOf('orl') !== -1)
    alert("The string 'Hello World' contains the substring 'orl'!");
else
    alert("The string 'Hello World' does not contain the substring 'orl'!");

Here is an example: http://jsfiddle.net/oliverni/cb8xw/

Is there a "null coalescing" operator in JavaScript?

Update

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

Please check compatibility before using it.


The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.


Clarification

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"

Delete all rows in a table based on another table

This is old I know, but just a pointer to anyone using this ass a reference. I have just tried this and if you are using Oracle, JOIN does not work in DELETE statements. You get a the following message:

ORA-00933: SQL command not properly ended.

How to add a tooltip to an svg graphic?

I came up with something using HTML + CSS only. Hope it works for you

_x000D_
_x000D_
.mzhrttltp {
  position: relative;
  display: inline-block;
}
.mzhrttltp .hrttltptxt {
  visibility: hidden;
  width: 120px;
  background-color: #040505;
  font-size:13px;color:#fff;font-family:IranYekanWeb;
  text-align: center;
  border-radius: 3px;
  padding: 4px 0;
  position: absolute;
  z-index: 1;
  top: 105%;
  left: 50%;
  margin-left: -60px;
}

.mzhrttltp .hrttltptxt::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #040505 transparent;
}

.mzhrttltp:hover .hrttltptxt {
  visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????&zwnj;????&zwnj;??</div></div>
_x000D_
_x000D_
_x000D_

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

How do I see the extensions loaded by PHP?

You want to run:

 php -m 

on the command line,

or if you have access to the server configuration file open

/etc/php5/apache2/php.ini

and look at all the the extensions,

you can even enable or disable them by switching between On and Off like this

<Extension_name> = <[On | Off]>

How to get names of enum entries?

Assuming you stick to the rules and only produce enums with numeric values, you can use this code. This correctly handles the case where you have a name that is coincidentally a valid number

enum Color {
    Red,
    Green,
    Blue,
    "10" // wat
}

var names: string[] = [];
for(var n in Color) {
    if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

The reason your original code doesn't compile is that <? extends Serializable> does not mean, "any class that extends Serializable," but "some unknown but specific class that extends Serializable."

For example, given the code as written, it is perfectly valid to assign new TreeMap<String, Long.class>() to expected. If the compiler allowed the code to compile, the assertThat() would presumably break because it would expect Date objects instead of the Long objects it finds in the map.

Java: convert List<String> to a String

No, there's no such convenience method in the standard Java API.

Not surprisingly, Apache Commons provides such a thing in their StringUtils class in case you don't want to write it yourself.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Given it's a raw expression, you should use DB::raw() to set CURRENT_TIMESTAMP as a default value for a column:

$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

This works flawlessly on every database driver.

New shortcut

As of Laravel 5.1.25 (see PR 10962 and commit 15c487fe) you can use the new useCurrent() column modifier method to set the CURRENT_TIMESTAMP as a default value for a column:

$table->timestamp('created_at')->useCurrent();

Back to the question, on MySQL you could also use the ON UPDATE clause through DB::raw():

$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

Gotchas

  • MySQL

    Starting with MySQL 5.7, 0000-00-00 00:00:00 is no longer considered a valid date. As documented at the Laravel 5.2 upgrade guide, all timestamp columns should receive a valid default value when you insert records into your database. You may use the useCurrent() column modifier (from Laravel 5.1.25 and above) in your migrations to default the timestamp columns to the current timestamps, or you may make the timestamps nullable() to allow null values.

  • PostgreSQL & Laravel 4.x

    In Laravel 4.x versions, the PostgreSQL driver was using the default database precision to store timestamp values. When using the CURRENT_TIMESTAMP function on a column with a default precision, PostgreSQL generates a timestamp with the higher precision available, thus generating a timestamp with a fractional second part - see this SQL fiddle.

    This will led Carbon to fail parsing a timestamp since it won't be expecting microseconds being stored. To avoid this unexpected behavior breaking your application you have to explicitly give a zero precision to the CURRENT_TIMESTAMP function as below:

    $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP(0)'));
    

    Since Laravel 5.0, timestamp() columns has been changed to use a default precision of zero which avoids this.

    Thanks to @andrewhl for pointing out this issue in the comments.

how to open an URL in Swift3

import UIKit 
import SafariServices 

let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!) 
present(vc, animated: true, completion: nil)

HTML image not showing in Gmail

Google only allows images which are coming from trusted source .

So I solved this issue by hosting my images in google drive and using its url as source for my images.

Example: with: http://drive.google.com/uc?export=view&id=FILEID'>

to form URL please refer here.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

Check if a specific tab page is selected (active)

in .Net 4 can use

if (tabControl1.Controls[5] == tabControl1.SelectedTab)
                MessageBox.Show("Tab 5 Is Selected");

OR

if ( tabpage5 == tabControl1.SelectedTab)
         MessageBox.Show("Tab 5 Is Selected");

How to write JUnit test with Spring Autowire?

I think somewhere in your codebase are you @Autowiring the concrete class ServiceImpl where you should be autowiring it's interface (presumably MyService).

error: cast from 'void*' to 'int' loses precision

I meet this problem too.

ids[i] = (int) arg; // error occur here => I change this to below.

ids[i] = (uintptr_t) arg;

Then I can continue compiling. Maybe you can try this too.

Error inflating class android.support.design.widget.NavigationView

I had similar error. When i use

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>
    <item name="android:textColorPrimary">#212121</item>
    <item name="android:textColorSecondary">#727272</item>

</style>

works for me when i remove the android:textColorPrimary and android:textColorSecondary theme items.

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <item name="colorPrimary">#673AB7</item>
    <item name="colorPrimaryDark">#512DA8</item>
    <item name="colorAccent">#00BCD4</item>

</style>

Try working with a very simple App theme to start off with.

EDIT:

This tutorial will help. My understanding is that using "android:textColorPrimary" requires minimum api level 21. Using the same tag without "android:" uses the design support library. Any support library widget will try to find the "textColorPrimary" item instead of "android:textColorPrimary" and if it fails to find the same it throws the above mentioned error.

Converting bool to text in C++

Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.

#define PRINTBOOL(x) x?"true":"false"

Resize HTML5 canvas to fit window

Basically what you have to do is to bind the onresize event to your body, once you catch the event you just need to resize the canvas using window.innerWidth and window.innerHeight.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Canvas Resize</title>

    <script type="text/javascript">
        function resize_canvas(){
            canvas = document.getElementById("canvas");
            if (canvas.width  < window.innerWidth)
            {
                canvas.width  = window.innerWidth;
            }

            if (canvas.height < window.innerHeight)
            {
                canvas.height = window.innerHeight;
            }
        }
    </script>
</head>

<body onresize="resize_canvas()">
        <canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>

How do I rotate the Android emulator display?

I have checked on Windows: Ctrl + F11 and Ctrl + F12 both are working to change the orientation of the Android simulator.

For other shortcut keys:

In the Eclipse toolbar go to "Help-->key Assist.. "

You can also use Ctrl + Shift + L here, so many shortcut keys of Eclipse are given.

Java unsupported major minor version 52.0

You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.

How to set or change the default Java (JDK) version on OS X?

This tool will do the work for you:

http://www.guigarage.com/2013/02/change-java-version-on-mac-os/

It's a simple JavaOne that can be used to define the current Java Version. The version can be used in a shell that is opened after a version was selected in the tool.

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

The problem with editing JavaScript like you can CSS and HTML is that there is no clean way to propagate the changes. JavaScript can modify the DOM, send Ajax requests, and dynamically modify existing objects and functions at runtime. So, once you have loaded a page with JavaScript, it might be completely different after the JavaScript has run. The browser would have to keep track of every modification your JavaScript code performs so that when you edit the JS, it rolls back the changes to a clean page.

But, you can modify JavaScript dynamically a few other ways:

  • JavaScript injections in the URL bar: javascript: alert (1);
  • Via a JavaScript console (there's one built into Firefox, Chrome, and newer versions of IE
  • If you want to modify the JavaScript files as they are served to your browser (i.e. grabbing them in transit and modifying them), then I can't offer much help. I would suggest using a debugging proxy: http://www.fiddler2.com/fiddler2/

The first two options are great because you can modify any JavaScript variables and functions currently in scope. However, you won't be able to modify the code and run it with a "just-served" page like you can with the third option.

Other than that, as far as I know, there is no edit-and-run JavaScript editor in the browser. Hope this helps,

Figure out size of UILabel based on String in Swift

Swift 5:

If you have UILabel and someway boundingRect isn't working for you (I faced this problem. It always returned 1 line height.) there is an extension to easily calculate label size.

extension UILabel {
    func getSize(constrainedWidth: CGFloat) -> CGSize {
        return systemLayoutSizeFitting(CGSize(width: constrainedWidth, height: UIView.layoutFittingCompressedSize.height), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
    }
}

You can use it like this:

let label = UILabel()
label.text = "My text\nIs\nAwesome"
let labelSize = label.getSize(constrainedWidth:200.0)

Works for me

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

If you really want to insert this record, remove the `abuse_id` field and the corresponding value from the INSERTstatement :

INSERT INTO  `abuses` (  `user_id` ,  `abuser_username` ,  `comment` ,  `reg_date` , `auction_id` ) 
VALUES ( 100020,  'artictundra', 'I placed a bid for it more than an hour ago. It is still active. I thought I was supposed to get an email after 15 minutes.', 1338052850, 108625 ) ;

Performing a Stress Test on Web Application?

This is an old question, but I think newer solutions are worthy of a mention. Checkout LoadImpact: http://www.loadimpact.com.

re.sub erroring with "Expected string or bytes-like object"

The simplest solution is to apply Python str function to the column you are trying to loop through.

If you are using pandas, this can be implemented as:

dataframe['column_name']=dataframe['column_name'].apply(str)

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Drawing in Java using Canvas

Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the

paintComponent(){
  super...
}

and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();

I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.

Doug Hauf

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

Textarea resize control is available via the CSS3 resize property:

textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }

Allowable values self-explanatory: none (disables textarea resizing), both, vertical and horizontal.

Notice that in Chrome, Firefox and Safari the default is both.

If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height, max-width, min-height, and min-width CSS properties to provide resizing within certain proportions.

Code example:

_x000D_
_x000D_
#textarea-wrapper {_x000D_
  padding: 10px;_x000D_
  background-color: #f4f4f4;_x000D_
  width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
  min-height:50px;_x000D_
  max-height:120px;_x000D_
  width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
  resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
  <label for="resize-default">Textarea (default):</label>_x000D_
  <textarea name="resize-default" id="resize-default"></textarea>_x000D_
  _x000D_
  <label for="resize-vertical">Textarea (vertical):</label>_x000D_
  <textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript backslash (\) in variables is causing an error

You have to escape each \ to be \\:

var ttt = "aa ///\\\\\\";

Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.

because you had to show a message to user that user can't give a name which has (\) character.

I think the scenario is like:

var user_input_name = document.getElementById('the_name').value;

Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.

If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.

I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:

var ttt = "aa ///\";

Hence, we assume the asker having problem with escaping.

If you want to simulate, you code must be valid at first place.

var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.

alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?

Now, you only need to do is

var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
  alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
  do_something_else();
  }

Edit: I used [] to quote text to be shown, so it would be less confused than using "".

Django CSRF Cookie Not Set

If you're using the HTML5 Fetch API to make POST requests as a logged in user and getting Forbidden (CSRF cookie not set.), it could be because by default fetch does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.

You can include the session token by passing the option credentials: 'include' to fetch:

var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
    method: 'POST',
    body: payload,
    headers: headers,
    credentials: 'include'
})

Convert array of JSON object strings to array of JS objects

If you really have:

var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];

then simply:

var objs = $.map(s, $.parseJSON);

Here's a demo.

python xlrd unsupported format, or corrupt file.

Open in google sheets and then download from sheets as CSV and then reupload to drive. Then you can Open CSV file from python.

How do I make Java register a string input with spaces?

in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.

How to set a cron job to run at a exact time?

check out

http://www.thesitewizard.com/general/set-cron-job.shtml

for the specifics of setting your crontab directives.

 45 10 * * *

will run in the 10th hour, 45th minute of every day.

for midnight... maybe

 0 0 * * *

How do I add a tool tip to a span element?

the "title" attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins

Enum String Name from Value

DB to C#

EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());

C# to DB

string dbStatus = ((int)status).ToString();

How to subtract n days from current date in java?

I found this perfect solution and may useful, You can directly get in format as you want:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -90); // I just want date before 90 days. you can give that you want.

SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); // you can specify your format here...
Log.d("DATE","Date before 90 Days: " + s.format(new Date(cal.getTimeInMillis())));

Thanks.

Javascript setInterval not working

Try this:

function funcName() {
    alert("test");
}

var run = setInterval(funcName, 10000)

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

The final solution to your assembly redirect errors

Okay, hopefully this should help resolve any (sane) assembly reference discrepancies ...

  1. Check the error.

Surf to the website

  1. Check web.config after the assembly redirect. Create one if not exists.

Existing web.config assembly redirect

  1. Right-click the reference for the assembly and choose Properties.

Assembly in the Reference list, in the relevant project

  1. Check the Version (not Runtime version) in the Properties table. Copy that.

Properties table showing Version of assembly

  1. Paste into the newVersion attribute.

web.config assembly redirect with updated newVersion

  1. For convenience, change the last part of the oldVersion to something high, round and imaginary.

web.config assembly redirect with updated oldVersion

Rejoice.

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Representing Directory & File Structure in Markdown Syntax

Under OSX, using reveal.js, I have got rendering issue if I just user tree and then copy/paste the output: strange symbols appear.

I have found 2 possible solutions.

1) Use charset ascii and simply copy/paste the output in the markdown file

tree -L 1 --charset=ascii

2) Use directly HTML and unicode in the markdown file

<pre>
.
&#8866; README.md
&#8866; docs
&#8866; e2e
&#8866; karma.conf.js
&#8866; node_modules
&#8866; package.json
&#8866; protractor.conf.js
&#8866; src
&#8866; tsconfig.json
&#8985; tslint.json
</pre>

Hope it helps.

How to deal with floating point number precision in JavaScript?

Solved it by first making both numbers integers, executing the expression and afterwards dividing the result to get the decimal places back:

function evalMathematicalExpression(a, b, op) {
    const smallest = String(a < b ? a : b);
    const factor = smallest.length - smallest.indexOf('.');

    for (let i = 0; i < factor; i++) {
        b *= 10;
        a *= 10;
    }

    a = Math.round(a);
    b = Math.round(b);
    const m = 10 ** factor;
    switch (op) {
        case '+':
            return (a + b) / m;
        case '-':
            return (a - b) / m;
        case '*':
            return (a * b) / (m ** 2);
        case '/':
            return a / b;
    }

    throw `Unknown operator ${op}`;
}

Results for several operations (the excluded numbers are results from eval):

0.1 + 0.002   = 0.102 (0.10200000000000001)
53 + 1000     = 1053 (1053)
0.1 - 0.3     = -0.2 (-0.19999999999999998)
53 - -1000    = 1053 (1053)
0.3 * 0.0003  = 0.00009 (0.00008999999999999999)
100 * 25      = 2500 (2500)
0.9 / 0.03    = 30 (30.000000000000004)
100 / 50      = 2 (2)

Difference between DOM parentNode and parentElement

In Internet Explorer, parentElement is undefined for SVG elements, whereas parentNode is defined.

Best way to move files between S3 buckets?

If you have a unix host within AWS, then use s3cmd from s3tools.org. Set up permissions so that your key as read access to your development bucket. Then run:

s3cmd cp -r s3://productionbucket/feed/feedname/date s3://developmentbucket/feed/feedname

add column to mysql table if it does not exist

$smpt = $pdo->prepare("SHOW fields FROM __TABLE__NAME__");
$smpt->execute();
$res = $smpt->fetchAll(PDO::FETCH_ASSOC);
//print_r($res);

Then in $res by cycle look for key of your column Smth like this:

    if($field['Field'] == '_my_col_'){
       return true;
    }
+

**Below code is good for checking column existing in the WordPress tables:**
public static function is_table_col_exists($table, $col)
    {
        global $wpdb;
        $fields = $wpdb->get_results("SHOW fields FROM {$table}", ARRAY_A);
        foreach ($fields as $field)
        {
            if ($field['Field'] == $col)
            {
                return TRUE;
            }
        }

        return FALSE;
    }

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

What is the boundary in multipart/form-data?

The exact answer to the question is: yes, you can use an arbitrary value for the boundary parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII (printable) characters.

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You probably also want to set the charset parameter to UTF-8 in your Content-Type header, unless you can be absolutely sure that only US-ASCII charset will be used in the payload data.

A few relevant excerpts from the RFC2046:

  • 4.1.2. Charset Parameter:

    Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

  • 5.1. Multipart Media Type

    As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.

    The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.

    Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.

    The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.

Here is an example using an arbitrary boundary:

Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"

--another cool boundary
Content-Disposition: form-data; name="foo"

bar
--another cool boundary
Content-Disposition: form-data; name="baz"

quux
--another cool boundary--

How do I unload (reload) a Python module?

For those like me who want to unload all modules (when running in the Python interpreter under Emacs):

   for mod in sys.modules.values():
      reload(mod)

More information is in Reloading Python modules.

Fill formula down till last row in column

Alternatively, you may use FillDown

Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown

Regex for string not ending with given suffix

The question is old but I could not find a better solution I post mine here. Find all USB drives but not listing the partitions, thus removing the "part[0-9]" from the results. I ended up doing two grep, the last negates the result:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -vE "part[0-9]*$"

This results on my system:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

If I only want the partitions I could do:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -E "part[0-9]*$"

Where I get:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part1
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part2

And when I do:

readlink -f /dev/disk/by-path/pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

I get:

/dev/sdb

Url.Action parameters?

Here is another simple way to do it

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>

Where is @Model.ID is a parameter

And here there is a second example.

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2&param3=ViewBag.P3'>Print</a>

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

Writing a string to a cell in excel

I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:

Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"

Does this fail as well?

Looks like you tried something similar:

'Worksheets("Game").Range("A1") = "Asdf"

However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

Fixing a systemd service 203/EXEC failure (no such file or directory)

I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

How does jQuery work when there are multiple elements with the same ID value?

Having 2 elements with the same ID is not valid html according to the W3C specification.

When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


If you absolutely must select by duplicate ID, use an attribute selector:

$('[id="a"]');

Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

Note: if possible, you should qualify that selector with a tag selector, like this:

$('span[id="a"]');

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

RandomForestClassfier.fit(): ValueError: could not convert string to float

As your input is in string you are getting value error message use countvectorizer it will convert data set in to sparse matrix and train your ml algorithm you will get the result

Align button at the bottom of div using CSS

Parent container has to have this:

position: relative;

Button itself has to have this:

position: relative;
bottom: 20px;
right: 20px;

or whatever you like

How to insert a row in an HTML table body in JavaScript

Add rows:

_x000D_
_x000D_
<html>_x000D_
    <script>_x000D_
        function addRow() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            //var row = document.getElementById("myTable");_x000D_
            var x = table.insertRow(0);_x000D_
            var e = table.rows.length-1;_x000D_
            var l = table.rows[e].cells.length;_x000D_
            //x.innerHTML = "&nbsp;";_x000D_
_x000D_
            for (var c=0, m=l; c < m; c++) {_x000D_
                table.rows[0].insertCell(c);_x000D_
                table.rows[0].cells[c].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function addColumn() {_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].insertCell(0);_x000D_
                table.rows[r].cells[0].innerHTML = "&nbsp;&nbsp;";_x000D_
            }_x000D_
        }_x000D_
_x000D_
        function deleteRow() {_x000D_
            document.getElementById("myTable").deleteRow(0);_x000D_
        }_x000D_
_x000D_
        function deleteColumn() {_x000D_
            // var row = document.getElementById("myRow");_x000D_
            var table = document.getElementById('myTable');_x000D_
            for (var r = 0, n = table.rows.length; r < n; r++) {_x000D_
                table.rows[r].deleteCell(0); // var table handle_x000D_
            }_x000D_
        }_x000D_
    </script>_x000D_
_x000D_
    <body>_x000D_
        <input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>_x000D_
        <input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>_x000D_
_x000D_
        <table  id='myTable' border=1 cellpadding=0 cellspacing=0>_x000D_
            <tr id='myRow'>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
                <td>&nbsp;</td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

And cells.

How do I make a column unique and index it in a Ruby on Rails migration?

rails generate migration add_index_to_table_name column_name:uniq

or

rails generate migration add_column_name_to_table_name column_name:string:uniq:index

generates

class AddIndexToModerators < ActiveRecord::Migration
  def change
    add_column :moderators, :username, :string
    add_index :moderators, :username, unique: true
  end
end

If you're adding an index to an existing column, remove or comment the add_column line, or put in a check

add_column :moderators, :username, :string unless column_exists? :moderators, :username

Singleton design pattern vs Singleton beans in Spring container

Singleton scope in spring means single instance in a Spring context ..
Spring container merely returns the same instance again and again for subsequent calls to get the bean.


And spring doesn't bother if the class of the bean is coded as singleton or not , in fact if the class is coded as singleton whose constructor as private, Spring use BeanUtils.instantiateClass (javadoc here) to set the constructor to accessible and invoke it.

Alternatively, we can use a factory-method attribute in bean definition like this

    <bean id="exampleBean" class="example.Singleton"  factory-method="getInstance"/>

CUDA incompatible with my gcc version

gcc 4.5 and 4.6 are not supported with CUDA - code won't compile and the rest of the toolchain, including cuda-gdb, won't work properly. You cannot use them, and the restriction is non-negotiable.

Your only solution is to install a gcc 4.4 version as a second compiler (most distributions will allow that). There is an option to nvcc --compiler-bindir which can be used to point to an alternative compiler. Create a local directory and then make symbolic links to the supported gcc version executables. Pass that local directory to nvcc via the --compiler-bindir option, and you should be able to compile CUDA code without affecting the rest of your system.


EDIT:

Note that this question, and answer, pertain to CUDA 4.

Since it was written, NVIDIA has continued to expand support for later gcc versions in newer CUDA toolchain release

  • As of the CUDA 4.1 release, gcc 4.5 is now supported. gcc 4.6 and 4.7 are unsupported.
  • As of the CUDA 5.0 release, gcc 4.6 is now supported. gcc 4.7 is unsupported.
  • As of the CUDA 6.0 release, gcc 4.7 is now supported.
  • As of the CUDA 7.0 release, gcc 4.8 is fully supported, with 4.9 support on Ubuntu 14.04 and Fedora 21.
  • As of the CUDA 7.5 release, gcc 4.8 is fully supported, with 4.9 support on Ubuntu 14.04 and Fedora 21.
  • As of the CUDA 8 release, gcc 5.3 is fully supported on Ubuntu 16.06 and Fedora 23.
  • As of the CUDA 9 release, gcc 6 is fully supported on Ubuntu 16.04, Ubuntu 17.04 and Fedora 25.
  • The CUDA 9.2 release adds support for gcc 7
  • The CUDA 10.1 release adds support for gcc 8
  • The CUDA 10.2 release continues support for gcc 8
  • The CUDA 11.0 release adds support for gcc 9 on Ubuntu 20.04
  • The CUDA 11.1 release expands gcc 9 support across most distributions and adds support for gcc 10 on Fedora linux

There is presently (as of CUDA 11.1) no gcc 10 support in CUDA other than Fedora linux

Note that NVIDIA has recently added a very useful table here which contains the supported compiler and OS matrix for the current CUDA release.

How do I URL encode a string

After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.

IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:

(Objective C code)

@implementation NSString (NSString_urlencoding)

- (NSString *)urlencode {
    static NSMutableCharacterSet *chars = nil;
    static dispatch_once_t pred;

    if (chars)
        return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];

    // to be thread safe
    dispatch_once(&pred, ^{
        chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
        [chars removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
    });
    return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
}
@end

This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:

NSString *myusername = "I'm[evil]&want(to)break!!!$->àéìòù";
NSLog(@"Source: %@ -> Dest: %@", myusername, [myusername urlencode]);

That will print on your debug console:

Source: I'm[evil]&want(to)break!!!$->àéìòù -> Dest: I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3%A0%C3%A9%C3%AC%C3%B2%C3%B9

... note also the use of dispatch_once to avoid multiple initializations in multithread environments.

Regular expression to match DNS hostname or IP Address?

try this:

((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)

it works in my case.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

One possibility is, if you are familiar with PDF format:

  1. Create some simply PDF with one page (Page should be contained within one object)
  2. Copy object multiply times
  3. Add references to the copied objects to the page catalog
  4. Fix xref table

You get an valid document of any size, entire file will be processed by a reader.

Copy table to a different database on a different SQL Server

Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:

http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A

Is it possible to auto-format your code in Dreamweaver?

And for JavaScript source format you can use Dreamweaver JavaScript source formatting extension.(available on adobe)

MS Excel showing the formula in a cell instead of the resulting value

I had the same problem and solved with below:

Range("A").Formula = Trim(CStr("the formula"))

How do you redirect to a page using the POST verb?

I would like to expand the answer of Jason Bunting

like this

ActionResult action = new SampelController().Index(2, "text");
return action;

And Eli will be here for something idea on how to make it generic variable

Can get all types of controller

Get child Node of another Node, given node name

You should read it recursively, some time ago I had the same question and solve with this code:

public void proccessMenuNodeList(NodeList nl, JMenuBar menubar) {
    for (int i = 0; i < nl.getLength(); i++) {
        proccessMenuNode(nl.item(i), menubar);
    }
}

public void proccessMenuNode(Node n, Container parent) {
    if(!n.getNodeName().equals("menu"))
        return;
    Element element = (Element) n;
    String type = element.getAttribute("type");
    String name = element.getAttribute("name");
    if (type.equals("menu")) {
        NodeList nl = element.getChildNodes();
        JMenu menu = new JMenu(name);

        for (int i = 0; i < nl.getLength(); i++)
            proccessMenuNode(nl.item(i), menu);

        parent.add(menu);
    } else if (type.equals("item")) {
        JMenuItem item = new JMenuItem(name);
        parent.add(item);
    }
}

Probably you can adapt it for your case.

How to get table cells evenly spaced?

I'm also open to suggestion on how to tidy this up, if there are any? :-)

Well, you could not use the span element, for semantic reasons. And you don't have to define the class PerformanceCell. The cells and rows can be accessed by using PerformanceTable tr {} and PerformanceTable tr {}, respectively.

For the spacing part, I have got the same problem several times. I shamefully admit I avoided the problem, so I am very curious to any answers too.

System.Data.OracleClient requires Oracle client software version 8.1.7

For me, the issue was some plugin in my Visual Studio started forcing my application into x64 64bit mode, so the Oracle driver wasn't being found as I had Oracle 32bit installed.

So if you are having this issue, try running Visual Studio in safemode (devenv /safemode). I could find that it was looking in SYSWOW64 for the ic.dll file by using the ProcMon app by SysInternals/Microsoft.

Update: For me it was the Telerik JustTrace product that was causing the issue, it was probably hooking in and affecting the runtime version somehow to do tracing.

Update2: It's not just JustTrace causing an issue, JustMock is causing the same processor mode issue. JustMock is easier to fix though: Click JustMock-> Disable Profiler and then my web app's oracle driver runs in the correct CPU mode. This might be fixed by Telerik in the future.

Image resolution for new iPhone 6 and 6+, @3x support added?

I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior). But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.

**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :

Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.

Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.

Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.

Setting environment variables in Linux using Bash

Set a local and environment variable using Bash on Linux

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

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

Sanity check, no local or environment variable called LOL.

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

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

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

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

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

You could also just unset the one variable:

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

Local variable LOL is gone.

Promote a local variable to an environment variable:

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

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

Exported variable DOGE above survives a Bash reset:

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

Unset all environment variables:

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

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

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

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

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

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

No posters have mentioned the contraction of floating expressions yet (ISO C standard, 6.5p8 and 7.12.2). If the FP_CONTRACT pragma is set to ON, the compiler is allowed to regard an expression such as a*a*a*a*a*a as a single operation, as if evaluated exactly with a single rounding. For instance, a compiler may replace it by an internal power function that is both faster and more accurate. This is particularly interesting as the behavior is partly controlled by the programmer directly in the source code, while compiler options provided by the end user may sometimes be used incorrectly.

The default state of the FP_CONTRACT pragma is implementation-defined, so that a compiler is allowed to do such optimizations by default. Thus portable code that needs to strictly follow the IEEE 754 rules should explicitly set it to OFF.

If a compiler doesn't support this pragma, it must be conservative by avoiding any such optimization, in case the developer has chosen to set it to OFF.

GCC doesn't support this pragma, but with the default options, it assumes it to be ON; thus for targets with a hardware FMA, if one wants to prevent the transformation a*b+c to fma(a,b,c), one needs to provide an option such as -ffp-contract=off (to explicitly set the pragma to OFF) or -std=c99 (to tell GCC to conform to some C standard version, here C99, thus follow the above paragraph). In the past, the latter option was not preventing the transformation, meaning that GCC was not conforming on this point: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=37845

Python: How to remove empty lists from a list?

Try

list2 = [x for x in list1 if x != []]

If you want to get rid of everything that is "falsy", e.g. empty strings, empty tuples, zeros, you could also use

list2 = [x for x in list1 if x]

How to create nonexistent subdirectories recursively using Bash?

$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

How to redirect to another page using AngularJS?

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

This: http://archives.postgresql.org/pgsql-bugs/2007-10/msg00234.php is also a nice and fast solution, and works for multiple schemas in one database:

Tables

SELECT 'ALTER TABLE '|| schemaname || '."' || tablename ||'" OWNER TO my_new_owner;'
FROM pg_tables WHERE NOT schemaname IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;

Sequences

SELECT 'ALTER SEQUENCE '|| sequence_schema || '."' || sequence_name ||'" OWNER TO my_new_owner;'
FROM information_schema.sequences WHERE NOT sequence_schema IN ('pg_catalog', 'information_schema')
ORDER BY sequence_schema, sequence_name;

Views

SELECT 'ALTER VIEW '|| table_schema || '."' || table_name ||'" OWNER TO my_new_owner;'
FROM information_schema.views WHERE NOT table_schema IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;

Materialized Views

Based on this answer

SELECT 'ALTER TABLE '|| oid::regclass::text ||' OWNER TO my_new_owner;'
FROM pg_class WHERE relkind = 'm'
ORDER BY oid;

This generates all the required ALTER TABLE / ALTER SEQUENCE / ALTER VIEW statements, copy these and paste them back into plsql to run them.

Check your work in psql by doing:

\dt *.*
\ds *.*
\dv *.*

Form Submission without page refresh

Just catch the submit event and prevent that, then do ajax

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

Why is the <center> tag deprecated in HTML?

CSS has a text-align: center property, and since this is purely a visual thing, not semantic, it should be relegated to CSS, not HTML.

How to use a client certificate to authenticate and authorize in a Web API

I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:

  1. The private key is actually being exported as part of the cert.

  2. The application pool identity running the app has access to said private key.

In our case I had to:

  1. Import the pfx file into the local server store while checking the export checkbox to ensure the private key was sent out.
  2. Using MMC console, grant the service account used access to the private key for the cert.

The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.

Common CSS Media Queries Break Points

I can tell you I am using just a single breakpoint at 768 - that is min-width: 768px to serve tablets and desktops, and max-width: 767px to serve phones.

I haven't looked back since. It makes the responsive development easy and not a chore, and provides a reasonable experience on all devices at minimal cost to development time without the need to fear a new Android device with a new resolution you haven't factored in.

Exact difference between CharSequence and String in java

In charSequence you don't have very useful methods which are available for String. If you don't want to look in the documentation, type: obj. and str.

and see what methods your compilator offers you. That's the basic difference for me.

How to let PHP to create subdomain automatically for each user?

I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.

JSON Java 8 LocalDateTime format in Spring Boot

As already mentioned, spring-boot will fetch all you need (for both web and webflux starter).

But what's even better - you don't need to register any modules yourself. Take a look here. Since @SpringBootApplication uses @EnableAutoConfiguration under the hood, it means JacksonAutoConfiguration will be added to the context automatically. Now, if you look inside JacksonAutoConfiguration, you will see:

    private void configureModules(Jackson2ObjectMapperBuilder builder) {
        Collection<Module> moduleBeans = getBeans(this.applicationContext,
                Module.class);
        builder.modulesToInstall(moduleBeans.toArray(new Module[0]));
    }

This fella will be called in the process of initialization and will fetch all the modules it can find in the classpath. (I use Spring Boot 2.1)

Can I call a function of a shell script from another shell script?

If you define

    #!/bin/bash
        fun1(){
          echo "Fun1 from file1 $1"
        }
fun1 Hello
. file2 
fun1 Hello
exit 0

in file1(chmod 750 file1) and file2

   fun1(){
      echo "Fun1 from file2 $1"
    }
    fun2(){
      echo "Fun1 from file1 $1"
    }

and run ./file2 you'll get Fun1 from file1 Hello Fun1 from file2 Hello Surprise!!! You overwrite fun1 in file1 with fun1 from file2... So as not to do so you must

declare -f pr_fun1=$fun1
. file2
unset -f fun1
fun1=$pr_fun1
unset -f pr_fun1
fun1 Hello

it's save your previous definition for fun1 and restore it with the previous name deleting not needed imported one. Every time you import functions from another file you may remember two aspects:

  1. you may overwrite existing ones with the same names(if that the thing you want you must preserve them as described above)
  2. import all content of import file(functions and global variables too) Be careful! It's dangerous procedure

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

After my initial struggle with the link and controller functions and reading quite a lot about them, I think now I have the answer.

First lets understand,

How do angular directives work in a nutshell:

  • We begin with a template (as a string or loaded to a string)

    var templateString = '<div my-directive>{{5 + 10}}</div>';

  • Now, this templateString is wrapped as an angular element

    var el = angular.element(templateString);

  • With el, now we compile it with $compile to get back the link function.

    var l = $compile(el)

    Here is what happens,

    • $compile walks through the whole template and collects all the directives that it recognizes.
    • All the directives that are discovered are compiled recursively and their link functions are collected.
    • Then, all the link functions are wrapped in a new link function and returned as l.
  • Finally, we provide scope function to this l (link) function which further executes the wrapped link functions with this scope and their corresponding elements.

    l(scope)

  • This adds the template as a new node to the DOM and invokes controller which adds its watches to the scope which is shared with the template in DOM.

enter image description here

Comparing compile vs link vs controller :

  • Every directive is compiled only once and link function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's compile function.

  • Now, after compilation we have link function which is executed while attaching the template to the DOM. So, therefore we perform everything that is specific to every instance of the directive. For eg: attaching events, mutating the template based on scope, etc.

  • Finally, the controller is meant to be available to be live and reactive while the directive works on the DOM (after getting attached). Therefore:

    (1) After setting up the view[V] (i.e. template) with link. $scope is our [M] and $controller is our [C] in M V C

    (2) Take advantage the 2-way binding with $scope by setting up watches.

    (3) $scope watches are expected to be added in the controller since this is what is watching the template during run-time.

    (4) Finally, controller is also used to be able to communicate among related directives. (Like myTabs example in https://docs.angularjs.org/guide/directive)

    (5) It's true that we could've done all this in the link function as well but its about separation of concerns.

Therefore, finally we have the following which fits all the pieces perfectly :

enter image description here

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

How to Install pip for python 3.7 on Ubuntu 18?

Combining the answers from @mpenkon and @dangel, this is what worked for me:

  1. sudo apt install python3-pip

  2. python3.7 -m pip install pip

Step #1 is required (assuming you don't already have pip for python3) for step #2 to work. It uses pip for Python3.6 to install pip for Python 3.7 apparently.

How do I get indices of N maximum values in a NumPy array?

When top_k<<axis_length,it better than argsort.

import numpy as np

def get_sorted_top_k(array, top_k=1, axis=-1, reverse=False):
    if reverse:
        axis_length = array.shape[axis]
        partition_index = np.take(np.argpartition(array, kth=-top_k, axis=axis),
                                  range(axis_length - top_k, axis_length), axis)
    else:
        partition_index = np.take(np.argpartition(array, kth=top_k, axis=axis), range(0, top_k), axis)
    top_scores = np.take_along_axis(array, partition_index, axis)
    # resort partition
    sorted_index = np.argsort(top_scores, axis=axis)
    if reverse:
        sorted_index = np.flip(sorted_index, axis=axis)
    top_sorted_scores = np.take_along_axis(top_scores, sorted_index, axis)
    top_sorted_indexes = np.take_along_axis(partition_index, sorted_index, axis)
    return top_sorted_scores, top_sorted_indexes

if __name__ == "__main__":
    import time
    from sklearn.metrics.pairwise import cosine_similarity

    x = np.random.rand(10, 128)
    y = np.random.rand(1000000, 128)
    z = cosine_similarity(x, y)
    start_time = time.time()
    sorted_index_1 = get_sorted_top_k(z, top_k=3, axis=1, reverse=True)[1]
    print(time.time() - start_time)

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

Update: This process is the same for upgrading 9.5 through at least 11.5; simply modify the commands to reflect versions 9.6 and 10, where 9.6 is the old version and 10 is the new version. Be sure to adjust the "old" and "new" directories accordingly, too.


I just upgraded PostgreSQL 9.5 to 9.6 on Ubuntu and thought I'd share my findings, as there are a couple of OS/package-specific nuances of which to be aware.

(I didn't want to have to dump and restore data manually, so several of the other answers here were not viable.)

In short, the process consists of installing the new version of PostgreSQL alongside the old version (e.g., 9.5 and 9.6), and then running the pg_upgrade binary, which is explained in (some) detail at https://www.postgresql.org/docs/9.6/static/pgupgrade.html .

The only "tricky" aspect of pg_upgrade is that failure to pass the correct value for an argument, or failure to be logged-in as the correct user or cd to the correct location before executing a command, may lead to cryptic error messages.

On Ubuntu (and probably Debian), provided you are using the "official" repo, deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main, and provided you haven't changed the default filesystem paths or runtime options, the following procedure should do the job.

Install the new version (note that we specify the 9.6, explicitly):

sudo apt install postgresql-9.6

Once installation succeeds, both versions will be running side-by-side, but on different ports. The installation output mentions this, at the bottom, but it's easy to overlook:

Creating new cluster 9.6/main ...
  config /etc/postgresql/9.6/main
  data   /var/lib/postgresql/9.6/main
  locale en_US.UTF-8
  socket /var/run/postgresql
  port   5433

Stop both server instances (this will stop both at the same time):

sudo systemctl stop postgresql

Switch to the dedicated PostgreSQL system user:

su postgres

Move into his home directory (failure to do this will cause errors):

cd ~

pg_upgrade requires the following inputs (pg_upgrade --help tells us this):

When you run pg_upgrade, you must provide the following information:
  the data directory for the old cluster  (-d DATADIR)
  the data directory for the new cluster  (-D DATADIR)
  the "bin" directory for the old version (-b BINDIR)
  the "bin" directory for the new version (-B BINDIR)

These inputs may be specified with "long names", to make them easier to visualize:

  -b, --old-bindir=BINDIR       old cluster executable directory
  -B, --new-bindir=BINDIR       new cluster executable directory
  -d, --old-datadir=DATADIR     old cluster data directory
  -D, --new-datadir=DATADIR     new cluster data directory

We must also pass the --new-options switch, because failure to do so results in the following:

connection to database failed: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/lib/postgresql/.s.PGSQL.50432"?

This occurs because the default configuration options are applied in the absence of this switch, which results in incorrect connection options being used, hence the socket error.

Execute the pg_upgrade command from the new PostgreSQL version:

/usr/lib/postgresql/9.6/bin/pg_upgrade --old-bindir=/usr/lib/postgresql/9.5/bin --new-bindir=/usr/lib/postgresql/9.6/bin --old-datadir=/var/lib/postgresql/9.5/main --new-datadir=/var/lib/postgresql/9.6/main --old-options=-cconfig_file=/etc/postgresql/9.5/main/postgresql.conf --new-options=-cconfig_file=/etc/postgresql/9.6/main/postgresql.conf

Logout of the dedicated system user account:

exit

The upgrade is now complete, but, the new instance will bind to port 5433 (the standard default is 5432), so keep this in mind if attempting to test the new instance before "cutting-over" to it.

Start the server as normal (again, this will start both the old and new instances):

systemctl start postgresql

If you want to make the new version the default, you will need to edit the effective configuration file, e.g., /etc/postgresql/9.6/main/postgresql.conf, and ensure that the port is defined as such:

port = 5432

If you do this, either change the old version's port number to 5433 at the same time (before starting the services), or, simply remove the old version (this will not remove your actual database content; you would need to use apt --purge remove postgresql-9.5 for that to happen):

apt remove postgresql-9.5

The above command will stop all instances, so you'll need to start the new instance one last time with:

systemctl start postgresql

As a final point of note, don't forget to consider pg_upgrade's good advice:

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade so,
once you start the new server, consider running:
    ./analyze_new_cluster.sh

Running this script will delete the old cluster's data files:
    ./delete_old_cluster.sh

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

How do I limit the number of returned items?

Like this, using .limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
  // `posts` will be of length 20
});

Refresh a page using PHP

That is simply possible with header() in PHP:

header('Refresh: 1; url=index.php');

Convert canvas to PDF

A better solution would be using Kendo ui draw dom to export to pdf-

Suppose the following html file which contains the canvas tag:

<script src="http://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>

    <script type="x/kendo-template" id="page-template">
     <div class="page-template">
            <div class="header">

            </div>
            <div class="footer" style="text-align: center">

                <h2> #:pageNum# </h2>
            </div>
      </div>
    </script>
    <canvas id="myCanvas" width="500" height="500"></canvas>
    <button onclick="ExportPdf()">download</button>

Now after that in your script write down the following and it will be done:

function ExportPdf(){ 
kendo.drawing
    .drawDOM("#myCanvas", 
    { 
        forcePageBreak: ".page-break", 
        paperSize: "A4",
        margin: { top: "1cm", bottom: "1cm" },
        scale: 0.8,
        height: 500, 
        template: $("#page-template").html(),
        keepTogether: ".prevent-split"
    })
        .then(function(group){
        kendo.drawing.pdf.saveAs(group, "Exported_Itinerary.pdf")
    });
}

And that is it, Write anything in that canvas and simply press that download button all exported into PDF. Here is a link to Kendo UI - http://docs.telerik.com/kendo-ui/framework/drawing/drawing-dom And a blog to better understand the whole process - https://www.cronj.com/blog/export-htmlcss-pdf-using-javascript/