Programs & Examples On #Timestamp

A timestamp is the time at which an event is recorded by a computer system. The timestamp term may also refer to Unix Time or to the timestamp data type.

How to convert MySQL time to UNIX timestamp using PHP?

Use strtotime(..):

$timestamp = strtotime($mysqltime);
echo date("Y-m-d H:i:s", $timestamp);

Also check this out (to do it in MySQL way.)

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

You might want to take a look what PHP has to offer: http://php.net/datetime

Handling MySQL datetimes and timestamps in Java

BalusC gave a good description about the problem but it lacks a good end to end code that users can pick and test it for themselves.

Best practice is to always store date-time in UTC timezone in DB. Sql timestamp type does not have timezone info.

When writing datetime value to sql db

    //Convert the time into UTC and build Timestamp object.
    Timestamp ts = Timestamp.valueOf(LocalDateTime.now(ZoneId.of("UTC")));
    //use setTimestamp on preparedstatement
    preparedStatement.setTimestamp(1, ts);

When reading the value back from DB into java,

  1. Read it as it is in java.sql.Timestamp type.
  2. Decorate the DateTime value as time in UTC timezone using atZone method in LocalDateTime class.
  3. Then, change it to your desired timezone. Here I am changing it to Toronto timezone.

    ResultSet resultSet = preparedStatement.executeQuery();
    resultSet.next();
    Timestamp timestamp = resultSet.getTimestamp(1);
    ZonedDateTime timeInUTC = timestamp.toLocalDateTime().atZone(ZoneId.of("UTC"));
    LocalDateTime timeInToronto = LocalDateTime.ofInstant(timeInUTC.toInstant(), ZoneId.of("America/Toronto"));
    

PHP How to find the time elapsed since a date time?

Had to do this recently - hope this helps someone. It doesn't cater for every possibility, but met my needs for a project.

https://github.com/duncanheron/twitter_date_format

https://github.com/duncanheron/twitter_date_format/blob/master/twitter_date_format.php

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

I found results like the following ugly:

1 years, 2 months, 0 days, 0 hours, 53 minutes and 1 seconds

Because of that I realized a function that respects plurals, removes empty values and optionally it is possible to shorten the output:

function since($timestamp, $level=6) {
    global $lang;
    $date = new DateTime();
    $date->setTimestamp($timestamp);
    $date = $date->diff(new DateTime());
    // build array
    $since = array_combine(array('year', 'month', 'day', 'hour', 'minute', 'second'), explode(',', $date->format('%y,%m,%d,%h,%i,%s')));
    // remove empty date values
    $since = array_filter($since);
    // output only the first x date values
    $since = array_slice($since, 0, $level);
    // build string
    $last_key = key(array_slice($since, -1, 1, true));
    $string = '';
    foreach ($since as $key => $val) {
        // separator
        if ($string) {
            $string .= $key != $last_key ? ', ' : ' ' . $lang['and'] . ' ';
        }
        // set plural
        $key .= $val > 1 ? 's' : '';
        // add date value
        $string .= $val . ' ' . $lang[ $key ];
    }
    return $string;
}

Looks much better:

1 year, 2 months, 53 minutes and 1 second

Optionally use $level = 2 to shorten it as follows:

1 year and 2 months

Remove the $lang part if you need it only in English or edit this translation to fit your needs:

$lang = array(
    'second' => 'Sekunde',
    'seconds' => 'Sekunden',
    'minute' => 'Minute',
    'minutes' => 'Minuten',
    'hour' => 'Stunde',
    'hours' => 'Stunden',
    'day' => 'Tag',
    'days' => 'Tage',
    'month' => 'Monat',
    'months' => 'Monate',
    'year' => 'Jahr',
    'years' => 'Jahre',
    'and' => 'und',
);

MySQL CURRENT_TIMESTAMP on create and on update

I think you maybe want ts_create as datetime (so rename -> dt_create) and only ts_update as timestamp? This will ensure it remains unchanging once set.

My understanding is that datetime is for manually-controlled values, and timestamp's a bit "special" in that MySQL will maintain it for you. In this case, datetime is therefore a good choice for ts_create.

SQL Server 2008 Row Insert and Update timestamps

As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERTs that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP which it includes in the final INSERT to the database. You could do the same for the CREATE. You may also be able to set things up so that users cannot execute INSERT and CREATE statements other than via the stored procedures.

I have to admit that I haven't actually done this myself so I'm not at all sure of the details.

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

Ping with timestamp on Windows CLI

Try this:

Create a batch file with the following:

echo off

cd\

:start

echo %time% >> c:\somedirectory\pinghostname.txt

ping pinghostname >> c:\somedirectory\pinghostname.txt

goto start

You can add your own options to the ping command based on your requirements. This doesn't put the time stamp on the same line as the ping, but it still gets you the info you need.

An even better way is to use fping, go here http://www.kwakkelflap.com/fping.html to download it.

How to convert SQL Server's timestamp column to datetime format

Some of them actually does covert to a date-time from SQL Server 2008 onwards.

Try the following SQL query and you will see for yourself:

SELECT CAST (0x00009CEF00A25634 AS datetime)

The above will result in 2009-12-30 09:51:03:000 but I have encountered ones that actually don't map to a date-time.

Creation timestamp and last update timestamp with Hibernate and MySQL

As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.

For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).

Convert Date/Time for given Timezone - java

We can get the UTC/GMT time stamp from the given date.

/**
 * Get the time stamp in GMT/UTC by passing the valid time (dd-MM-yyyy HH:mm:ss)
 */
public static long getGMTTimeStampFromDate(String datetime) {
    long timeStamp = 0;
    Date localTime = new Date();

    String format = "dd-MM-yyyy HH:mm:ss";
    SimpleDateFormat sdfLocalFormat = new SimpleDateFormat(format);
    sdfLocalFormat.setTimeZone(TimeZone.getDefault());

    try {

        localTime = (Date) sdfLocalFormat.parse(datetime); 

        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"),
                Locale.getDefault());
        TimeZone tz = cal.getTimeZone();

        cal.setTime(localTime);

        timeStamp = (localTime.getTime()/1000);
        Log.d("GMT TimeStamp: ", " Date TimegmtTime: " + datetime
                + ", GMT TimeStamp : " + localTime.getTime());

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return timeStamp;

}

It will return the UTC time based on passed date.

  • We can do reverse like UTC time stamp to current date and time(vice versa)

        public static String getLocalTimeFromGMT(long gmtTimeStamp) {
                 try{
                        Calendar calendar = Calendar.getInstance();
                        TimeZone tz = TimeZone.getDefault();
                        calendar.setTimeInMillis(gmtTimeStamp * 1000);
        //              calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); 
                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        Date currenTimeZone = (Date) calendar.getTime();
                        return sdf.format(currenTimeZone);
                    }catch (Exception e) {
                    }
                    return "";  
                }
    

I hope this will help others. Thanks!!

Setting a JPA timestamp column to be generated by the database?

Add the @CreationTimestamp annotation:

@CreationTimestamp
@Column(name="timestamp", nullable = false, updatable = false, insertable = false)
private Timestamp timestamp;

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

Convert Java String to sql.Timestamp

I believe you need to do this:

  1. Convert everythingButNano using SimpleDateFormat or the like to everythingDate.
  2. Convert nano using Long.valueof(nano)
  3. Convert everythingDate to a Timestamp with new Timestamp(everythingDate.getTime())
  4. Set the Timestamp nanos with Timestamp.setNano()

Option 2 Convert to the date format pointed out in Jon Skeet's answer and use that.

How do I convert dmesg timestamp to custom date format?

A caveat which the other answers don't seem to mention is that the time which is shown by dmesg doesn't take into account any sleep/suspend time. So there are cases where the usual answer of using dmesg -T doesn't work, and shows a completely wrong time.

A workaround for such situations is to write something to the kernel log at a known time and then use that entry as a reference to calculate the other times. Obviously, it will only work for times after the last suspend.

So to display the correct time for recent entries on machines which may have been suspended since their last boot, use something like this from my other answer here:

# write current time to kernel ring buffer so it appears in dmesg output
echo "timecheck: $(date +%s) = $(date +%F_%T)" | sudo tee /dev/kmsg

# use our "timecheck" entry to get the difference
# between the dmesg timestamp and real time
offset=$(dmesg | grep timecheck | tail -1 \
| perl -nle '($t1,$t2)=/^.(\d+)\S+ timecheck: (\d+)/; print $t2-$t1')

# pipe dmesg output through a Perl snippet to
# convert it's timestamp to correct readable times
dmesg | tail \
| perl -pe 'BEGIN{$offset=shift} s/^\[(\d+)\S+/localtime($1+$offset)/e' $offset

Convert datetime to Unix timestamp and convert it back in python

If your datetime object represents UTC time, don't use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:

>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

iPhone: How to get current milliseconds?

[[NSDate date] timeIntervalSince1970];

It returns the number of seconds since epoch as a double. I'm almost sure you can access the milliseconds from the fractional part.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

Android Get Current timestamp?

From developers blog:

System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.

Function to convert timestamp to human date in javascript

The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:

var d = new Date(1382086394000);

How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.

Fri Oct 18 2013 18:53:14 GMT+1000 (EST) 

In ES5 there are some other built-in formatting options:

and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:

alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());

* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.

How to convert HH:mm:ss.SSS to milliseconds?

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.
package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

Java: Convert String to TimeStamp

Follow these steps for a correct result:

try {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
    Date parsedDate = dateFormat.parse(yourString);
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) { //this generic but you can control another types of exception
    // look the origin of excption 
}

Please note that .parse(String) might throw a ParseException.

Swift - iOS - Dates and times in different format

Time Picker In swift

class ViewController: UIViewController {
    
    //timePicker
    @IBOutlet weak var lblTime: UILabel!
    @IBOutlet weak var timePicker: UIDatePicker!
    @IBOutlet weak var cancelTime_Btn: UIBarButtonItem!
    @IBOutlet weak var donetime_Btn: UIBarButtonItem!
    @IBOutlet weak var toolBar: UIToolbar!
    
    //Date picker
//    @IBOutlet weak var datePicker: UIDatePicker!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ishidden(bool: true)
        let dateFormatter2 = DateFormatter()
        dateFormatter2.dateFormat = "HH:mm a" //"hh:mm a"
        lblTime.text = dateFormatter2.string(from: timePicker.date)
        
    }
    
    @IBAction func selectTime_Action(_ sender: Any) {
        timePicker.datePickerMode = .time
        ishidden(bool: false)
    }
    
    @IBAction func timeCancel_Action(_ sender: Any) {
        ishidden(bool: true)
    }
    
    @IBAction func timeDoneBtn(_ sender: Any) {
        let dateFormatter1 = DateFormatter()
        dateFormatter1.dateFormat =  "HH:mm a"//"hh:mm"
        
        let str = dateFormatter1.string(from: timePicker.date)
        lblTime.text = str
        
        ishidden(bool: true)
        
    }
    
    func ishidden(bool:Bool){
           timePicker.isHidden = bool
           toolBar.isHidden = bool
       }
}

Pandas: Convert Timestamp to datetime.date

Assume time column is in timestamp integer msec format

1 day = 86400000 ms

Here you go:

day_divider = 86400000

df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format

df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format

Get Unix timestamp with C++

The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)

What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.

How to convert date to timestamp in PHP?

With DateTime API:

$dateTime = new DateTime('2008-09-22'); 
echo $dateTime->format('U'); 

// or 

$date = new DateTime('2008-09-22');
echo $date->getTimestamp();

The same with the procedural API:

$date = date_create('2008-09-22');
echo date_format($date, 'U');

// or

$date = date_create('2008-09-22');
echo date_timestamp_get($date);

If the above fails because you are using a unsupported format, you can use

$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U'); 

// or

$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');

Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

Yet another alternative is to use the IntlDateFormatter API:

$formatter = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'GMT',
    IntlDateFormatter::GREGORIAN,
    'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');

Unless you are working with localized date strings, the easier choice is likely DateTime.

Time stamp in the C programming language

Use @Arkaitz Jimenez's code to get two timevals:

#include <sys/time.h>
//...
struct timeval tv1, tv2, diff;

// get the first time:
gettimeofday(&tv1, NULL);

// do whatever it is you want to time
// ...

// get the second time:
gettimeofday(&tv2, NULL);

// get the difference:

int result = timeval_subtract(&diff, &tv1, &tv2);

// the difference is storid in diff now.

Sample code for timeval_subtract can be found at this web site:

 /* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */

 int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
   /* Perform the carry for the later subtraction by updating y. */
   if (x->tv_usec < y->tv_usec) {
     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
     y->tv_usec -= 1000000 * nsec;
     y->tv_sec += nsec;
   }
   if (x->tv_usec - y->tv_usec > 1000000) {
     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
     y->tv_usec += 1000000 * nsec;
     y->tv_sec -= nsec;
   }

   /* Compute the time remaining to wait.
      tv_usec is certainly positive. */
   result->tv_sec = x->tv_sec - y->tv_sec;
   result->tv_usec = x->tv_usec - y->tv_usec;

   /* Return 1 if result is negative. */
   return x->tv_sec < y->tv_sec;
 }

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Use strftime in the standard POSIX module. The arguments to strftime in Perl’s binding were designed to align with the return values from localtime and gmtime. Compare

strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)

with

my          ($sec,$min,$hour,$mday,$mon,$year,$wday,     $yday,     $isdst) = gmtime(time);

Example command-line use is

$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'

or from a source file as in

use POSIX;

print strftime "%F %T", localtime time;

Some systems do not support the %F and %T shorthands, so you will have to be explicit with

print strftime "%Y-%m-%d %H:%M:%S", localtime time;

or

print strftime "%Y-%m-%d %H:%M:%S", gmtime time;

Note that time returns the current time when called whereas $^T is fixed to the time when your program started. With gmtime, the return value is the current time in GMT. Retrieve time in your local timezone with localtime.

How to get the current TimeStamp?

In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch() static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.

Function that creates a timestamp in c#

You can also use

Stopwatch.GetTimestamp().ToString();

MySql difference between two timestamps in days?

If you want to return in full TIMESTAMP format than try it: -

 SELECT TIMEDIFF(`call_end_time`, `call_start_time`) as diff from tablename;

return like

     diff
     - - -
    00:05:15

What does this format means T00:00:00.000Z?

Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME; instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") or any pattern

This fixed my problem Below

java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10

How to change default format at created_at and updated_at value laravel

In your Post model add two accessor methods like this:

public function getCreatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

public function getUpdatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

Now every time you use these properties from your model to show a date these will be presented differently, just the date without the time, for example:

$post = Post::find(1);
echo $post->created_at; // only Y-m-d formatted date will be displayed

So you don't need to change the original type in the database. to change the type in your database you need to change it to Date from Timestamp and you need to do it from your migration (If your using at all) or directly into your database if you are not using migration. The timestamps() method adds these fields (using Migration) and to change these fields during the migration you need to remove the timestamps() method and use date() instead, for example:

$table->date('created_at');
$table->date('updated_at');

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I know this is going to be a late answer, however here is the most correct answer.

In MySQL database, change your timestamp default value into CURRENT_TIMESTAMP. If you have old records with the fake value, you will have to manually fix them.

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

How to convert UTC timestamp to device local time in android

This may help some one with same requirement

private String getDate(long time){
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
        String dateString = formatter.format(new Date(time));
        String date = ""+dateString;
        return date;
    }

iOS Swift - Get the Current Local Time and Date Timestamp

If you code for iOS 13.0 or later and want a timestamp, then you can use:

let currentDate = NSDate.now

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use modern java.time classes if you use java 8 or newer.

String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat.

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

When is a timestamp (auto) updated?

Give the command SHOW CREATE TABLE whatever

Then look at the table definition.

It probably has a line like this

logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

in it. DEFAULT CURRENT_TIMESTAMP means that any INSERT without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP means that any update without an explicit timestamp results in an update to the current timestamp value.

You can control this default behavior when creating your table.

Or, if the timestamp column wasn't created correctly in the first place, you can change it.

ALTER TABLE whatevertable
     CHANGE whatevercolumn 
            whatevercolumn TIMESTAMP NOT NULL
                           DEFAULT CURRENT_TIMESTAMP 
                           ON UPDATE CURRENT_TIMESTAMP;

This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable without changing the timestamp, that is,

To prevent the column from updating when other columns change

then you need to issue this kind of update.

UPDATE whatevertable
   SET something = 'newvalue',
       whatevercolumn = whatevercolumn
 WHERE someindex = 'indexvalue'

This works with TIMESTAMP and DATETIME columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMPs) When you use TIMESTAMPs, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Get records of current month

Check the MySQL Datetime Functions:

Try this:

SELECT * 
FROM tableA 
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND 
      MONTH(columnName) = MONTH(CURRENT_DATE());

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

Creating a file name as a timestamp in a batch job

1) You can download GNU coreutils which comes with GNU date

2) you can use VBScript, which makes date manipulation easier in Windows:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder = "c:\test"
Set objFolder = objFS.GetFolder(strFolder)
current = Now
mth = Month(current)
d = Day(current)
yr = Year(current)
If Len(mth) <2 Then
    mth="0"&mth
End If
If Len(d) < 2 Then
    d = "0"&d
End If
timestamp=yr & "-" & mth &"-"& d
For Each strFile In objFolder.Files
    strFileName = strFile.Name
    If InStr(strFileName,"file_name_here") > 0 Then
        BaseName = objFS.GetBaseName(strFileName)
        Extension = objFS.GetExtensionName(strFileName)
        NewName = BaseName & "-" & timestamp & "." & Extension
        strFile.Name = NewName
    End If
Next

Run the script as:

c:\test> cscript /nologo myscript.vbs

Using current time in UTC as default value in PostgreSQL

What about

now()::timestamp

If your other timestamp are without time zone then this cast will yield the matching type "timestamp without time zone" for the current time.

I would like to read what others think about that option, though. I still don't trust in my understanding of this "with/without" time zone stuff.

EDIT: Adding Michael Ekoka's comment here because it clarifies an important point:

Caveat. The question is about generating default timestamp in UTC for a timestamp column that happens to not store the time zone (perhaps because there's no need to store the time zone if you know that all your timestamps share the same). What your solution does is to generate a local timestamp (which for most people will not necessarily be set to UTC) and store it as a naive timestamp (one that does not specify its time zone).

Converting Date and Time To Unix Timestamp

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

Getting date format m-d-Y H:i:s.u from milliseconds

php.net says:

Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

So use as simple:

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";

Recommended and use dateTime() class from referenced:

$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );

print $d->format("Y-m-d H:i:s.u"); // note at point on "u"

Note u is microseconds (1 seconds = 1000000 µs).

Another example from php.net:

$d2=new DateTime("2012-07-08 11:14:15.889342");

Reference of dateTime() on php.net

I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds

How to convert java.sql.timestamp to LocalDate (java8) java.time?

The accepted answer is not ideal, so I decided to add my 2 cents

timeStamp.toLocalDateTime().toLocalDate();

is a bad solution in general, I'm not even sure why they added this method to the JDK as it makes things really confusing by doing an implicit conversion using the system timezone. Usually when using only java8 date classes the programmer is forced to specify a timezone which is a good thing.

The good solution is

timestamp.toInstant().atZone(zoneId).toLocalDate()

Where zoneId is the timezone you want to use which is typically either ZoneId.systemDefault() if you want to use your system timezone or some hardcoded timezone like ZoneOffset.UTC

The general approach should be

  1. Break free to the new java8 date classes using a class that is directly related, e.g. in our case java.time.Instant is directly related to java.sql.Timestamp, i.e. no timezone conversions are needed between them.
  2. Use the well-designed methods in this java8 class to do the right thing. In our case atZone(zoneId) made it explicit that we are doing a conversion and using a particular timezone for it.

Java Date cut off time information

You can do this to avoid timezone issue:

public static Date truncDate(Date date) {
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

Although Java Date object is timestamp value, but during truncate, it will be converted to local timezone, so you will get surprising value if you expect value from UTC timezone.

How do I automatically update a timestamp in PostgreSQL

Updating timestamp, only if the values changed

Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)

CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
   IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
      NEW.modified = now(); 
      RETURN NEW;
   ELSE
      RETURN OLD;
   END IF;
END;
$$ language 'plpgsql';

How to parse/format dates with LocalDateTime? (Java 8)

Parsing a string with date and time into a particular point in time (Java calls it an "Instant") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time and java.time.chrono, covers almost all needs (except Time Dilation :) ).

However, that complexity brings a lot of confusion.

The key to understand date parsing is:

Why does Java have so many ways to parse a date

  1. There are several systems to measure a time. For instance, the historical Japanese calendars were derived from the time ranges of the reign of the respective emperor or dynasty. Then there is e.g. UNIX timestamp. Fortunately, the whole (business) world managed to use the same.
  2. Historically, the systems were being switched from/to, for various reasons. E.g. from Julian calendar to Gregorian calendar in 1582. So 'western' dates before that need to be treated differently.
  3. And of course the change did not happen at once. Because the calendar came from the headquarteds of some religion and other parts of Europe believed in other dieties, for instance Germany did not switch until the year 1700.

...and why is the LocalDateTime, ZonedDateTime et al. so complicated

  1. There are time zones. A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
    The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.

  2. There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
    If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
    Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."

  3. Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.

To make it a bit more complicated (but that's not too important for your use case) :

  1. The scientists observe Earth's dynamic, which changes over time; based on that, they add seconds at the end of individual years. (So 2040-12-31 24:00:00 may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.
  2. The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.

    Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.

  3. Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00 may be off a couple of seconds from the future parsing.

JDK's APIs for this evolved with the contemporary needs

  • The early Java releases had just java.util.Date which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.
  • Also, the needs of the databases were different, so quite early, java.sql.Date was introduced, with it's own limitations.
  • Because neither covered different calendars and time zones well, the Calendar API was introduced.
  • This still did not cover the complexity of the time zones. And yet, the mix of the above APIs was really a pain to work with. So as Java developers started working on global web applications, libraries that targeted most use cases, like JodaTime, got quickly popular. JodaTime was the de-facto standard for about a decade.
  • But the JDK did not integrate with JodaTime, so working with it was a bit cumbersome. So, after a very long discussion on how to approach the matter, JSR-310 was created mainly based on JodaTime.

How to deal with it in Java's java.time

Determine what type to parse a timestamp to

When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.

Does it contain the date and the time?

  1. Does it have a time offset?
    A time offset is the +hh:mm part. Sometimes, +00:00 may be substituted with Z as 'Zulu time', UTC as Universal Time Coordinated, or GMT as Greenwich Mean Time. These also set the time zone.
    For these timestamps, you use OffsetDateTime.

  2. Does it have a time zone?
    For these timestamps, you use ZonedDateTime.
    Zone is specified either by

    • name ("Prague", "Pacific Standard Time", "PST"), or
    • "zone ID" ("America/Los_Angeles", "Europe/London"), represented by java.time.ZoneId.

    The list of time zones is compiled by a "TZ database", backed by ICAAN.

    According to ZoneId's javadoc, The zone id's can also somehow be specified as Z and offset. I'm not sure how this maps to real zones. If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle, see below.

  3. If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime and converted to OffsetDateTime by adding the missing info:

    • You can assume that it is a UTC time. Add the UTC offset of 0 hours.
    • You can assume that it is a time of the place where the conversion is happening. Convert it by adding the system's time zone.
    • You can neglect and just use it as is. That is useful e.g. to compare or substract two times (see Duration), or when you don't know and it doesn't really matter (e.g. local bus schedule).

Partial time information

  • Based on what the timestamp contains, you can take LocalDate, LocalTime, OffsetTime, MonthDay, Year, or YearMonth out of it.

If you have the full information, you can get a java.time.Instant. This is also internally used to convert between OffsetDateTime and ZonedDateTime.

Figure out how to parse it

There is an extensive documentation on DateTimeFormatter which can both parse a timestamp string and format to string.

The pre-created DateTimeFormatters should cover moreless all standard timestamp formats. For instance, ISO_INSTANT can parse 2011-12-03T10:15:30.123457Z.

If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).

private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
   .parseCaseInsensitive()
   .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
   .toFormatter();

I recommend to look at the source code of DateTimeFormatter and get inspired on how to build one using DateTimeFormatterBuilder. While you're there, also have a look at ResolverStyle which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.

TemporalAccessor

Now, the frequent mistake is to go into the complexity of TemporalAccessor. This comes from how the developers were used to work with SimpleDateFormatter.parse(String). Right, DateTimeFormatter.parse("...") gives you TemporalAccessor.

// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");

But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);

You do not actually need to the DateTimeFormatter either. The types you want to parse have the parse(String) methods.

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");

Regarding TemporalAccessor, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.

I hope I shed some light of understanding onto your soul :)

Note: There's a backport of java.time to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.

[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )

Convert timestamp in milliseconds to string formatted time in Java

Try this:

Date date = new Date(logEvent.timeSTamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateFormatted = formatter.format(date);

See SimpleDateFormat for a description of other format strings that the class accepts.

See runnable example using input of 1200 ms.

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

How to select rows that have current day's timestamp?

If you want to compare with a particular date , You can directly write it like :

select * from `table_name` where timestamp >= '2018-07-07';

// here the timestamp is the name of the column having type as timestamp

or

For fetching today date , CURDATE() function is available , so :

select * from `table_name` where timestamp >=  CURDATE();

How to have an automatic timestamp in SQLite?

Just declare a default value for a field:

CREATE TABLE MyTable(
    ID INTEGER PRIMARY KEY,
    Name TEXT,
    Other STUFF,
    Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

How to get current timestamp in milliseconds since 1970 just the way Java gets

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

SQL Server: Cannot insert an explicit value into a timestamp column

If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.

This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:

var dateNow = new Date();  
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();

postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);

How to get correct timestamp in C#

For UTC:

string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

For local system:

string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

How to convert TimeStamp to Date in Java?

Assuming you have a pre-existing java.util.Date date:

Timestamp timestamp = new Timestamp(long);
date.setTime( l_timestamp.getTime() );

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

I used yet another trick to format date with 6-digit precision (microseconds):

System.out.println(
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.").format(microseconds/1000)
    +String.format("%06d", microseconds%1000000));

This technique can be extended further, to nanoseconds and up.

NOW() function in PHP

If you want to get time now including AM / PM

<?php 
    $time_now = date("Y-m-d h:i:s a");
    echo $time_now;
?>

It outputs 2020-05-01 05:45:28 pm

or

<?php 
    $time_now = date("Y-m-d h:i:s A");
    echo $time_now;
?>

It outputs 2020-05-01 05:45:28 PM

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here's the real answer.

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

CURRENT_TIMESTAMP in milliseconds

In mysql, it is possible to use the uuid function to extract milliseconds.

select conv( 
            concat(
                   substring(uid,16,3), 
                   substring(uid,10,4), 
                   substring(uid,1,8))
                   ,16,10) 
            div 10000 
            - (141427 * 24 * 60 * 60 * 1000) as current_mills
from (select uuid() uid) as alias;

Result:

+---------------+
| current_mills |
+---------------+
| 1410954031133 |
+---------------+

It also works in older mysql versions!

Thank you to this page: http://rpbouman.blogspot.com.es/2014/06/mysql-extracting-timstamp-and-mac.html

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Best timestamp format for CSV/Excel?

I believe if you used the double data type, the re-calculation in Excel would work just fine.

Getting time and date from timestamp with php

You can try this:

For Date:

$date = new DateTime($from_date);
$date = $date->format('d-m-Y');

For Time:

$time = new DateTime($from_date);
$time = $time->format('H:i:s');

Compare two Timestamp in java

java.util.Date mytime = null;
if (mytime.after(now) && mytime.before(last_download_time) )

Worked for me

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

How to get UTC timestamp in Ruby?

You could use: Time.now.to_i.

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

Current timestamp as filename in Java

try this one

String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

This works for me in python 2.7

 select some_date::DATE from some_table;

MySQL convert date string to Unix timestamp

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

Documentation: UNIX_TIMESTAMP, FROM_UNIXTIME

Calculating time difference between 2 dates in minutes

I am using below code for today and database date.

TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

According to the documentation, the first argument can be any of the following:

MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

How do you get a timestamp in JavaScript?

var d = new Date();
console.log(d.valueOf()); 

How do I add 24 hours to a unix timestamp in php?

As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:

 <?php echo strtotime('+1 day'); ?>

Above code will add 1 day or 24 hours to your current timestamp.

in place of +1 day you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.

examples from the manual are as below:

<?php
     echo strtotime("now"), "\n";
     echo strtotime("10 September 2000"), "\n";
     echo strtotime("+1 day"), "\n";
     echo strtotime("+1 week"), "\n";
     echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
     echo strtotime("next Thursday"), "\n";
     echo strtotime("last Monday"), "\n";
?>

Get current time as formatted string in Go?

All the other response are very miss-leading for somebody coming from google and looking for "timestamp in go"! YYYYMMDDhhmmss is not a "timestamp".

To get the "timestamp" of a date in go (number of seconds from january 1970), the correct function is .Unix(), and it really return an integer

Current time in microseconds in java

As other posters already indicated; your system clock is probably not synchronized up to microseconds to actual world time. Nonetheless are microsecond precision timestamps useful as a hybrid for both indicating current wall time, and measuring/profiling the duration of things.

I label all events/messages written to a log files using timestamps like "2012-10-21 19:13:45.267128". These convey both when it happened ("wall" time), and can also be used to measure the duration between this and the next event in the log file (relative difference in microseconds).

To achieve this, you need to link System.currentTimeMillis() with System.nanoTime() and work exclusively with System.nanoTime() from that moment forward. Example code:

/**
 * Class to generate timestamps with microsecond precision
 * For example: MicroTimestamp.INSTANCE.get() = "2012-10-21 19:13:45.267128"
 */ 
public enum MicroTimestamp 
{  INSTANCE ;

   private long              startDate ;
   private long              startNanoseconds ;
   private SimpleDateFormat  dateFormat ;

   private MicroTimestamp()
   {  this.startDate = System.currentTimeMillis() ;
      this.startNanoseconds = System.nanoTime() ;
      this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;
   }

   public String get()
   {  long microSeconds = (System.nanoTime() - this.startNanoseconds) / 1000 ;
      long date = this.startDate + (microSeconds/1000) ;
      return this.dateFormat.format(date) + String.format("%03d", microSeconds % 1000) ;
   }
}

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

get UTC timestamp in python with datetime

The accepted answer seems not work for me. My solution:

import time
utc_0 = int(time.mktime(datetime(1970, 01, 01).timetuple()))
def datetime2ts(dt):
    """Converts a datetime object to UTC timestamp"""
    return int(time.mktime(dt.utctimetuple())) - utc_0

Need to get current timestamp in Java

I did it like this when I wanted a tmiestamp

    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());

Hope it helps :) As a newbie I think it's self-explanatory

I think you also need import java.text.SimpleDateFormat; header for it to work :))

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

Convert LocalDate to LocalDateTime or java.sql.Timestamp

JodaTime

To convert JodaTime's org.joda.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());

To convert JodaTime's org.joda.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());

JavaTime

To convert Java8's java.time.LocalDate to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());

To convert Java8's java.time.LocalDateTime to java.sql.Timestamp, just do

Timestamp timestamp = Timestamp.valueOf(localDateTime);

How can one change the timestamp of an old commit in Git?

Use git filter-branch with an env filter that sets GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for the specific hash of the commit you're looking to fix.

This will invalidate that and all future hashes.

Example:

If you wanted to change the dates of commit 119f9ecf58069b265ab22f1f97d2b648faf932e0, you could do so with something like this:

git filter-branch --env-filter \
    'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
     then
         export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
         export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
     fi'

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

best practice to generate random token for forgot password

This may be helpful whenever you need a very very random token

<?php
   echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>

Timestamp Difference In Hours for PostgreSQL

Get fields where a timestamp is greater than date in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > to_date('05 Dec 2000', 'DD Mon YYYY');

Subtract minutes from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 minutes'

Subtract hours from timestamp in postgresql:

SELECT * from yourtable 
WHERE your_timestamp_field > current_timestamp - interval '5 hours'

Java: Date from unix timestamp

For 1280512800, multiply by 1000, since java is expecting milliseconds:

java.util.Date time=new java.util.Date((long)timeStamp*1000);

If you already had milliseconds, then just new java.util.Date((long)timeStamp);

From the documentation:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Ruby/Rails: converting a Date to a UNIX timestamp

DateTime.new(2012, 1, 15).to_time.to_i

Timestamp to human readable format

getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth()+1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())

var timestamp = 1301090400,
date = new Date(timestamp * 1000),
datevalues = [
   date.getFullYear(),
   date.getMonth()+1,
   date.getDate(),
   date.getHours(),
   date.getMinutes(),
   date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]

JavaScript unit test tools for TDD

The JavaScript section of the Wikipedia entry, List of Unit Testing Frameworks, provides a list of available choices. It indicates whether they work client-side, server-side, or both.

SyntaxError: Unexpected token o in JSON at position 1

Don't ever use JSON.parse without wrapping it in try-catch block:

// payload 
let userData = null;

try {
    // Parse a JSON
    userData = JSON.parse(payload); 
} catch (e) {
    // You can read e for more info
    // Let's assume the error is that we already have parsed the payload
    // So just return that
    userData = payload;
}

// Now userData is the parsed result

What is the difference between static_cast<> and C style casting?

static_cast checks at compile time that conversion is not between obviously incompatible types. Contrary to dynamic_cast, no check for types compatibility is done at run time. Also, static_cast conversion is not necessarily safe.

static_cast is used to convert from pointer to base class to pointer to derived class, or between native types, such as enum to int or float to int.

The user of static_cast must make sure that the conversion is safe.

The C-style cast does not perform any check, either at compile or at run time.

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

how to convert JSONArray to List of Object using camel-jackson

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("Compemployes");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.

python max function using 'key' and lambda expression

lambda is an anonymous function, it is equivalent to:

def func(p):
   return p.totalScore     

Now max becomes:

max(players, key=func)

But as def statements are compound statements they can't be used where an expression is required, that's why sometimes lambda's are used.

Note that lambda is equivalent to what you'd put in a return statement of a def. Thus, you can't use statements inside a lambda, only expressions are allowed.


What does max do?

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

So, it simply returns the object that is the largest.


How does key work?

By default in Python 2 key compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).

To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key argument.

Example 1:

A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.

>>> lis = ['1', '100', '111', '2']

Here max compares the items using their original values (strings are compared lexicographically so you'd get '2' as output) :

>>> max(lis)
'2'

To compare the items by their integer value use key with a simple lambda:

>>> max(lis, key=lambda x:int(x))  # compare `int` version of each item
'111'

Example 2: Applying max to a list of tuples.

>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]

By default max will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:

>>> max(lis)
(4, 'e')

But, what if you wanted to compare each item by the value at index 1? Simple: use lambda:

>>> max(lis, key = lambda x: x[1])
(-1, 'z')

Comparing items in an iterable that contains objects of different type:

List with mixed items:

lis = ['1','100','111','2', 2, 2.57]

In Python 2 it is possible to compare items of two different types:

>>> max(lis)  # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x))  # compare integer version of each item
'111'

But in Python 3 you can't do that any more:

>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
  File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
    max(lis)
TypeError: unorderable types: int() > str()

But this works, as we are comparing integer version of each object:

>>> max(lis, key=lambda x: int(x))  # or simply `max(lis, key=int)`
'111'

Storing data into list with class

You need to add an instance of the class:

lstemail.Add(new EmailData { FirstName = "John", LastName = "Smith", Location = "Los Angeles"});

I would recommend adding a constructor to your class, however:

public class EmailData
{
    public EmailData(string firstName, string lastName, string location)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Location = location;
    }
    public string FirstName{ set; get; }
    public string LastName { set; get; }
    public string Location{ set; get; }
}

This would allow you to write the addition to your list using the constructor:

lstemail.Add(new EmailData("John", "Smith", "Los Angeles"));

set value of input field by php variable's value

One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -

<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
    $value1=$_POST['value1'];
    $value2=$_POST['value2'];
    $sign=$_POST['sign'];
    ...
        //Adding to $result variable
    if($sign=='-') {
      $result = $value1-$value2;
    }
    //Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">

How to switch to the new browser window, which opens after click on the button?

This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window

String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
   for(String windowHandle  : handles)
       {
       if(!windowHandle.equals(parentWindow))
          {
          driver.switchTo().window(windowHandle);
         <!--Perform your operation here for new window-->
         driver.close(); //closing child window
         driver.switchTo().window(parentWindow); //cntrl to parent window
          }
       }

Has anyone ever got a remote JMX JConsole to work?

When testing/debugging/diagnosing remote JMX problems, first always try to connect on the same host that contains the MBeanServer (i.e. localhost), to rule out network and other non-JMX specific problems.

element with the max height from a set of elements

Use .map() and Math.max.

var maxHeight = Math.max.apply(null, $("div.panel").map(function ()
{
    return $(this).height();
}).get());

If that's confusing to read, this might be clearer:

var heights = $("div.panel").map(function ()
    {
        return $(this).height();
    }).get();

maxHeight = Math.max.apply(null, heights);

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

No resource found that matches the given name '@style/Theme.AppCompat.Light'

The steps described above do work, however I've encountered this problem on IntelliJ IDEA and have found that I'm having these problems with existing projects and the only solution is to remove the 'appcompat' module (not the library) and re-import it.

Blank HTML SELECT without blank item in dropdown list

Here is a simple way to do it using plain JavaScript. This is the vanilla equivalent of the jQuery script posted by pimvdb. You can test it here.

<script type='text/javascript'>
  window.onload = function(){
    document.getElementById('id_here').selectedIndex = -1;
  }
</script>

.

<select id="id_here">
  <option>aaaa</option>
  <option>bbbb</option>
</select>

Make sure the "id_here" matches in the form and in the JavaScript.

How to escape special characters of a string with single backslashes

We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr

How to get indices of a sorted array in Python

Essentially you need to do an argsort, what implementation you need depends if you want to use external libraries (e.g. NumPy) or if you want to stay pure-Python without dependencies.

The question you need to ask yourself is: Do you want the

  • indices that would sort the array/list
  • indices that the elements would have in the sorted array/list

Unfortunately the example in the question doesn't make it clear what is desired because both will give the same result:

>>> arr = np.array([1, 2, 3, 100, 5])

>>> np.argsort(np.argsort(arr))
array([0, 1, 2, 4, 3], dtype=int64)

>>> np.argsort(arr)
array([0, 1, 2, 4, 3], dtype=int64)

Choosing the argsort implementation

If you have NumPy at your disposal you can simply use the function numpy.argsort or method numpy.ndarray.argsort.

An implementation without NumPy was mentioned in some other answers already, so I'll just recap the fastest solution according to the benchmark answer here

def argsort(l):
    return sorted(range(len(l)), key=l.__getitem__)

Getting the indices that would sort the array/list

To get the indices that would sort the array/list you can simply call argsort on the array or list. I'm using the NumPy versions here but the Python implementation should give the same results

>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(arr)
array([1, 2, 0, 3], dtype=int64)

The result contains the indices that are needed to get the sorted array.

Since the sorted array would be [1, 2, 3, 4] the argsorted array contains the indices of these elements in the original.

  • The smallest value is 1 and it is at index 1 in the original so the first element of the result is 1.
  • The 2 is at index 2 in the original so the second element of the result is 2.
  • The 3 is at index 0 in the original so the third element of the result is 0.
  • The largest value 4 and it is at index 3 in the original so the last element of the result is 3.

Getting the indices that the elements would have in the sorted array/list

In this case you would need to apply argsort twice:

>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(np.argsort(arr))
array([2, 0, 1, 3], dtype=int64)

In this case :

  • the first element of the original is 3, which is the third largest value so it would have index 2 in the sorted array/list so the first element is 2.
  • the second element of the original is 1, which is the smallest value so it would have index 0 in the sorted array/list so the second element is 0.
  • the third element of the original is 2, which is the second-smallest value so it would have index 1 in the sorted array/list so the third element is 1.
  • the fourth element of the original is 4 which is the largest value so it would have index 3 in the sorted array/list so the last element is 3.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

Here's a fix to invoketheshell's buggy code (which currently appears as the accepted answer):

def performance_measure(y_actual, y_hat):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

    for i in range(len(y_hat)): 
        if y_actual[i] == y_hat[i]==1:
            TP += 1
        if y_hat[i] == 1 and y_actual[i] == 0:
            FP += 1
        if y_hat[i] == y_actual[i] == 0:
            TN +=1
        if y_hat[i] == 0 and y_actual[i] == 1:
            FN +=1

    return(TP, FP, TN, FN)

How do I make a composite key with SQL Server Management Studio?

Highlight both rows in the table design view and click on the key icon, they will now be a composite primary key.

I'm not sure of your question, but only one column per table may be an IDENTITY column, not both.

How to change the decimal separator of DecimalFormat from comma to dot/point?

BigDecimal does not seem to respect Locale settings.

Locale.getDefault(); //returns sl_SI

Slovenian locale should have a decimal comma. Guess I had strange misconceptions regarding numbers.

a = new BigDecimal("1,2") //throws exception
a = new BigDecimal("1.2") //is ok

a.toPlainString() // returns "1.2" always

I have edited a part of my message that made no sense since it proved to be due the human error (forgot to commit data and was looking at the wrong thing).

Same as BigDecimal can be said for any Java .toString() functions. I guess that is good in some ways. Serialization for example or debugging. There is an unique string representation.

Also as others mentioned using formatters works OK. Just use formatters, same for the JSF frontend, formatters do the job properly and are aware of the locale.

How to set image to UIImage

Just Follow This

UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 300, 400)];
[imgview setImage:[UIImage imageNamed:@"YourImageName"]];
[imgview setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imgview];

Getting windbg without the whole WDK?

If you're on Windows 7 x64, the solution provided by Sukesh doesn't work.

I managed to install the debugging tools by downloading the Windows SDK installer for Windows 8 (here), and then choosing "Debugging Tools for Windows" in the installer:

screenshot

Share Text on Facebook from Android App via ACTION_SEND

Check this out : By this we can check activity results also....
// Open all sharing option for user
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    sharingIntent.setType("text/plain");                    
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ShortDesc+" from "+BusinessName);
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ShortDesc+" "+ShareURL);
                    sharingIntent.putExtra(Intent.EXTRA_TITLE, ShortDesc+" "+ShareURL);
                    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"),1000);
/**
     * Get the result when we share any data to another activity 
     * */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
        case 1000:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Activity 1 returned NOT OK", Toast.LENGTH_LONG).show();
            break;
        case 1002:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
            break;
        }// end switch



    }// end onActivityResult

Get first n characters of a string

substr() would be best, you'll also want to check the length of the string first

$str = 'someLongString';
$max = 7;

if(strlen($str) > $max) {
   $str = substr($str, 0, $max) . '...';
}

wordwrap won't trim the string down, just split it up...

Get index of a row of a pandas dataframe as an integer

Little sum up for searching by row:

This can be useful if you don't know the column values ??or if columns have non-numeric values

if u want get index number as integer u can also do:

item = df[4:5].index.item()
print(item)
4

it also works in numpy / list:

numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]

in [x] u pick number in range [4:7], for example if u want 6:

numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6

for DataFrame:

df[4:7]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449

or:

df[(df.index>=4) & (df.index<7)]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449   

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

I ran into the same problem. My fix was changing <parameter value="v12.0" /> to <parameter value="mssqllocaldb" /> into the "app.config" file.

Protect .NET code from reverse engineering?

  • Use online update to block those unlicensed copies.

  • Verify serial number from different modules of your application and do not use a single function call to do the verification (so that crackers cannot bypass the verification easily).

  • Not only check serial number at startup, do the verification while saving data, do it every Friday evening, do it when user is idle ...

  • Verify application file check sum, store your security check sum in different places.

  • Don't go too far on these kind of tricks, make sure your application never crash/get into malfunction while verifying registration code.

  • Build a useful app for users is much more important than make a
    unbreakable binary for crackers.

Centering Bootstrap input fields

Try applying this style to your div class="input-group":

text-align:center;

View it: Fiddle.

Best /Fastest way to read an Excel Sheet into a DataTable?

I've used this method and for me, it is so efficient and fast.

// Step 1. Download NuGet source of Generic Parsing by Andrew Rissing
// Step 2. Reference this to your project
// Step 3. Reference Microsoft.Office.Interop.Excel to your project
// Step 4. Follow the logic below

public static DataTable ExcelSheetToDataTable(string filePath) {

    // Save a copy of the Excel file as CSV
    var xlApp = new XL.Application();
    var xlWbk = xlApp.Workbooks.Open(filePath);
    var tempPath =
        Path.Combine(Environment
            .GetFolderPath(Environment.SpecialFolder.UserProfile)
            , "AppData"
            , "Local",
            , "Temp"
            , Path.GetFileNameWithoutExtension(filePath) + ".csv");

    xlApp.DisplayAlerts = false;
    xlWbk.SaveAs(tempPath, XL.XlFileFormat.xlCSV);
    xlWbk.Close(SaveChanges: false);
    xlApp.Quit();

    // The actual parsing
    using (var parser = new GenericParserAdapter(tempPath)) {
        parser.FirstRowHasHeader = true;
        return parser.GetDataTable();
    }

}

Generic Parsing by Andrew Rissing

C# Passing Function as Argument

Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:

public delegate double MyFunction(double x);

public double Diff(double x, MyFunction f)
{
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

public double MyFunctionMethod(double x)
{
    // Can add more complicated logic here
    return x + 10;
}

public void Client()
{
    double result = Diff(1.234, x => x * 456.1234);
    double secondResult = Diff(2.345, MyFunctionMethod);
}

List all files from a directory recursively with Java

I personally like this version of FileUtils. Here's an example that finds all mp3s or flacs in a directory or any of its subdirectories:

String[] types = {"mp3", "flac"};
Collection<File> files2 = FileUtils.listFiles(/path/to/your/dir, types , true);

How to redirect output of an already running process

I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.

how to bind datatable to datagridview in c#

for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by :

public DataTable  getAllUsers()
    {
        OracleConnection Connection = new OracleConnection(stringConnection);
        Connection.ConnectionString = stringConnection;
        Connection.Open();

        DataSet dataSet = new DataSet();

        OracleCommand cmd = new OracleCommand("semect * from Users");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Connection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet.Tables[0];
    }

step 2- set the return result to DataGridView :

public void setTableToDgv(DataGridView DGV, DataTable table)
    {
        DGV.DataSource = table;
    }

using example:

    setTableToDgv(dgv_client,getAllUsers());

Text size of android design TabLayout tabs

I was using Android Pie and nothing seemed to worked so I played around with app:tabTextAppearance attribute. I know its not the perfect answer but might help someone.

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabTextAppearance="@style/TextAppearance.AppCompat.Caption" />

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

Placing/Overlapping(z-index) a view above another view in android

RelativeLayout works the same way, the last image in the relative layout wins.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

Just add AsEnumerable() andToList() , so it looks like this

db.Favorites
    .Where(x => x.userId == userId)
    .Join(db.Person, x => x.personId, y => y.personId, (x, y).ToList().AsEnumerable()

ToList().AsEnumerable()

getaddrinfo: nodename nor servname provided, or not known

I had this problem running rake db:create. This page clued me into the DNS issue. I checked my VPN connection and found it was disconnected for some reason. I reconnected and now rake worked without a hitch.

How to set HttpResponse timeout for Android in Java

To set settings on the client:

AndroidHttpClient client = AndroidHttpClient.newInstance("Awesome User Agent V/1.0");
HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
HttpConnectionParams.setSoTimeout(client.getParams(), 5000);

I've used this successfully on JellyBean, but should also work for older platforms ....

HTH

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Another possible solution:

? Restart your Visual Studio Instance with Administrator Rights

enter image description here

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

How to overload __init__ method based on argument type?

Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:

Here's a sample (this is a read method and not a constructor, but the idea is the same):

def read(self, str=None, filename=None, addr=0):
    """ Read binary data and return a store object. The data
        store is also saved in the interal 'data' attribute.

        The data can either be taken from a string (str 
        argument) or a file (provide a filename, which will 
        be read in binary mode). If both are provided, the str 
        will be used. If neither is provided, an ArgumentError 
        is raised.
    """
    if str is None:
        if filename is None:
            raise ArgumentError('Please supply a string or a filename')

        file = open(filename, 'rb')
        str = file.read()
        file.close()
    ...
    ... # rest of code

The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:

obj.read(filename="blob.txt")

And to read it from a string, I say:

obj.read(str="\x34\x55")

This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex

Check existence of directory and create if doesn't exist

As of April 16, 2015, with the release of R 3.2.0 there's a new function called dir.exists(). To use this function and create the directory if it doesn't exist, you can use:

ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didn't exist but was succesfully created.

Note that to simply check if the directory exists you can use

dir.exists(file.path(mainDir, subDir))

Vim multiline editing like in sublimetext?

Those are some good out-of-the box solutions given above, but we can also try some plugins which provide multiple cursors like Sublime.

I think this one looks promising:

It seemed abandoned for a while, but has had some contributions in 2014.

It is quite powerful, although it took me a little while to get used to the flow (which is quite Sublime-like but still modal like Vim).

In my experience if you have a lot of other plugins installed, you may meet some conflicts!

There are some others attempts at this feature:

Please feel free to edit if you notice any of these undergoing improvement.

Exception from HRESULT: 0x800A03EC Error

I was getting the same error but it's sorted now. In my case, I had columns with the heading "Key1", "Key2", and "Key3". I have changed the column names to something else and it's sorted.

It seems that these are reserved keywords.

Regards, Mahesh

Using the "With Clause" SQL Server 2008

There are two types of WITH clauses:

Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).

;WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

Here is a select statement also using a WITH clause

SELECT * FROM orders WITH (NOLOCK) where order_id = 123

Zoom to fit all markers in Mapbox or Leaflet

var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());

Timeout jQuery effects

Ben Alman wrote a sweet plugin for jQuery called doTimeout. It has a lot of nice features!

Check it out here: jQuery doTimeout: Like setTimeout, but better.

Horizontal ListView in Android?

You can use RecyclerView in the support library. RecyclerView is a generalized version of ListView that supports:

  • A layout manager for positioning items
  • Default animations for common item operations

Android Recycler View Docs

Angular bootstrap datepicker date format does not format ng-model value

With so many answers already written, Here's my take.

With Angular 1.5.6 & ui-bootstrap 1.3.3 , just add this on the model & you are done.

ng-model-options="{timezone: 'UTC'}" 

Note: Use this only if you are concerned about the date being 1 day behind & not bothered with extra time of T00:00:00.000Z

Updated Plunkr Here :

http://plnkr.co/edit/nncmB5EHEUkZJXRwz5QI?p=preview

Add a fragment to the URL without causing a redirect?

window.location.hash = 'whatever';

nuget 'packages' element is not declared warning

The problem is, you need a xsd schema for packages.config.

This is how you can create a schema (I found it here):

Open your Config file -> XML -> Create Schema

enter image description here

This would create a packages.xsd for you, and opens it in Visual Studio:

enter image description here

In my case, packages.xsd was created under this path:

C:\Users\MyUserName\AppData\Local\Temp

Now I don't want to reference the packages.xsd from a Temp folder, but I want it to be added to my solution and added to source control, so other users can get it... so I copied packages.xsd and pasted it into my solution folder. Then I added the file to my solution:

1. Copy packages.xsd in the same folder as your solution

2. From VS, right click on solution -> Add -> Existing Item... and then add packages.xsd

enter image description here

So, now we have created packages.xsd and added it to the Solution. All we need to do is to tell the config file to use this schema.

Open the config file, then from the top menu select:

XML -> Schemas...

Add your packages.xsd, and select Use this schema (see below)

enter image description here

Change Button color onClick

Using jquery, try this. if your button id is say id= clickme

$("clickme").on('çlick', function(){

$(this).css('background-color', 'grey'); .......

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

How to get a index value from foreach loop in jstl

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

above line was giving me an error. So I wrote down in below way which is working fine for me.

<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>

Maybe someone else might get same error. Look at this guys!

Turn off deprecated errors in PHP 5.3

this error occur when you change your php version: it's very simple to suppress this error message

To suppress the DEPRECATED Error message, just add below code into your index.php file:

init_set('display_errors',False);

What are the best practices for SQLite on Android?

Concurrent Database Access

Same article on my blog(I like formatting more)

I wrote small article which describe how to make access to your android database thread safe.


Assuming you have your own SQLiteOpenHelper.

public class DatabaseHelper extends SQLiteOpenHelper { ... }

Now you want to write data to database in separate threads.

 // Thread 1
 Context context = getApplicationContext();
 DatabaseHelper helper = new DatabaseHelper(context);
 SQLiteDatabase database = helper.getWritableDatabase();
 database.insert(…);
 database.close();

 // Thread 2
 Context context = getApplicationContext();
 DatabaseHelper helper = new DatabaseHelper(context);
 SQLiteDatabase database = helper.getWritableDatabase();
 database.insert(…);
 database.close();

You will get following message in your logcat and one of your changes will not be written.

android.database.sqlite.SQLiteDatabaseLockedException: database is locked (code 5)

This is happening because every time you create new SQLiteOpenHelper object you are actually making new database connection. If you try to write to the database from actual distinct connections at the same time, one will fail. (from answer above)

To use database with multiple threads we need to make sure we are using one database connection.

Let’s make singleton class Database Manager which will hold and return single SQLiteOpenHelper object.

public class DatabaseManager {

    private static DatabaseManager instance;
    private static SQLiteOpenHelper mDatabaseHelper;

    public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = helper;
        }
    }

    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                    " is not initialized, call initialize(..) method first.");
        }

        return instance;
    }

    public SQLiteDatabase getDatabase() {
        return new mDatabaseHelper.getWritableDatabase();
    }

}

Updated code which write data to database in separate threads will look like this.

 // In your application class
 DatabaseManager.initializeInstance(new MySQLiteOpenHelper());
 // Thread 1
 DatabaseManager manager = DatabaseManager.getInstance();
 SQLiteDatabase database = manager.getDatabase()
 database.insert(…);
 database.close();

 // Thread 2
 DatabaseManager manager = DatabaseManager.getInstance();
 SQLiteDatabase database = manager.getDatabase()
 database.insert(…);
 database.close();

This will bring you another crash.

java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase

Since we are using only one database connection, method getDatabase() return same instance of SQLiteDatabase object for Thread1 and Thread2. What is happening, Thread1 may close database, while Thread2 is still using it. That’s why we have IllegalStateException crash.

We need to make sure no-one is using database and only then close it. Some folks on stackoveflow recommended to never close your SQLiteDatabase. This will result in following logcat message.

Leak found
Caused by: java.lang.IllegalStateException: SQLiteDatabase created and never closed

Working sample

public class DatabaseManager {

    private int mOpenCounter;

    private static DatabaseManager instance;
    private static SQLiteOpenHelper mDatabaseHelper;
    private SQLiteDatabase mDatabase;

    public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
        if (instance == null) {
            instance = new DatabaseManager();
            mDatabaseHelper = helper;
        }
    }

    public static synchronized DatabaseManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
                    " is not initialized, call initializeInstance(..) method first.");
        }

        return instance;
    }

    public synchronized SQLiteDatabase openDatabase() {
        mOpenCounter++;
        if(mOpenCounter == 1) {
            // Opening new database
            mDatabase = mDatabaseHelper.getWritableDatabase();
        }
        return mDatabase;
    }

    public synchronized void closeDatabase() {
        mOpenCounter--;
        if(mOpenCounter == 0) {
            // Closing database
            mDatabase.close();

        }
    }

}

Use it as follows.

SQLiteDatabase database = DatabaseManager.getInstance().openDatabase();
database.insert(...);
// database.close(); Don't close it directly!
DatabaseManager.getInstance().closeDatabase(); // correct way

Every time you need database you should call openDatabase() method of DatabaseManager class. Inside this method, we have a counter, which indicate how many times database is opened. If it equals to one, it means we need to create new database connection, if not, database connection is already created.

The same happens in closeDatabase() method. Every time we call this method, counter is decreased, whenever it goes to zero, we are closing database connection.


Now you should be able to use your database and be sure it's thread safe.

npm check and update package if needed

As of [email protected]+ you can simply do:

npm update <package name>

This will automatically update the package.json file. We don't have to update the latest version manually and then use npm update <package name>

You can still get the old behavior using

npm update --no-save

(Reference)

React - Preventing Form Submission

2 ways

First one we pass the event in the argument right into the onClick.

  onTestClick(e) {
    e.preventDefault();
    alert('here');
  }

  // Look here we pass the args in the onClick
  <Button color="primary" onClick={e => this.onTestClick(e)}>primary</Button>&nbsp;

Second one we pass it into argument and we did right in the onClick

  onTestClick() {
    alert('here');
  }

  // Here we did right inside the onClick, but this is the best way
  <Button color="primary" onClick={e => (e.preventDefault(), this.onTestClick())}>primary</Button>&nbsp;

Hope that can help

Jenkins: Failed to connect to repository

Jenkins runs as another user, not as your ordinary login. So, do as this to solve the ssh problem:

  1. Log on as jenkins su jenkins (you may first have to do sudo passwd jenkins to be able to set the password for jenkins. I couldn't find the default...)
  2. Generate ssh key pair: ssh-keygen
  3. Copy the public key (id_rsa.pub) to your github account (or wherever)
  4. Clone the repo as jenkins in order to have the host added to jenkins known_hosts which is neccessary to do. Now you can remove the cloned repo again if you wish.

Read Variable from Web.Config

If you want the basics, you can access the keys via:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();

To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Why doesn't catching Exception catch RuntimeException?

class Test extends Thread
{
    public void run(){  
        try{  
            Thread.sleep(10000);  
        }catch(InterruptedException e){  
            System.out.println("test1");
            throw new RuntimeException("Thread interrupted..."+e);  
        }  

    }  

    public static void main(String args[]){  
        Test t1=new Test1();  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
            System.out.println("test2");
            System.out.println("Exception handled "+e);
        }  

    }  
}

Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

How do I run a spring boot executable jar in a Production environment?

I start applications that I want to run persistently or at least semi-permanently via screen -dmS NAME /path/to/script. As far as I am informed this is the most elegant solution.

"UnboundLocalError: local variable referenced before assignment" after an if statement

The other answers are correct: You don't have a default value. However, you have another problem in your logic:

You read the same file twice. After reading it once, the cursor is at the end of the file. To solve this, you can do two things: Either open/close the file upon each function call:

def temp_sky(lreq, breq):
    with open("/home/path/to/file",'r') as tfile:
        # do your stuff

This hase the disadvantage of having to open the file each time. The better way would be:

tfile.seek(0)

You do this after your for line in tfile: loop. It resets the cursor to the beginning to the next call will start from there again.

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

(based on anser from Hakan Fistik)

You can also set the postBuffer globally, which might be necessary, if you haven't checkout out the repository yet!

git config http.postBuffer 524288000

Local variable referenced before assignment?

You have to specify that test1 is global:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

Basic HTTP and Bearer Token Authentication

If you are using a reverse proxy such as nginx in between, you could define a custom token, such as X-API-Token.

In nginx you would rewrite it for the upstream proxy (your rest api) to be just auth:

proxy_set_header Authorization $http_x_api_token;

... while nginx can use the original Authorization header to check HTTP AUth.

Amazon S3 boto - how to create a folder?

Use this:

import boto3
s3 = boto3.client('s3')
bucket_name = "YOUR-BUCKET-NAME"
directory_name = "DIRECTORY/THAT/YOU/WANT/TO/CREATE" #it's name of your folders
s3.put_object(Bucket=bucket_name, Key=(directory_name+'/'))

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I took a different approach. I switched to use $.post and the error has gone since then.

Changing website favicon dynamically

Why not?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

Turning PAE/NX on/off didn't work for me. I just needed to turn on virtualization on my computer. I was working on a HP Compaq 8200 and followed the steps below to turn on virtualization. If you are working on a different computer, you probably just need to look up how to turn on virtualization on your pc. The steps below for HP Compaq 8200 (or similar) is copied verbatim from the comment posted by the user qqdmax5 on Hp discussion board here.


To run Oracle VM Virtual Box / VMware machines on 64-bit host there is a need to enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).

Usually these setting are disabled on the level of BIOS.

To enable VTx and VTd you have to change corresponding settings in the BIOS.

Here is an example how to do it for HP Compaq 8200 or similar PC:

  1. Start the machine.
  2. Press F10 to enter BIOS.
  3. Security-> System Security
  4. Enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).
  5. Save and restart the machine.

There is also some discussion on this on askubuntu.

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Facebook API "This app is in development mode"

I had also faced the same issue in which my FB app was automatically stopped and users were not able to login and were getting the message "app is in development mode.....".

Reason why FB automatically stopped my app was that I had not provided a valid PRIVACY policy & terms URL. So, make sure you enter these URLs on your app basic settings page and then make your app PUBLIC from app review page as described in above posts.

How to change the color of a SwitchCompat from AppCompat library

So some days I lack brain cells and:

<android.support.v7.widget.SwitchCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/CustomSwitchStyle"/>

does not apply the theme because style is incorrect. I was supposed to use app:theme :P

<android.support.v7.widget.SwitchCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:theme="@style/CustomSwitchStyle"/>

Whoopsies. This post was what gave me insight into my mistake...hopefully if someone stumbles across this it will help them like it did me. Thank you Gaëtan Maisse for your answer

How to scan multiple paths using the @ComponentScan annotation?

@ComponentScan uses string array, like this:

@ComponentScan({"com.my.package.first","com.my.package.second"})

When you provide multiple package names in only one string, Spring interprets this as one package name, and thus can't find it.

Pure css close button

Hi you can used this code in pure css

as like this

css

.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
 content: "×";
}

HTML

<a href="#" class="arrow"> 
</a>

? Live demo http://jsfiddle.net/rohitazad/VzZhU/

Change mysql user password using command line

Before MySQL 5.7.6 this works from the command line:

mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$w0rdf1sh');"

I don't have a mysql install to test on but I think in your case it would be

mysql -e "UPDATE mysql.user SET Password=PASSWORD('$w0rdf1sh') WHERE User='tate256';"

How to configure SMTP settings in web.config

Web.Config file:

<configuration>
 <system.net>
        <mailSettings>
            <smtp from="[email protected]">
                <network host="smtp.gmail.com" 
                 port="587" 
                 userName="[email protected]" 
                 password="yourpassword" 
                 enableSsl="true"/>
            </smtp>
        </mailSettings>
</system.net>
</configuration>

[] and {} vs list() and dict(), which is better?

there is one difference in behavior between [] and list() as example below shows. we need to use list() if we want to have the list of numbers returned, otherwise we get a map object! No sure how to explain it though.

sth = [(1,2), (3,4),(5,6)]
sth2 = map(lambda x: x[1], sth) 
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>

sth2 = [map(lambda x: x[1], sth)]
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
type(sth2) # list 
type(sth2[0]) # map

sth2 = list(map(lambda x: x[1], sth))
print(sth2) #[2, 4, 6]
type(sth2) # list
type(sth2[0]) # int

Multi-dimensional arrays in Bash

If you want to use a bash script and keep it easy to read recommend putting the data in structured JSON, and then use lightweight tool jq in your bash command to iterate through the array. For example with the following dataset:

[

    {"specialId":"123",
    "specialName":"First"},

    {"specialId":"456",
    "specialName":"Second"},

    {"specialId":"789",
    "specialName":"Third"}
]

You can iterate through this data with a bash script and jq like this:

function loopOverArray(){

    jq -c '.[]' testing.json | while read i; do
        # Do stuff here
        echo "$i"
    done
}

loopOverArray

Outputs:

{"specialId":"123","specialName":"First"}
{"specialId":"456","specialName":"Second"}
{"specialId":"789","specialName":"Third"}

How to store standard error in a variable

This is an interesting problem to which I hoped there was an elegant solution. Sadly, I end up with a solution similar to Mr. Leffler, but I'll add that you can call useless from inside a Bash function for improved readability:

#!/bin/bash

function useless {
    /tmp/useless.sh | sed 's/Output/Useless/'
}

ERROR=$(useless)
echo $ERROR

All other kind of output redirection must be backed by a temporary file.

SSIS Connection Manager Not Storing SQL Password

The designed behavior in SSIS is to prevent storing passwords in a package, because it's bad practice/not safe to do so.

Instead, either use Windows auth, so you don't store secrets in packages or config files, or, if that's really impossible in your environment (maybe you have no Windows domain, for example) then you have to use a workaround as described in http://support.microsoft.com/kb/918760 (Sam's correct, just read further in that article). The simplest answer is a config file to go with the package, but then you have to worry that the config file is stored securely so someone can't just read it and take the credentials.

Get the current year in JavaScript

// Return today's date and time
var currentTime = new Date()

// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1

// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()

// returns the year (four digits)
var year = currentTime.getFullYear()

// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)

LINQ: Select where object does not contain items from list

I have not tried this, so I am not guarantueeing anything, however

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

Escape Character in SQL Server

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

FROM: SQL Server Escape an Underscore

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How to print binary tree diagram?

Print in Console:

                                                500
                       700                                             300   
    200                                   400                                                                                          

Simple code :

public int getHeight()
    {
        if(rootNode == null) return -1;
        return getHeight(rootNode);
    }

    private int getHeight(Node node)
    {
        if(node == null) return -1;

        return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
    }

    public void printBinaryTree(Node rootNode)
    {
        Queue<Node> rootsQueue = new LinkedList<Node>();
        Queue<Node> levelQueue = new LinkedList<Node>();
        levelQueue.add(rootNode);
        int treeHeight = getHeight();
        int firstNodeGap;
        int internalNodeGap;
        int copyinternalNodeGap;
        while(true)
        {
            System.out.println("");
            internalNodeGap = (int)(Math.pow(2, treeHeight + 1) -1);  
            copyinternalNodeGap = internalNodeGap;
            firstNodeGap = internalNodeGap/2;

            boolean levelFirstNode = true;

            while(!levelQueue.isEmpty())
            {
                internalNodeGap = copyinternalNodeGap;
                Node currNode = levelQueue.poll();
                if(currNode != null)
                {
                    if(levelFirstNode)
                    {
                        while(firstNodeGap > 0)
                        {
                            System.out.format("%s", "   ");
                            firstNodeGap--; 
                        }
                        levelFirstNode =false;
                    }
                    else
                    {
                        while(internalNodeGap>0)
                        {
                            internalNodeGap--;
                            System.out.format("%s", "   ");
                        }
                    }
                    System.out.format("%3d",currNode.data);
                    rootsQueue.add(currNode);
                }
            }

            --treeHeight;

            while(!rootsQueue.isEmpty())
            {
                Node currNode = rootsQueue.poll();
                if(currNode != null)
                {
                    levelQueue.add(currNode.left);
                    levelQueue.add(currNode.right);
                }
            }

            if(levelQueue.isEmpty()) break;
        }

    }

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Well, people usually ask this question: Heroku or AWS when starting to deploy something.

My experiment of using both of Heroku & AWS, here is my quick review and comparison:

Heroku

  • One command to deploy whatever your project types: Ruby on Rails, Nodejs
  • So many 1-click to integrate plugins & third parties: It is super easy to start with something.
  • Don't have auto-scaling; that means you need to scale up/down manually
  • Cost is expensive, especially, when system needs more resources
  • Free instance available
  • The free instance goes to sleep if it is inactive.
  • Data center: US & EU only
  • CAN dive into/access to machine level by using Heroku run bash (Thanks, MJafar Mash for the advice) but it is kind of limited! You don't have full access!
  • Don't need to know too much about DevOps

AWS - EC2

  • This just like a machine with pre-config OS (or not), so you need to install software, library to make your website/service go online.
  • Plugin & Library need to be integrated manually, or automation script (public script & written by you)
  • Auto scaling & load balancer are the supported services, just learn how to config & integrate to your system
  • Cost is quite cheap, depends on which services and number of hours you use it
  • There are several free hours for T2.micro instances, but usually, you will pay few dollars every month (if still using T2.micro)
  • Your free instance won't go to sleep, available 24/7 (because you may pay for it :) )
  • Data center: around the world. Pick the region which is the best fit for you.
  • Dive into machine level. So you can enjoy it
  • Some knowledge about DevOps, but it is okay, Stackoverflow is helpful there!

AWS Elastic Beanstalk an alternative of Heroku, but cheaper

  • Elastic Beanstalk was announced as a public beta from 2010; it helps we easier to work with deployment. For detail please go here

  • Beanstalk is free, the cost you will pay will be for the services you use & number of hours of usage.

  • I use Elastic Beanstalk for a long time, and I think it can be the replacement of Heroku and cheaper!

Summary

  • Heroku: Easy at beginning, FREE instance, but expensive later
  • AWS: Not easy, free hours available, kind of cheaper, Beanstalk should be concerned to use

So in my current system, I use Heroku for staging and Beanstalk for production!

Template not provided using create-react-app

Such a weird problem because this worked for me yesterday and I came across the same error this morning. Based on the release notes, a new feature was added to support templates so it looks like a few parts have changed in the command line (for example, the --typescript was deprecated in favor of using --template typescript)

I did manage to get it all working by doing the following:

  1. Uninstall global create-react-app npm uninstall create-react-app -g.
  2. Verify npm cache npm cache verify.
  3. Close terminal. I use the mac terminal, if using an IDE maybe close and re-open.
  4. Re-open terminal, browse to where you want your project and run create-react-app via npx using the new template command conventions. For getting it to work, I used the typescript my-app from the documentation site to ensure consistency: npx create-react-app my-app --template typescript

If it works, you should see multiple installs: one for react-scripts and one for the template. The error message should also no longer appear.

How to copy text programmatically in my Android app?

Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher. https://developer.android.com/about/versions/10/privacy/changes#clipboard-data

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */
}

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
}
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */
}

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

How to backup MySQL database in PHP?

try this 100% working.

<?php
function dbbackup($host,$user,$pass,$name,$tables=false, $backup_name=false)
{ 
set_time_limit(3000); 
$mysqli = new mysqli($host,$user,$pass,$name); 
$mysqli->select_db($name); 
$mysqli->query("SET NAMES 'utf8'");
$queryTables = $mysqli->query('SHOW TABLES'); 
while($row = $queryTables->fetch_row()) 
{ 
    $target_tables[] = $row[0]; 
}   
if($tables !== false) 
{
    $target_tables = array_intersect( $target_tables, $tables); 
} 
$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
foreach($target_tables as $table)
{
    if (empty($table))
    {
        continue;
    } 
    $result = $mysqli->query('SELECT * FROM `'.$table.'`');     $fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;     $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row(); 
    $content .= "\n\n".$TableMLine[1].";\n\n";   $TableMLine[1]=str_ireplace('CREATE TABLE `','CREATE TABLE IF NOT EXISTS `',$TableMLine[1]);
    for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
    {
        while($row = $result->fetch_row())  
        {
            if ($st_counter%100 == 0 || $st_counter == 0 )  
            {
                $content .= "\nINSERT INTO ".$table." VALUES";
            }
            $content .= "\n(";    
            for($j=0; $j<$fields_amount; $j++)
            {
                $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                if (isset($row[$j]))
                {
                    $content .= '"'.$row[$j].'"' ;
                } 
                else
                {
                    $content .= '""';
                }
                if ($j<($fields_amount-1))
                {
                    $content.= ',';
                }  
            }
            $content .=")";
            if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
            {
                $content .= ";";
            }
            else
            {
                $content .= ",";
            }
            $st_counter=$st_counter+1;
        }
    } $content .="\n\n\n";
}
$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
$backup_name = $backup_name ? $backup_name : $name.'___('.date('H-i-s').'_'.date('d-m-Y').').sql';
ob_get_clean(); 
header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header('Content-Length: '. (function_exists('mb_strlen') ? mb_strlen($content, '8bit'): strlen($content)) );   
header("Content-disposition: attachment; filename=\"".$backup_name."\""); 
echo $content; exit;
}
dbbackup("host", "user", "password", "database" );
?>

check on github

How to convert index of a pandas dataframe into a column?

If you want to use the reset_index method and also preserve your existing index you should use:

df.reset_index().set_index('index', drop=False)

or to change it in place:

df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)

For example:

print(df)
          gi  ptt_loc
0  384444683      593
4  384444684      594
9  384444686      596

print(df.reset_index())
   index         gi  ptt_loc
0      0  384444683      593
1      4  384444684      594
2      9  384444686      596

print(df.reset_index().set_index('index', drop=False))
       index         gi  ptt_loc
index
0          0  384444683      593
4          4  384444684      594
9          9  384444686      596

And if you want to get rid of the index label you can do:

df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
   index         gi  ptt_loc
0      0  384444683      593
4      4  384444684      594
9      9  384444686      596

batch script - run command on each file in directory

you can run something like this (paste the code bellow in a .bat, or if you want it to run interractively replace the %% by % :

for %%i in (c:\directory\*.xls) do ssconvert %%i %%i.xlsx

If you can run powershell it will be :

Get-ChildItem -Path c:\directory -filter *.xls | foreach {ssconvert $($_.FullName) $($_.baseName).xlsx }

ES6 class variable alternatives

Still you can't declare any classes like in another programming languages. But you can create as many class variables. But problem is scope of class object. So According to me, Best way OOP Programming in ES6 Javascript:-

class foo{
   constructor(){
     //decalre your all variables
     this.MY_CONST = 3.14;
     this.x = 5;
     this.y = 7;
     // or call another method to declare more variables outside from constructor.
     // now create method level object reference and public level property
     this.MySelf = this;
     // you can also use var modifier rather than property but that is not working good
     let self = this.MySelf;
     //code ......... 
   }
   set MySelf(v){
      this.mySelf = v;
   }
   get MySelf(v){
      return this.mySelf;
   }
   myMethod(cd){
      // now use as object reference it in any method of class
      let self = this.MySelf;
      // now use self as object reference in code
   }
}

How to update nested state properties in React

If you are using ES2015 you have access to the Object.assign. You can use it as follows to update a nested object.

this.setState({
  someProperty: Object.assign({}, this.state.someProperty, {flag: false})
});

You merge the updated properties with the existing and use the returned object to update the state.

Edit: Added an empty object as target to the assign function to make sure the state isn't mutated directly as carkod pointed out.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

The major difference in those factories is when what you want to do with the factories and when you want to use it.

Sometimes, when you are doing IOC (inversion of control e.g. constructor injection), you know that you can create solid objects. As mentioned in the example above of fruits, if you are ready to create objects of fruits, you can use simple factory pattern.

But many times, you do not want to create solid objects, they will come later in the program flow. But the configuration tells you the what kind of factory you want to use at start, instead of creating objects, you can pass on factories which are derived from a common factory class to the constructor in IOC.

So, I think its also about the object lifetime and creation.

How to set socket timeout in C when making multiple connections?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so:

    struct timeval timeout;      
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

    if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
                sizeof(timeout)) < 0)
        error("setsockopt failed\n");

Edit: from the setsockopt man page:

SO_SNDTIMEO is an option to set a timeout value for output operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for output operations to complete. If a send operation has blocked for this much time, it returns with a partial count or with the error EWOULDBLOCK if no data were sent. In the current implementation, this timer is restarted each time additional data are delivered to the protocol, implying that the limit applies to output portions ranging in size from the low-water mark to the high-water mark for output.

SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a struct timeval parameter with the number of seconds and microseconds used to limit waits for input operations to complete. In the current implementation, this timer is restarted each time additional data are received by the protocol, and thus the limit is in effect an inactivity timer. If a receive operation has been blocked for this much time without receiving additional data, it returns with a short count or with the error EWOULDBLOCK if no data were received. The struct timeval parameter must represent a positive time interval; otherwise, setsockopt() returns with the error EDOM.

Python: Passing variables between functions

Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.

def defineAList():
    #list = ['1','2','3'] this creates a new list, named list in the current namespace.
    #same name, different list!

    list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
    print "For checking purposes: in defineAList, list is",list
    return list

Alternatively, you can pass it around:

def main():
    new_list = defineAList()
    useTheList(new_list)

Convert xlsx to csv in Linux with command line

If you are OK to run Java command line then you can do it with Apache POI HSSF's Excel Extractor. It has a main method that says to be the command line extractor. This one seems to just dump everything out. They point out to this example that converts to CSV. You would have to compile it before you can run it but it too has a main method so you should not have to do much coding per se to make it work.

Another option that might fly but will require some work on the other end is to make your Excel files come to you as Excel XML Data or XML Spreadsheet of whatever MS calls that format these days. It will open a whole new world of opportunities for you to slice and dice it the way you want.

How to import an Oracle database from dmp file and log file?

All this peace of code put into *.bat file and run all at once:

My code for creating user in oracle. crate_drop_user.sql file

drop user "USER" cascade;
DROP TABLESPACE "USER";

CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE 
    AUTOEXTEND 
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    SEGMENT SPACE MANAGEMENT  AUTO
/ 

CREATE  TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE 
    'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    UNIFORM SIZE 1M    
/

CREATE USER "USER"  PROFILE "DEFAULT" 
    IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER" 
    TEMPORARY TABLESPACE "USER_TEMP" 
/    

alter user USER quota unlimited on "USER";

GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";

create file import.bat and put this lines in it:

SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log

Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.

Good luck, Ivan

How do I pass multiple ints into a vector at once?

Yes you can, in your case:

vector<int>TestVector;`
for(int i=0;i<5;i++)
{

    TestVector.push_back(2+3*i);
    
} 

Android - default value in editText

Use android android:hint for set default value or android:text

@angular/material/index.d.ts' is not a module

import { MatDialogModule } from '@angular/material/dialog';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';

How to add more than one machine to the trusted hosts list using winrm

winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'

How to print the current time in a Batch-File?

This works with Windows 10, 8.x, 7, and possibly further back:

@echo Started: %date% %time%
.
.
.
@echo Completed: %date% %time%

What is the shortest function for reading a cookie by name in JavaScript?

This will only ever hit document.cookie ONE time. Every subsequent request will be instant.

(function(){
    var cookies;

    function readCookie(name,c,C,i){
        if(cookies){ return cookies[name]; }

        c = document.cookie.split('; ');
        cookies = {};

        for(i=c.length-1; i>=0; i--){
           C = c[i].split('=');
           cookies[C[0]] = C[1];
        }

        return cookies[name];
    }

    window.readCookie = readCookie; // or expose it however you want
})();

I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to 120 bytes:

function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}

You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}

How to enable directory listing in apache web server

I had to disable selinux to make this work. Note. The system needs to be rebooted for selinux to take effect.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

In my case I was able to open the solution in offline mode just running the command:

iisreset

How to fix broken paste clipboard in VNC on Windows

http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html

Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.

To get those clipboard operations back you need to run the program "vncconfig &".

After this your clipboard actions should work fine with out any problems.

Run "vncconfig &" on the client.

How can one develop iPhone apps in Java?

Perhaps you should consider Android applications instead of iPhone applications if you really want to develop in Java for smartphones. Android natively uses Java for it's applications; so perhaps this might be a better option?

As for iPhone, I would recommend you to look into Obj-C or C/C++ depending on the type of applications you want to make. Should be fun to dabble into a new language! :)

What is "406-Not Acceptable Response" in HTTP?

You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:

def create
  post = Post.create params[:post]
  respond_to do |format|
    format.json { render :json => post }
  end
end

Change it to:

def create
  post = Post.create params[:post])
  render :json => post
end

And it will solve your problem. It worked for me :)

CSS to make table 100% of max-width

Use this :

<div style="width:700px; background:#F2F2F2">
    <table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
        <tr align="center" style="margin: 0; padding: 0;">
            <td>
                <table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
                    <tr style="background-color: white;">
                        <td style=" padding: 10px 15px 10px 15px; color: #000000;">
                            <p>Some content here</p>
                            <span style="font-weight: bold;">My Signature</span><br/>
                            My Title<br/>
                            My Company<br/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

Passing a variable from one php include file to another: global vs. not

Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');
global $name;

function foo() {
  echo $name;
}

function bar() {
  echo $name;
}

foo();
bar();

will only show errors. The correct way to do that would be:

include('front.inc');

function foo() {
  global $name;
  echo $name;
}

function bar() {
  global $name;
  echo $name;
}

foo();
bar();

Check if a parameter is null or empty in a stored procedure

I sometimes use NULLIF like so...

IF NULLIF(@PreviousStartDate, '') IS NULL

There's probably no reason it's better than the way suggested by @Oded and @bluefeet, just stylistic preference.

@danihp's method is really cool but my tired old brain wouldn't go to COALESCE when I'm thinking is null or empty :-)

functional way to iterate over range (ES6/7)

Here's an approach using generators:

function* square(n) {
    for (var i = 0; i < n; i++ ) yield i*i;
}

Then you can write

console.log(...square(7));

Another idea is:

[...Array(5)].map((_, i) => i*i)

Array(5) creates an unfilled five-element array. That's how Array works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.

Alternatively, we could write

Array.from(Array(5)).map((_, i) => i*i)

or, we could take advantage of the second argument to Array#from to skip the map and write

Array.from(Array(5), (_, i) => i*i)

A horrible hack which I saw recently, which I do not recommend you use, is

[...1e4+''].map((_, i) => i*i)

Chrome says my extension's manifest file is missing or unreadable

Some permissions issue for default sample.

I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.

Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip

which can be found at
https://developer.chrome.com/extensions/samples

this worked great, hope it helps

How do you save/store objects in SharedPreferences on Android?

An other way to save and restore an object from android sharedpreferences without using the Json format

private static ExampleObject getObject(Context c,String db_name){
            SharedPreferences sharedPreferences = c.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            ExampleObject o = new ExampleObject();
            Field[] fields = o.getClass().getFields();
            try {
                for (Field field : fields) {
                    Class<?> type = field.getType();
                    try {
                        final String name = field.getName();
                        if (type == Character.TYPE || type.equals(String.class)) {
                            field.set(o,sharedPreferences.getString(name, ""));
                        } else if (type.equals(int.class) || type.equals(Short.class))
                            field.setInt(o,sharedPreferences.getInt(name, 0));
                        else if (type.equals(double.class))
                            field.setDouble(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(float.class))
                            field.setFloat(o,sharedPreferences.getFloat(name, 0));
                        else if (type.equals(long.class))
                            field.setLong(o,sharedPreferences.getLong(name, 0));
                        else if (type.equals(Boolean.class))
                            field.setBoolean(o,sharedPreferences.getBoolean(name, false));
                        else if (type.equals(UUID.class))
                            field.set(
                                    o,
                                    UUID.fromString(
                                            sharedPreferences.getString(
                                                    name,
                                                    UUID.nameUUIDFromBytes("".getBytes()).toString()
                                            )
                                    )
                            );

                    } catch (IllegalAccessException e) {
                        Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                    } catch (IllegalArgumentException e) {
                        Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                    }
                }
            } catch (Exception e) {
                System.out.println("Exception: " + e);
            }
            return o;
        }
        private static void setObject(Context context, Object o, String db_name) {
            Field[] fields = o.getClass().getFields();
            SharedPreferences sp = context.getSharedPreferences(db_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            for (Field field : fields) {
                Class<?> type = field.getType();
                try {
                    final String name = field.getName();
                    if (type == Character.TYPE || type.equals(String.class)) {
                        Object value = field.get(o);
                        if (value != null)
                            editor.putString(name, value.toString());
                    } else if (type.equals(int.class) || type.equals(Short.class))
                        editor.putInt(name, field.getInt(o));
                    else if (type.equals(double.class))
                        editor.putFloat(name, (float) field.getDouble(o));
                    else if (type.equals(float.class))
                        editor.putFloat(name, field.getFloat(o));
                    else if (type.equals(long.class))
                        editor.putLong(name, field.getLong(o));
                    else if (type.equals(Boolean.class))
                        editor.putBoolean(name, field.getBoolean(o));
                    else if (type.equals(UUID.class))
                        editor.putString(name, field.get(o).toString());

                } catch (IllegalAccessException e) {
                    Log.e(StaticConfig.app_name, "IllegalAccessException", e);
                } catch (IllegalArgumentException e) {
                    Log.e(StaticConfig.app_name, "IllegalArgumentException", e);
                }
            }

            editor.apply();
        }

JQuery Redirect to URL after specified time

Yes, the solution is to use setTimeout, like this:

var delay = 10000;
var url = "https://stackoverflow.com";
var timeoutID = setTimeout(function() {
    window.location.href = url;
}, delay);

note that the result was stored into timeoutID. If, for whatever reason you need to cancel the order, you just need to call

clearTimeout(timeoutID);

Column/Vertical selection with Keyboard in SublimeText 3

Alright, here's the best solution I've found that meets all the requirements:

  1. Download the Sublime-Text-Advanced-CSV Sublime plugin and install.
  2. Specify a delimiter for your column (default is ","), via the "CSV: Set Delimiter" command.
  3. Hit "ctrl + , s" (or select from Command Palette) and your column will be selected.

No need for mouse interaction whatsoever.

Recursive search and replace in text files on Mac and Linux

https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

Usage looks like:

$ ls test
a  d  d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"                         
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye

Removing page title and date when printing web page (with CSS?)

Try this;

@media print{ @page { margin-top: 30px; margin-bottom: 30px;}}

What causes: "Notice: Uninitialized string offset" to appear?

Try to test and initialize your arrays before you use them :

if( !isset($catagory[$i]) ) $catagory[$i] = '' ;
if( !isset($task[$i]) ) $task[$i] = '' ;
if( !isset($fullText[$i]) ) $fullText[$i] = '' ;
if( !isset($dueDate[$i]) ) $dueDate[$i] = '' ;
if( !isset($empId[$i]) ) $empId[$i] = '' ;

If $catagory[$i] doesn't exist, you create (Uninitialized) one ... that's all ; => PHP try to read on your table in the address $i, but at this address, there's nothing, this address doesn't exist => PHP return you a notice, and it put nothing to you string. So you code is not very clean, it takes you some resources that down you server's performance (just a very little).

Take care about your MySQL tables default values

if( !isset($dueDate[$i]) ) $dueDate[$i] = '0000-00-00 00:00:00' ;

or

if( !isset($dueDate[$i]) ) $dueDate[$i] = 'NULL' ;

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

codes need to save UTF8 without BOM while recording. Sometimes, written codes with (Notepad++) or other coding tools and use UTF8 encode, this error occurs. I'm sorry, I do not know English. This is just my experience.

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Javascript - Get Image height

Try with JQuery:

<script type="text/javascript">
function jquery_get_width_height()
{
    var imgWidth = $("#img").width();
    var imgHeight = $("#img").height();
    alert("JQuery -- " + "imgWidth: " + imgWidth + " - imgHeight: " + imgHeight);
}
</script>

or

<script type="text/javascript">
function javascript_get_width_height()
{
    var img = document.getElementById('img');
    alert("JavaSript -- " + "imgWidth: " + img.width + " - imgHeight: " + img.height);
}
</script>

How do I get logs/details of ansible-playbook module executions?

Ansible command-line help, such as ansible-playbook --help shows how to increase output verbosity by setting the verbose mode (-v) to more verbosity (-vvv) or to connection debugging verbosity (-vvvv). This should give you some of the details you're after in stdout, which you can then be logged.

Is it possible to put CSS @media rules inline?

Inline styles cannot currently contain anything other than declarations (property: value pairs).

You can use style elements with appropriate media attributes in head section of your document.

How to detect escape key press with pure JS or jQuery?

i think the simplest way is vanilla javascript:

document.onkeyup = function(event) {
   if (event.keyCode === 27){
     //do something here
   }
}

Updated: Changed key => keyCode

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

1- Never use Response.Write.

2- I put the code below after create (not in Page_Load) a LinkButton (dynamically) and solved my problem:

ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(lblbtndoc1);

Remove composer

If you install the composer as global on Ubuntu, you just need to find the composer location.

Use command

type composer

or

where composer

For Mac users, use command:

which composer

and then just remove the folder using rm command.

running php script (php function) in linux bash

I was in need to decode URL in a Bash script. So I decide to use PHP in this way:

$ cat url-decode.sh
#!/bin/bash
URL='url=https%3a%2f%2f1%2fecp%2f'
/usr/bin/php -r '$arg1 = $argv[1];echo rawurldecode($arg1);' "$URL"

Sample output:

$ ./url-decode.sh 
url=https://1/ecp/

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How do you see recent SVN log entries?

This answer is directed at further questions regarding Subversion subcommands options. For every available subcommand (i.e. add, log, status ...), you can simply add the --help option to display the complete list of available options you can use with your subcommand as well as examples on how to use them. The following snippet is taken directly from the svn log --help command output under the "examples" section :

Show the latest 5 log messages for the current working copy
directory and display paths changed in each commit:
  svn log -l 5 -v

Jenkins Pipeline Wipe Out Workspace

The mentioned solutions deleteDir() and cleanWs() (if using the workspace cleanup plugin) both work, but the recommendation to use it in an extra build step is usually not the desired solution. If the build fails and the pipeline is aborted, this cleanup-stage is never reached and therefore the workspace is not cleaned on failed builds.

=> In most cases you should probably put it in a post-built-step condition like always:

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
    post { 
        always { 
            cleanWs()
        }
    }
}

milliseconds to time in javascript

Editing RobG's solution and using JavaScript's Date().

function msToTime(ms) {

    function addZ(n) {
        return (n<10? '0':'') + n;
    }
    var dt = new Date(ms);
    var hrs = dt.getHours();
    var mins = dt.getMinutes();
    var secs = dt.getSeconds();
    var millis = dt.getMilliseconds();

    var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
    return tm;
}

LINQ query on a DataTable

Using LINQ to manipulate data in DataSet/DataTable

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

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

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

It happened for me as well while running a game using and-engine. It was fixed after i added the below code to my manifest.xml. This code should be added to your mainactivity.

android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

reading from app.config file

ConfigurationSettings.AppSettings is deprecated, see here:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings.aspx

That said, it should still work.

Just a suggestion, but have you confirmed that your application configuration is the one your executable is using?

Try attaching a debugger and checking the following value:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

And then opening the configuration file and verifying the section is there as you expected.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

I had same problem and this accepted solution didn't helped me, if someone has same problem you can use my code snippet:

// example of filtering and sharing multiple images with texts
// remove facebook from sharing intents
private void shareFilter(){

    String share = getShareTexts();
    ArrayList<Uri> uris = getImageUris();

    List<Intent> targets = new ArrayList<>();
    Intent template = new Intent(Intent.ACTION_SEND_MULTIPLE);
    template.setType("image/*");
    List<ResolveInfo> candidates = getActivity().getPackageManager().
            queryIntentActivities(template, 0);

    // remove facebook which has a broken share intent
    for (ResolveInfo candidate : candidates) {
        String packageName = candidate.activityInfo.packageName;
        if (!packageName.equals("com.facebook.katana")) {
            Intent target = new Intent(Intent.ACTION_SEND_MULTIPLE);
            target.setType("image/*");
            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
            target.putExtra(Intent.EXTRA_TEXT, share);
            target.setPackage(packageName);
            targets.add(target);
        }
    }
    Intent chooser = Intent.createChooser(targets.remove(0), "Share Via");
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
    startActivity(chooser);

}

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I deleted folders build inside a project. After cleaned and rebuilt it in Android Studio. Then corrected errors in build.gradle and AndroidManifest.

How to get access to job parameters from ItemReader, in Spring Batch?

Did you declare the jobparameters as map properly as bean?

Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?

For more on expression language you can find information in Spring documentation here.

Multiple FROMs - what it means

The first answer is too complex, historic, and uninformative for my tastes.


It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,

  • Free you from having to manually remove what you don't want, by forcing you to whitelist what you do want,
  • Free resources that would otherwise be taken up because of Docker's implementation.

Let's start with the first. Very often with something like Debian you'll see.

RUN apt-get update \ 
  && apt-get dist-upgrade \
  && apt-get install <whatever> \
  && apt-get clean

We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,

RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;

It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree for an example of that).

By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean), and you would otherwise have lots of un-needed files in your final image.

See also

Use formula in custom calculated field in Pivot Table

Some of it is possible, specifically accessing subtotals:

"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)

enter image description here

  • And make sure the field in question is a number field that can be summed, it does not work for text fields for which only count is normally informative.

Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/

Any good boolean expression simplifiers out there?

I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).

Also in Logic Friday the expression A | B just returns 3 entries in truth table; I expected 4.

How do I drop a foreign key constraint only if it exists in sql server?

Declare @FKeyRemoveQuery NVarchar(max)

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))

BEGIN
    SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'   
    FROM sys.foreign_keys
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')

    EXECUTE Sp_executesql @FKeyRemoveQuery 

END

Select multiple rows with the same value(s)

One way of doing this is via an exists clause:

select * from genes g
where exists
(select null from genes g1
 where g.locus = g1.locus and g.chromosome = g1.chromosome and g.id <> g1.id)

Alternatively, in MySQL you can get a summary of all matching ids with a single table access, using group_concat:

select group_concat(id) matching_ids, chromosome, locus 
from genes
group by chromosome, locus
having count(*) > 1

Avoid browser popup blockers

I tried multiple solutions, but his is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

Parsing string as JSON with single quotes?

I know it's an old post, but you can use JSON5 for this purpose.

<script src="json5.js"></script>
<script>JSON.stringify(JSON5.parse('{a:1}'))</script>

Resize command prompt through commands

If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

Not tested, but something like this:

var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
          (now.getUTCMonth() + 1).toString() +
          "/" + now.getUTCDate() + " " + now.getUTCHours() +
          ":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();

Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."

Format Float to n decimal places

I was looking for an answer to this question and later I developed a method! :) A fair warning, it's rounding up the value.

private float limitDigits(float number) {
    return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}

How to quickly check if folder is empty (.NET)?

Here is something that might help you doing it. I managed to do it in two iterations.

 private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
   {
     var directories =
        Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
        .ToList();

     var directoryList = 
     (from directory in directories
     let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
     where !isEmpty select directory)
     .ToList();

     return directoryList.ToList();
   }

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

You have to put this as root:

GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'IP' IDENTIFIED BY 'PASSWORD' with grant option;

;

where IP is the IP you want to allow access, USERNAME is the user you use to connect, and PASSWORD is the relevant password.

If you want to allow access from any IP just put % instead of your IP

and then you only have to put

FLUSH PRIVILEGES;

Or restart mysql server and that's it.

Sort objects in an array alphabetically on one property of the array

var DepartmentFactory = function(data) {
    this.id = data.Id;
    this.name = data.DepartmentName;
    this.active = data.Active;
}

// use `new DepartmentFactory` as given below. `new` is imporatant

var objArray = [];
objArray.push(new DepartmentFactory({Id: 1, DepartmentName: 'Marketing', Active: true}));
objArray.push(new DepartmentFactory({Id: 2, DepartmentName: 'Sales', Active: true}));
objArray.push(new DepartmentFactory({Id: 3, DepartmentName: 'Development', Active: true}));
objArray.push(new DepartmentFactory({Id: 4, DepartmentName: 'Accounting', Active: true}));

function sortOn(property){
    return function(a, b){
        if(a[property] < b[property]){
            return -1;
        }else if(a[property] > b[property]){
            return 1;
        }else{
            return 0;   
        }
    }
}

//objArray.sort(sortOn("id")); // because `this.id = data.Id;`
objArray.sort(sortOn("name")); // because `this.name = data.DepartmentName;`
console.log(objArray);

demo: http://jsfiddle.net/diode/hdgeH/

Could not establish secure channel for SSL/TLS with authority '*'

In case it helps anyone else, using the new Microsoft Web Service Reference Provider tool, which is for .NET Standard and .NET Core, I had to add the following lines to the binding definition as below:

binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport = new HttpTransportSecurity{ClientCredentialType = HttpClientCredentialType.Certificate};

This is effectively the same as Micha's answer but in code as there is no config file.

So to incorporate the binding with the instantiation of the web service I did this:

 System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
 binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
 binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Certificate;
 var client = new WebServiceClient(binding, GetWebServiceEndpointAddress());

Where WebServiceClient is the proper name of your web service as you defined it.

how to get request path with express req object

//auth required or redirect
app.use('/account', function(req, res, next) {
  console.log(req.path);
  if ( !req.session.user ) {
    res.redirect('/login?ref='+req.path);
  } else {
    next();
  }
});

req.path is / when it should be /account ??

The reason for this is that Express subtracts the path your handler function is mounted on, which is '/account' in this case.

Why do they do this?

Because it makes it easier to reuse the handler function. You can make a handler function that does different things for req.path === '/' and req.path === '/goodbye' for example:

function sendGreeting(req, res, next) {
  res.send(req.path == '/goodbye' ? 'Farewell!' : 'Hello there!')
}

Then you can mount it to multiple endpoints:

app.use('/world', sendGreeting)
app.use('/aliens', sendGreeting)

Giving:

/world           ==>  Hello there!
/world/goodbye   ==>  Farewell!
/aliens          ==>  Hello there!
/aliens/goodbye  ==>  Farewell!

Abstract methods in Python

See the abc module. Basically, you define __metaclass__ = abc.ABCMeta on the class, then decorate each abstract method with @abc.abstractmethod. Classes derived from this class cannot then be instantiated unless all abstract methods have been overridden.

If your class is already using a metaclass, derive it from ABCMeta rather than type and you can continue to use your own metaclass.

A cheap alternative (and the best practice before the abc module was introduced) would be to have all your abstract methods just raise an exception (NotImplementedError is a good one) so that classes derived from it would have to override that method to be useful.

However, the abc solution is better because it keeps such classes from being instantiated at all (i.e., it "fails faster"), and also because you can provide a default or base implementation of each method that can be reached using the super() function in derived classes.

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

What steps are needed to stream RTSP from FFmpeg?

An alternative that I used instead of FFServer was Red5 Pro, on Ubuntu, I used this line: ffmpeg -f pulse -i default -f video4linux2 -thread_queue_size 64 -framerate 25 -video_size 640x480 -i /dev/video0 -pix_fmt yuv420p -bsf:v h264_mp4toannexb -profile:v baseline -level:v 3.2 -c:v libx264 -x264-params keyint=120:scenecut=0 -c:a aac -b:a 128k -ar 44100 -f rtsp -muxdelay 0.1 rtsp://localhost:8554/live/paul

Git error on commit after merge - fatal: cannot do a partial commit during a merge

During a merge Git wants to keep track of the parent branches for all sorts of reasons. What you want to do is not a merge as git sees it. You will likely want to do a rebase or cherry-pick manually.

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How to paste yanked text into the Vim command line

For pasting something that is the system clipboard you can just use SHIFT - INS.

It works in Windows, but I am guessing it works well in Linux too.

Accessing items in an collections.OrderedDict by index

If its an OrderedDict() you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')

Note for Python 3.X

dict.items would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible

>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')

How many concurrent requests does a single Flask process receive?

No- you can definitely handle more than that.

Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.

Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).

Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.

These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.

Another example is threads, which are units of code inside processes that allow concurrency as well.

The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.

The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.

Good luck!

*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Here's another way to do it instead of using foreach loops for looking inside EntityValidationErrors. Of course you can format the message to your own liking :

try {
        // your code goes here...
    } 
catch (DbEntityValidationException ex) 
    {
        Console.Write($"Validation errors: {string.Join(Environment.NewLine, ex.EntityValidationErrors.SelectMany(vr => vr.ValidationErrors.Select(err => $"{err.PropertyName} - {err.ErrorMessage}")))}", ex);
        throw;
    }

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

Save the plots into a PDF

For multiple plots in a single pdf file you can use PdfPages

In the plotGraph function you should return the figure and than call savefig of the figure object.

------ plotting module ------

def plotGraph(X,Y):
      fig = plt.figure()
      ### Plotting arrangements ###
      return fig

------ plotting module ------

----- mainModule ----

from matplotlib.backends.backend_pdf import PdfPages

plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)

pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download()

Click on download button when gui prompted. It worked for me.(nltk.download('stopwords') doesn't work for me)

Declaring static constants in ES6 classes?

class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

Seems to work for me.

How to delete an app from iTunesConnect / App Store Connect

As the instructions state on the iTuneconnect Developer Guidelines you need to ensure that you are the "team agent" to delete apps. This is stated in the quote below from the developer guidelines.

If the Delete App button isn’t displayed, check that you’re the team agent and that the app is in one of the statuses that allow the app to be deleted.

I have just checked on my account by logging in as the main account holder and the delete button is there for an app that I have previously removed from sale but when I have looked in as another user they don't have this permission, only the main account holder seems to have it.

Search for string and get count in vi editor

I suggest doing:

  1. Search either with * to do a "bounded search" for what's under the cursor, or do a standard /pattern search.
  2. Use :%s///gn to get the number of occurrences. Or you can use :%s///n to get the number of lines with occurrences.

** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.

Note: Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines where the latter might give you 3 matches on 3 lines. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.

android get all contacts

Get contacts info , photo contacts , photo uri and convert to Class model

1). Sample for Class model :

    public class ContactModel {
        public String id;
        public String name;
        public String mobileNumber;
        public Bitmap photo;
        public Uri photoURI;
    }

2). get Contacts and convert to Model

     public List<ContactModel> getContacts(Context ctx) {
        List<ContactModel> list = new ArrayList<>();
        ContentResolver contentResolver = ctx.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(ctx.getContentResolver(),
                            ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));

                    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
                    Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

                    Bitmap photo = null;
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
                    while (cursorInfo.moveToNext()) {
                        ContactModel info = new ContactModel();
                        info.id = id;
                        info.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        info.mobileNumber = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        info.photo = photo;
                        info.photoURI= pURI;
                        list.add(info);
                    }

                    cursorInfo.close();
                }
            }
            cursor.close();
        }
        return list;
    }

Change Row background color based on cell value DataTable

I used createdRow Function and solved my problem

    $('#result1').DataTable( {
        data: data['firstQuery'],
        columns: [
                        { title: 'Shipping Agent Code' },
                        { title: 'City' },
                        { title: 'Delivery Zone' },
                        { title: 'Total Slots Open ' },
                        { title: 'Slots Utilized' },
                        { title: 'Utilization %' },

                    ],
                    "columnDefs": [
                        {"className": "dt-center", "targets": "_all"}
                      ],
                      "createdRow": function( row, data, dataIndex){
                            if( data[5] >= 90  ){
                                $(row).css('background-color', '#F39B9B');
                            }
                            else if( data[5] <= 70  ){
                                $(row).css('background-color', '#A497E5');
                            }
                            else{
                                $(row).css('background-color', '#9EF395');
                            }

                        }
                } );

Where is the user's Subversion config file stored on the major operating systems?

Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion

Subprocess changing directory

If you need to change directory, run a command and get the std output as well:

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<[email protected]>\nDate:   2020-04-23 09:58:49 +0200\n\n

Remove NA values from a vector

I ran a quick benchmark comparing the two base approaches and it turns out that x[!is.na(x)] is faster than na.omit. User qwr suggested I try purrr::dicard also - this turned out to be massively slower (though I'll happily take comments on my implementation & test!)

microbenchmark::microbenchmark(
  purrr::map(airquality,function(x) {x[!is.na(x)]}), 
  purrr::map(airquality,na.omit),
  purrr::map(airquality, ~purrr::discard(.x, .p = is.na)),
  times = 1e6)

Unit: microseconds
                                                     expr    min     lq      mean median      uq       max neval cld
 purrr::map(airquality, function(x) {     x[!is.na(x)] })   66.8   75.9  130.5643   86.2  131.80  541125.5 1e+06 a  
                          purrr::map(airquality, na.omit)   95.7  107.4  185.5108  129.3  190.50  534795.5 1e+06  b 
  purrr::map(airquality, ~purrr::discard(.x, .p = is.na)) 3391.7 3648.6 5615.8965 4079.7 6486.45 1121975.4 1e+06   c

For reference, here's the original test of x[!is.na(x)] vs na.omit:

microbenchmark::microbenchmark(
    purrr::map(airquality,function(x) {x[!is.na(x)]}), 
    purrr::map(airquality,na.omit), 
    times = 1000000)


Unit: microseconds
                                              expr  min   lq      mean median    uq      max neval cld
 map(airquality, function(x) {     x[!is.na(x)] }) 53.0 56.6  86.48231   58.1  64.8 414195.2 1e+06  a 
                          map(airquality, na.omit) 85.3 90.4 134.49964   92.5 104.9 348352.8 1e+06   b

Determining type of an object in ruby

variable_name.class

Here variable name is "a" a.class

How to replace sql field value

It depends on what you need to do. You can use replace since you want to replace the value:

select replace(email, '.com', '.org')
from yourtable

Then to UPDATE your table with the new ending, then you would use:

update yourtable
set email = replace(email, '.com', '.org')

You can also expand on this by checking the last 4 characters of the email value:

update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'

However, the issue with replace() is that .com can be will in other locations in the email not just the last one. So you might want to use substring() the following way:

update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';

See SQL Fiddle with Demo

Using substring() will return the start of the email value, without the final .com and then you concatenate the .org to the end. This prevents the replacement of .com elsewhere in the string.

Alternatively you could use stuff(), which allows you to do both deleting and inserting at the same time:

update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';

This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com) and insert .org instead.

See SQL Fiddle with Demo for this method as well.

Optimal way to DELETE specified rows from Oracle

I have tried this code and It's working fine in my case.

DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
  (
      SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
      FROM NG_USR_0_CLIENT_GRID_NEW
      WHERE wi_name = 'NB-0000001385-Process'
  )
  WHERE RN=2
);

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

No.

Sometimes you can quote the filename.

"C:\Program Files\Something"

Some programs will tolerate the quotes. Since you didn't provide any specific program, it's impossible to tell if quotes will work for you.

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

Main differences between SOAP and RESTful web services in Java

REST is easier to use for the most part and is more flexible. Unlike SOAP, REST doesn’t have to use XML to provide the response. We can find REST-based Web services that output the data in the Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS) formats.

We can obtain the output we need in a form that’s easy to parse within the language we need for our application.REST is more efficient (use smaller message formats), fast and closer to other Web technologies in design philosophy.

How to keep environment variables when using sudo

You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:

Defaults env_keep += "http_proxy https_proxy"

You should also consider specifying env_keep for only a single command like this:

Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"