Programs & Examples On #Time

Measuring the time it takes to perform an operation. Also, questions related to obtaining the current time, calculating on times, formatting and parsing times, etc.

How to parse unix timestamp to time.Time

According to the go documentation, Unix returns a local time.

Unix returns the local Time corresponding to the given Unix time

This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

To do so, I adapted the snippet to make it return a time in UTC:

i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
    panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())

This prints on my machine (in CEST)

2014-07-16 20:55:46 +0000 UTC

Convert number of minutes into hours & minutes using PHP

check this link for better solution. Click here

How to convert hh:mm:ss to minutes

$minutes=$item['time_diff'];
$hours =   sprintf('%02d',intdiv($minutes, 60)) .':'. ( sprintf('%02d',$minutes % 60));

Current time formatting with Javascript

You may want to try

var d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"

Documentation

How to get only time from date-time C#

You need to account for DateTime Kind too.

public static DateTime GetTime(this DateTime d)
{
    return new DateTime(d.TimeOfDay.Ticks, d.Kind);
}

Get a UTC timestamp

You can use Date.UTC method to get the time stamp at the UTC timezone.

Usage:

var now = new Date;
var utc_timestamp = Date.UTC(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , 
      now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());

Live demo here http://jsfiddle.net/naryad/uU7FH/1/

How to get time difference in minutes in PHP

<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.

Convert timestamp in milliseconds to string formatted time in Java

I'll show you three ways to (a) get the minute field from a long value, and (b) print it using the Date format you want. One uses java.util.Calendar, another uses Joda-Time, and the last uses the java.time framework built into Java 8 and later.

The java.time framework supplants the old bundled date-time classes, and is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

The java.time framework is the way to go when using Java 8 and later. Otherwise, such as Android, use Joda-Time. The java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.

java.util.Date & .Calendar

final long timestamp = new Date().getTime();

// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
    new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);

Joda-Time

// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);

Output:

24
09:24:10:254
24
09:24:10:254

java.time

long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );

System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );

millisecondsSinceEpoch: 1289375173771 instant: 2010-11-10T07:46:13.771Z output: 07:46:13:771

Get the time difference between two datetimes

This approach will work ONLY when the total duration is less than 24 hours:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")

// outputs: "00:39:30"

If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.

If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

// outputs: "48:39:30"

Note that I'm using the utc time as a shortcut. You could pull out d.minutes() and d.seconds() separately, but you would also have to zeropad them.

This is necessary because the ability to format a duration objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");

// outputs: "48:39:30"

Displaying the build date

The option not discussed here is to insert your own data into AssemblyInfo.cs, the "AssemblyInformationalVersion" field seems appropriate - we have a couple of projects where we were doing something similar as a build step (however I'm not entirely happy with the way that works so don't really want to reproduce what we've got).

There's an article on the subject on codeproject: http://www.codeproject.com/KB/dotnet/Customizing_csproj_files.aspx

Getting time and date from timestamp with php

$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];

Time in milliseconds in C

Here is what I write to get the timestamp in millionseconds.

#include<sys/time.h>

long long timeInMilliseconds(void) {
    struct timeval tv;

    gettimeofday(&tv,NULL);
    return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}

Extract time from date String

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Convert seconds to HH-MM-SS with JavaScript?

--update 2

Please use @Frank's a one line solution:

new Date(SECONDS * 1000).toISOString().substr(11, 8)

It is by far the best solution.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:

martind@whitewater:~$ cat `which isoToEpoch`
#!/usr/bin/perl -w
use strict;
use Time::Piece;
# sudo apt-get install libtime-piece-perl
while (<>) {
  # date --iso=s:
  # 2007-02-15T18:25:42-0800
  # Other matched formats:
  # 2007-02-15 13:50:29 (UTC-0800)
  # 2007-02-15 13:50:29 (UTC-08:00)
  s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
  print;
}
martind@whitewater:~$ 

Calculate time difference in Windows batch file

Fixed Gynnad's leading 0 Issue. I fixed it with the two Lines

SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%

Full Script ( CalculateTime.cmd ):

@ECHO OFF

:: F U N C T I O N S

:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0

:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
SET /A DURATION=%ENDTIME%-%STARTTIME%
IF %DURATION% == 0 SET TIMEDIFF=00:00:00,00 && EXIT /B 0
IF %ENDTIME% LSS %STARTTIME% SET /A DURATION=%STARTTIME%-%ENDTIME%
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
SET /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
SET /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=0%DURATIONH%
IF %DURATIONM% LSS 10 SET DURATIONM=0%DURATIONM%
IF %DURATIONS% LSS 10 SET DURATIONS=0%DURATIONS%
IF %DURATIONHS% LSS 10 SET DURATIONHS=0%DURATIONHS%
SET TIMEDIFF=%DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
EXIT /B 0

:: U S A G E

:: Start Measuring
CALL :__START_TIME_MEASURE

:: Print Message on Screen without Linefeed
ECHO|SET /P=Execute Job... 

:: Some Time pending Jobs here
:: '> NUL 2>&1' Dont show any Messages or Errors on Screen
MyJob.exe > NUL 2>&1

:: Stop Measuring
CALL :__STOP_TIME_MEASURE

:: Finish the Message 'Execute Job...' and print measured Time
ECHO [Done] (%TIMEDIFF%)

:: Possible Result
:: Execute Job... [Done] (00:02:12,31)
:: Between 'Execute Job... ' and '[Done] (00:02:12,31)' the Job will be executed

How Many Seconds Between Two Dates?

.Net provides the TimeSpan class to do the math for you.

var time1 = new Date(YYYY, MM, DD, 0, 0, 0, 0)
var time2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0)

Dim ts As TimeSpan = time2.Subtract(time1)

ts.TotalSeconds

Go / golang time.Now().UnixNano() convert to milliseconds?

At https://github.com/golang/go/issues/44196 randall77 suggested

time.Now().Sub(time.Unix(0,0)).Milliseconds()

which exploits the fact that Go's time.Duration already have Milliseconds method.

Should MySQL have its timezone set to UTC?

How about making your app agnostic of the server's timezone?

Owing to any of these possible scenarios:

  • You might not have control over the web/database server's timezone settings
  • You might mess up and set the settings incorrectly
  • There are so many settings as described in the other answers, and so many things to keep track of, that you might miss something
  • An update on the server, or a software reset, or another admin, might unknowing reset the servers' timezone to the default - thus breaking your application

All of the above scenarios give rise to breaking of your application's time calculations. Thus it appears that the better approach is to make your application work independent of the server's timezone.

The idea is simply to always create dates in UTC before storing them into the database, and always re-create them from the stored values in UTC as well. This way, the time calculations won't ever be incorrect, because they're always in UTC. This can be achieved by explicity stating the DateTimeZone parameter when creating a PHP DateTime object.

On the other hand, the client side functionality can be configured to convert all dates/times received from the server to the client's timezone. Libraries like moment.js make this super easy to do.

For example, when storing a date in the database, instead of using the NOW() function of MySQL, create the timestamp string in UTC as follows:

// Storing dates
$date = new DateTime('now', new DateTimeZone('UTC'));
$sql = 'insert into table_name (date_column) values ("' . $date . '")';

// Retreiving dates
$sql = 'select date_column from table_name where condition';
$dateInUTC = new DateTime($date_string_from_db, new DateTimeZone('UTC'));

You can set the default timezone in PHP for all dates created, thus eliminating the need to initialize the DateTimeZone class every time you want to create a date.

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

Python logging: use milliseconds in time format

After instantiating a Formatter I usually set formatter.converter = gmtime. So in order for @unutbu's answer to work in this case you'll need:

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s.%03d" % (t, record.msecs)
        return s

Get a timestamp in C in microseconds?

You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval type directly:

struct timeval GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv;
}

The second, and for me less desirable, choice is to build a uint64_t out of a timeval:

uint64_t GetTimeStamp() {
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;
}

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.

Extracting time from POSIXct

I can't find anything that deals with clock times exactly, so I'd just use some functions from package:lubridate and work with seconds-since-midnight:

require(lubridate)
clockS = function(t){hour(t)*3600+minute(t)*60+second(t)}
plot(clockS(times),val)

You might then want to look at some of the axis code to figure out how to label axes nicely.

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Current date and time as string

Non C++11 solution: With the <ctime> header, you could use strftime. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.

#include <iostream>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
  std::string str(buffer);

  std::cout << str;

  return 0;
}

How to convert a string variable containing time to time_t type in c++?

You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t

Swift convert unix time to date and time

func timeStringFromUnixTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)

    // Returns date formatted as 12 hour time.
    dateFormatter.dateFormat = "hh:mm a"
    return dateFormatter.stringFromDate(date)
}

func dayStringFromTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)
    dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(date)
}

What is the standard way to add N seconds to datetime.time in Python?

Old question, but I figured I'd throw in a function that handles timezones. The key parts are passing the datetime.time object's tzinfo attribute into combine, and then using timetz() instead of time() on the resulting dummy datetime. This answer partly inspired by the other answers here.

def add_timedelta_to_time(t, td):
    """Add a timedelta object to a time object using a dummy datetime.

    :param t: datetime.time object.
    :param td: datetime.timedelta object.

    :returns: datetime.time object, representing the result of t + td.

    NOTE: Using a gigantic td may result in an overflow. You've been
    warned.
    """
    # Create a dummy date object.
    dummy_date = date(year=100, month=1, day=1)

    # Combine the dummy date with the given time.
    dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)

    # Add the timedelta to the dummy datetime.
    new_datetime = dummy_datetime + td

    # Return the resulting time, including timezone information.
    return new_datetime.timetz()

And here's a really simple test case class (using built-in unittest):

import unittest
from datetime import datetime, timezone, timedelta, time

class AddTimedeltaToTimeTestCase(unittest.TestCase):
    """Test add_timedelta_to_time."""

    def test_wraps(self):
        t = time(hour=23, minute=59)
        td = timedelta(minutes=2)
        t_expected = time(hour=0, minute=1)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)

    def test_tz(self):
        t = time(hour=4, minute=16, tzinfo=timezone.utc)
        td = timedelta(hours=10, minutes=4)
        t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)


if __name__ == '__main__':
    unittest.main()

How can I do time/hours arithmetic in Google Spreadsheet?

In the case you want to format it within a formula (for example, if you are concatenating strings and values), the aforementioned format option of Google is not available, but you can use the TEXT formula:

=TEXT(B1-C1,"HH:MM:SS")

Therefore, for the questioned example, with concatenation:

="The number of " & TEXT(B1,"HH") & " hour slots in " & TEXT(C1,"HH") _
& " is " & TEXT(C1/B1,"HH")

Cheers

Java string to date conversion

That's the hard way, and those java.util.Date setter methods have been deprecated since Java 1.1 (1997). Simply format the date using SimpleDateFormat using a format pattern matching the input string.

In your specific case of "January 2, 2010" as the input string:

  1. "January" is the full text month, so use the MMMM pattern for it
  2. "2" is the short day-of-month, so use the d pattern for it.
  3. "2010" is the 4-digit year, so use the yyyy pattern for it.
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010

Note the importance of the explicit Locale argument. If you omit it, then it will use the default locale which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a java.text.ParseException even though when the format pattern seems valid.

Here's an extract of relevance from the javadoc, listing all available format patterns:

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M/L Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. MMMMM or more is unnecessary.

Here are some examples of valid SimpleDateFormat patterns to parse a given string to date:

Input string Pattern
2001.07.04 AD at 12:08:56 PDT yyyy.MM.dd G 'at' HH:mm:ss z
Wed, Jul 4, '01 EEE, MMM d, ''yy
12:08 PM h:mm a
12 o'clock PM, Pacific Daylight Time hh 'o''clock' a, zzzz
0:08 PM, PDT K:mm a, z
02001.July.04 AD 12:08 PM yyyyy.MMMM.dd GGG hh:mm aaa
Wed, 4 Jul 2001 12:08:56 -0700 EEE, d MMM yyyy HH:mm:ss Z
010704120856-0700 yyMMddHHmmssZ
2001-07-04T12:08:56.235-0700 yyyy-MM-dd'T'HH:mm:ss.SSSZ
2001-07-04T12:08:56.235-07:00 yyyy-MM-dd'T'HH:mm:ss.SSSXXX
2001-W27-3 YYYY-'W'ww-u

An important note is that SimpleDateFormat is not thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope.


Java 8 update

If you happen to be on Java 8 or newer, then use DateTimeFormatter (also here, click the link to see all predefined formatters and available format patterns; the tutorial is available here). This new API is inspired by JodaTime.

String string = "January 2, 2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Note: if your format pattern happens to contain the time part as well, then use LocalDateTime#parse(text, formatter) instead of LocalDate#parse(text, formatter). And, if your format pattern happens to contain the time zone as well, then use ZonedDateTime#parse(text, formatter) instead.

Here's an extract of relevance from the javadoc, listing all available format patterns:

Symbol Meaning Presentation Examples
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;

Do note that it has several predefined formatters for the more popular patterns. So instead of e.g. DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);, you could use DateTimeFormatter.RFC_1123_DATE_TIME. This is possible because they are, on the contrary to SimpleDateFormat, thread safe. You could thus also define your own, if necessary.

For a particular input string format, you don't need to use an explicit DateTimeFormatter: a standard ISO 8601 date, like 2016-09-26T17:44:57Z, can be parsed directly with LocalDateTime#parse(text) as it already uses the ISO_LOCAL_DATE_TIME formatter. Similarly, LocalDate#parse(text) parses an ISO date without the time component (see ISO_LOCAL_DATE), and ZonedDateTime#parse(text) parses an ISO date with an offset and time zone added (see ISO_ZONED_DATE_TIME).

How to log a method's execution time exactly in milliseconds?

An example of fine-grained timing using mach_absolute_time() in Swift 4:

let start = mach_absolute_time()

// do something

let elapsedMTU = mach_absolute_time() - start
var timebase = mach_timebase_info()
if mach_timebase_info(&timebase) == 0 {
    let elapsed = Double(elapsedMTU) * Double(timebase.numer) / Double(timebase.denom)
    print("render took \(elapsed)")
}
else {
    print("timebase error")
}

How to delete last item in list?

list.pop() removes and returns the last element of the list.

Measuring elapsed time with the Time module

For users that want better formatting,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))

will print out, for 2 seconds:

'00:00:02'

and for 7 minutes one second:

'00:07:01'

note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 

strftime documentation

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.

How to get current time and date in C++?

New answer for an old question:

The question does not specify in what timezone. There are two reasonable possibilities:

  1. In UTC.
  2. In the computer's local timezone.

For 1, you can use this date library and the following program:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << '\n';
}

Which just output for me:

2015-08-18 22:08:18.944211

The date library essentially just adds a streaming operator for std::chrono::system_clock::time_point. It also adds a lot of other nice functionality, but that is not used in this simple program.

If you prefer 2 (the local time), there is a timezone library that builds on top of the date library. Both of these libraries are open source and cross platform, assuming the compiler supports C++11 or C++14.

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto local = make_zoned(current_zone(), system_clock::now());
    std::cout << local << '\n';
}

Which for me just output:

2015-08-18 18:08:18.944211 EDT

The result type from make_zoned is a date::zoned_time which is a pairing of a date::time_zone and a std::chrono::system_clock::time_point. This pair represents a local time, but can also represent UTC, depending on how you query it.

With the above output, you can see that my computer is currently in a timezone with a UTC offset of -4h, and an abbreviation of EDT.

If some other timezone is desired, that can also be accomplished. For example to find the current time in Sydney , Australia just change the construction of the variable local to:

auto local = make_zoned("Australia/Sydney", system_clock::now());

And the output changes to:

2015-08-19 08:08:18.944211 AEST

Update for C++20

This library is now largely adopted for C++20. The namespace date is gone and everything is in namespace std::chrono now. And use zoned_time in place of make_time. Drop the headers "date.h" and "tz.h" and just use <chrono>.

As I write this, partial implementations are just beginning to emerge on some platforms.

In Python, how do you convert seconds since epoch to a `datetime` object?

From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

Python 3:

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2, using pytz:

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

Get time of specific timezone

short answer from client-side: NO, you have to get it from the server side.

Display milliseconds in Excel

First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):

=DATE(1970,1,1)+(A1/86400000)

If your cell is properly formatted, you should see a human-readable date/time.

Timer for Python game

Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).

time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Let's say that your time value is in cell A1 then in A2 you can put:

=A1*1000*60*60*24

or simply:

=A1*86400000

What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).

You will then need to format cell A2 as General for it to be in milliseconds format.

If your time is a text value then use:

=TIMEVALUE(A1)*86400000

UPDATE

Per @dandfra's comment this solution may not work in the Italian version of Excel.

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 transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

This will work:

DECLARE @MS INT = 235216
select cast(dateadd(ms, @MS, '00:00:00') AS TIME(3))

(where ms is just a number of seconds not a timeformat)

How to stop execution after a certain time in Java?

long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

Convert seconds to hh:mm:ss in Python

Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:

IDLE 2.6.2      
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001

python date of the previous month

For someone who got here and looking to get both the first and last day of the previous month:

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)

start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)

# For printing results
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)

Output:

First day of prev month: 2019-02-01
Last day of prev month: 2019-02-28

How to use timeit module

If you want to use timeit in an interactive Python session, there are two convenient options:

  1. Use the IPython shell. It features the convenient %timeit special function:

    In [1]: def f(x):
       ...:     return x*x
       ...: 
    
    In [2]: %timeit for x in range(100): f(x)
    100000 loops, best of 3: 20.3 us per loop
    
  2. In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement:

    >>> def f(x):
    ...     return x * x 
    ... 
    >>> import timeit
    >>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
                      number=100000)
    [2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
    

Measuring function execution time in R

There is also proc.time()

You can use in the same way as Sys.time but it gives you a similar result to system.time.

ptm <- proc.time()
#your function here
proc.time() - ptm

the main difference between using

system.time({ #your function here })

is that the proc.time() method still does execute your function instead of just measuring the time... and by the way, I like to use system.time with {} inside so you can put a set of things...

Convert UNIX epoch to Date object

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.

Get the current time in C

guys i got a new way get system time. though its lengthy and is full of silly works but in this way you can get system time in integer format.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    char hc1,hc2,mc1,mc2;
    int hi1,hi2,mi1,mi2,hour,minute;
    system("echo %time% >time.txt");
    fp=fopen("time.txt","r");
    if(fp==NULL)
       exit(1) ;
    hc1=fgetc(fp);
    hc2=fgetc(fp);
    fgetc(fp);
    mc1=fgetc(fp);
    mc2=fgetc(fp);
    fclose(fp);
    remove("time.txt");
    hi1=hc1;
    hi2=hc2;
    mi1=mc1;
    mi2=mc2;
    hi1-=48;
    hi2-=48;
    mi1-=48;
    mi2-=48;
    hour=hi1*10+hi2;
    minute=mi1*10+mi2;
    printf("Current time is %d:%d\n",hour,minute);
    return 0;
}

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

If you want to use the ISO8601DateFormatter() with a date from a Rails 4+ JSON feed (and don't need millis of course), you need to set a few options on the formatter for it to work right otherwise the the date(from: string) function will return nil. Here's what I'm using:

extension Date {
    init(dateString:String) {
        self = Date.iso8601Formatter.date(from: dateString)!
    }

    static let iso8601Formatter: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withFullDate,
                                          .withTime,
                                          .withDashSeparatorInDate,
                                          .withColonSeparatorInTime]
        return formatter
    }()
}

Here's the result of using the options verses not in a playground screenshot:

enter image description here

How to convert date to timestamp?

Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000

How to print time in format: 2009-08-10 18:17:54.811

The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>

int main() {
  char buffer[26];
  int millisec;
  struct tm* tm_info;
  struct timeval tv;

  gettimeofday(&tv, NULL);

  millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
  if (millisec>=1000) { // Allow for rounding up to nearest second
    millisec -=1000;
    tv.tv_sec++;
  }

  tm_info = localtime(&tv.tv_sec);

  strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
  printf("%s.%03d\n", buffer, millisec);

  return 0;
}

Command to get time in milliseconds

date command didnt provide milli seconds on OS X, so used an alias from python

millis(){  python -c "import time; print(int(time.time()*1000))"; }

OR

alias millis='python -c "import time; print(int(time.time()*1000))"'

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

$ time date +%s%N
1597103627N
date +%s%N  0.00s user 0.00s system 63% cpu 0.006 total

Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date).

On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date)

$ time python -c "import time; print(int(time.time()*1000))"
1597103899460
python -c "import time; print(int(time.time()*1000))"  0.03s user 0.01s system 83% cpu 0.053 total

I figured awk is lightweight than python, so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
1597103729525
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'  0.00s user 0.00s system 74% cpu 0.010 total

How to get the seconds since epoch from the time + date output of gmtime()?

If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll down one.

If you want to reverse time.gmtime(), you want calendar.timegm().

>>> calendar.timegm(time.gmtime())
1293581619.0

You can turn your string into a time tuple with time.strptime(), which returns a time tuple that you can pass to calendar.timegm():

>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778

More information about calendar module here

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

Very simple, no library required:

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

or you might prefer:

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

EDIT

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

new Date(14, 0, 1);

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

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

How do I measure time elapsed in Java?

Which types to use in order to accomplish this in Java?

The short answer is a long. Now, more on how to measure...

System.currentTimeMillis()

The "traditional" way to do this is indeed to use System.currentTimeMillis():

long startTime = System.currentTimeMillis();
// ... do something ...
long estimatedTime = System.currentTimeMillis() - startTime;

o.a.c.l.t.StopWatch

Note that Commons Lang has a StopWatch class that can be used to measure execution time in milliseconds. It has methods methods like split(), suspend(), resume(), etc that allow to take measure at different points of the execution and that you may find convenient. Have a look at it.

System.nanoTime()

You may prefer to use System.nanoTime() if you are looking for extremely precise measurements of elapsed time. From its javadoc:

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

Jamon

Another option would be to use JAMon, a tool that gathers statistics (execution time, number of hit, average execution time, min, max, etc) for any code that comes between start() and stop() methods. Below, a very simple example:

import com.jamonapi.*;
...
Monitor mon=MonitorFactory.start("myFirstMonitor");
...Code Being Timed...
mon.stop();

Check out this article on www.javaperformancetunning.com for a nice introduction.

Using AOP

Finally, if you don't want to clutter your code with these measurement (or if you can't change existing code), then AOP would be a perfect weapon. I'm not going to discuss this very deeply but I wanted at least to mention it.

Below, a very simple aspect using AspectJ and JAMon (here, the short name of the pointcut will be used for the JAMon monitor, hence the call to thisJoinPoint.toShortString()):

public aspect MonitorAspect {
    pointcut monitor() : execution(* *.ClassToMonitor.methodToMonitor(..));

    Object arround() : monitor() {
        Monitor monitor = MonitorFactory.start(thisJoinPoint.toShortString());
        Object returnedObject = proceed();
        monitor.stop();
        return returnedObject;
    }
}

The pointcut definition could be easily adapted to monitor any method based on the class name, the package name, the method name, or any combination of these. Measurement is really a perfect use case for AOP.

How to print the current time in a Batch-File?

set time1=%time%
call timeout 10
set time2=%time%
echo. time1
echo. time2
echo.
pause

How to redirect the output of the time command to a file in Linux?

Simple. The GNU time utility has an option for that.

But you have to ensure that you are not using your shell's builtin time command, at least the bash builtin does not provide that option! That's why you need to give the full path of the time utility:

/usr/bin/time -o time.txt sleep 1

Convert time fields to strings in Excel

Easy. To change a time value like: 1:00:15 to text, you can use the 'TEXT' function. Example, if your time value (1:00:15) is contained in cell 'A1', you can convert it into a text by doing: Text(A1, "h:mm:ss"). The result still looks the same: 1:00:15. But notice that this time round, it has become a text value.

Converting Milliseconds to Minutes and Seconds?

To convert time in millis directly to minutes: second format you can use this

String durationText = DateUtils.formatElapsedTime(timeInMillis / 1000));

This will return a string with time in proper formatting. It worked for me.

How to calculate the time interval between two time strings

Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.

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.

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

Update TextView Every Second

It would be better if you just used an AsyncTask running using a Timer something like this

 Timer LAIATT = new Timer();
    TimerTask LAIATTT = new TimerTask()
    {
        @Override
        public void run()
        {
            LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();
            LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    };
    LAIATT.schedule(LAIATTT, 0, 1000);

Exception in thread "main" java.lang.Error: Unresolved compilation problems

For this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

There are problems with your import or package name.
You can delete the package name or fix import errors

How to convert milliseconds into human readable form?

Your choices are simple:

  1. Write the code to do the conversion (ie, divide by milliSecondsPerDay to get days and use the modulus to divide by milliSecondsPerHour to get hours and use the modulus to divide by milliSecondsPerMinute and divide by 1000 for seconds. milliSecondsPerMinute = 60000, milliSecondsPerHour = 60 * milliSecondsPerMinute, milliSecondsPerDay = 24 * milliSecondsPerHour.
  2. Use an operating routine of some kind. UNIX and Windows both have structures that you can get from a Ticks or seconds type value.

How do I get time of a Python program's execution?

Just use the timeit module. It works with both Python 2 and Python 3.

import timeit

start = timeit.default_timer()

# All the program statements
stop = timeit.default_timer()
execution_time = stop - start

print("Program Executed in "+str(execution_time)) # It returns time in seconds

It returns in seconds and you can have your execution time. It is simple, but you should write these in thew main function which starts program execution. If you want to get the execution time even when you get an error then take your parameter "Start" to it and calculate there like:

def sample_function(start,**kwargs):
     try:
         # Your statements
     except:
         # except statements run when your statements raise an exception
         stop = timeit.default_timer()
         execution_time = stop - start
         print("Program executed in " + str(execution_time))

Convert Difference between 2 times into Milliseconds?

Try:

DateTime first;
DateTime second;

int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;

Extract time from moment js object

This is the good way using formats:

const now = moment()
now.format("hh:mm:ss K") // 1:00:00 PM
now.format("HH:mm:ss") // 13:00:00

Red more about moment sring format

Adding minutes to date time in PHP

If you want to give a variable that contains the minutes.

Then I think this is a great way to achieve this.

$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

How to get current time in milliseconds in PHP?

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
    if (version_compare(PHP_VERSION, '5.0.0', '<'))
    {
        return array_sum(explode(' ', microtime()));
    }

    return microtime(true);
}

How to convert a time string to seconds?

It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with %I

>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>

Python loop to run for certain amount of seconds

I was looking for an easier-to-read time-loop when I encountered this question here. Something like:

for sec in max_seconds(10):
      do_something()

So I created this helper:

# allow easy time-boxing: 'for sec in max_seconds(42): do_something()'
def max_seconds(max_seconds, *, interval=1):
    interval = int(interval)
    start_time = time.time()
    end_time = start_time + max_seconds
    yield 0
    while time.time() < end_time:
        if interval > 0:
            next_time = start_time
            while next_time < time.time():
                next_time += interval
            time.sleep(int(round(next_time - time.time())))
        yield int(round(time.time() - start_time))
        if int(round(time.time() + interval)) > int(round(end_time)): 
            return

It only works with full seconds which was OK for my use-case.

Examples:

for sec in max_seconds(10) # -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for sec in max_seconds(10, interval=3) # -> 0, 3, 6, 9
for sec in max_seconds(7): sleep(1.5) # -> 0, 2, 4, 6
for sec in max_seconds(8): sleep(1.5) # -> 0, 2, 4, 6, 8

Be aware that interval isn't that accurate, as I only wait full seconds (sleep never was any good for me with times < 1 sec). So if your job takes 500 ms and you ask for an interval of 1 sec, you'll get called at: 0, 500ms, 2000ms, 2500ms, 4000ms and so on. One could fix this by measuring time in a loop rather than sleep() ...

how to sync windows time from a ntp time server in command

If you just need to resync windows time, open an elevated command prompt and type:

w32tm /resync

C:\WINDOWS\system32>w32tm /resync 
Sending resync command to local computer 
The command completed successfully.

What is the easiest way to get current GMT time in Unix timestamp format?

I would use time.time() to get a timestamp in seconds since the epoch.

import time

time.time()

Output:

1369550494.884832

For the standard CPython implementation on most platforms this will return a UTC value.

Xcode swift am/pm time to 24 hour format

Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):

func getTodayString() -> String{

        let formatter = DateFormatter()
        formatter.dateFormat = "h:mm:ss a "
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"

        let currentDateStr = formatter.string(from: Date())
        print(currentDateStr)
        return currentDateStr 
}

OUTPUT : 12:41:42 AM

Feel free to comment. Thanks

Convert a Unix timestamp to time in JavaScript

_x000D_
_x000D_
function timeConverter(UNIX_timestamp){_x000D_
  var a = new Date(UNIX_timestamp * 1000);_x000D_
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];_x000D_
  var year = a.getFullYear();_x000D_
  var month = months[a.getMonth()];_x000D_
  var date = a.getDate();_x000D_
  var hour = a.getHours();_x000D_
  var min = a.getMinutes();_x000D_
  var sec = a.getSeconds();_x000D_
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;_x000D_
  return time;_x000D_
}_x000D_
console.log(timeConverter(0));
_x000D_
_x000D_
_x000D_

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Try this snippet of code:

String timeSettings = android.provider.Settings.System.getString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME);
        if (timeSettings.contentEquals("0")) {
            android.provider.Settings.System.putString(
                    this.getContentResolver(),
                    android.provider.Settings.System.AUTO_TIME, "1");
        }
        Date now = new Date(System.currentTimeMillis());
        Log.d("Date", now.toString());

Make sure to add permission in Manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to print current date on python3?

Please try the below lines in order to get the current date.

import datetime

now = datetime.datetime.now()

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

Output:
2020-02-26 21:15:32

Refer : https://beginnersbug.com/how-to-get-the-current-date-in-pyspark-with-example/

Calculate date/time difference in java

Since Java 5, you can use java.util.concurrent.TimeUnit to avoid the use of Magic Numbers like 1000 and 60 in your code.

By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date javadoc.

Checking Date format from a string in C#

string inputString = "2000-02-02";
DateTime dDate;

if (DateTime.TryParse(inputString, out dDate))
{
    String.Format("{0:d/MM/yyyy}", dDate); 
}
else
{
    Console.WriteLine("Invalid"); // <-- Control flow goes here
}

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

Using JODA:

PeriodFormatter periodFormat = new PeriodFormatterBuilder()
  .minimumParsedDigits(2)
  .appendHour() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendMinute() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendSecond()
  .appendSeparator(".")
  .appendMillis3Digit()
  .toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();

Calculate relative time in C#

Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"):

using System.Text;

/// <summary>
/// Compares a supplied date to the current date and generates a friendly English 
/// comparison ("5 days ago", "5 days from now")
/// </summary>
/// <param name="date">The date to convert</param>
/// <param name="approximate">When off, calculate timespan down to the second.
/// When on, approximate to the largest round unit of time.</param>
/// <returns></returns>
public static string ToRelativeDateString(this DateTime value, bool approximate)
{
    StringBuilder sb = new StringBuilder();

    string suffix = (value > DateTime.Now) ? " from now" : " ago";

    TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));

    if (timeSpan.Days > 0)
    {
        sb.AppendFormat("{0} {1}", timeSpan.Days,
          (timeSpan.Days > 1) ? "days" : "day");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Hours > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
          timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Minutes > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
          timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Seconds > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
          timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second");
        if (approximate) return sb.ToString() + suffix;
    }
    if (sb.Length == 0) return "right now";

    sb.Append(suffix);
    return sb.ToString();
}

Easily measure elapsed time

#include <ctime>

void f() {
  using namespace std;
  clock_t begin = clock();

  code_to_time();

  clock_t end = clock();
  double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
}

The time() function is only accurate to within a second, but there are CLOCKS_PER_SEC "clocks" within a second. This is an easy, portable measurement, even though it's over-simplified.

Add days to JavaScript Date

You can use JavaScript, no jQuery required:

var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 
Formatting to dd/mm/yyyy :

var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();

var someFormattedDate = dd + '/'+ mm + '/'+ y;

How to convert seconds to time format?

If You want nice format like: 0:00:00 use str_pad() as @Gardner.

A non well formed numeric value encountered

If the error is at the time of any calculation, double check that the values does not contains any comma(,). Values must be only in integer/ float format.

Timing a command's execution in PowerShell

Yup.

Measure-Command { .\do_something.ps1 }

Note that one minor downside of Measure-Command is that you see no stdout output.

[Update, thanks to @JasonMArcher] You can fix that by piping the command output to some commandlet that writes to the host, e.g. Out-Default so it becomes:

Measure-Command { .\do_something.ps1 | Out-Default }

Another way to see the output would be to use the .NET Stopwatch class like this:

$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed

How do I represent a time only value in .NET?

Here's a full featured TimeOfDay class.

This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.

It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.

Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:

This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.

// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT

using System;
using System.Text.RegularExpressions;

namespace Cambia
{
    public class TimeOfDay
    {
        private const int MINUTES_PER_DAY = 60 * 24;
        private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
        private const int SECONDS_PER_HOUR = 3600;
        private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");

        public TimeOfDay()
        {
            Init(0, 0, 0);
        }
        public TimeOfDay(int hour, int minute, int second = 0)
        {
            Init(hour, minute, second);
        }
        public TimeOfDay(int hhmmss)
        {
            Init(hhmmss);
        }
        public TimeOfDay(DateTime dt)
        {
            Init(dt);
        }
        public TimeOfDay(TimeOfDay td)
        {
            Init(td.Hour, td.Minute, td.Second);
        }

        public int HHMMSS
        {
            get
            {
                return Hour * 10000 + Minute * 100 + Second;
            }
        }
        public int Hour { get; private set; }
        public int Minute { get; private set; }
        public int Second { get; private set; }
        public double TotalDays
        {
            get
            {
                return TotalSeconds / (24d * SECONDS_PER_HOUR);
            }
        }
        public double TotalHours
        {
            get
            {
                return TotalSeconds / (1d * SECONDS_PER_HOUR);
            }
        }
        public double TotalMinutes
        {
            get
            {
                return TotalSeconds / 60d;
            }
        }
        public int TotalSeconds
        {
            get
            {
                return Hour * 3600 + Minute * 60 + Second;
            }
        }
        public bool Equals(TimeOfDay other)
        {
            if (other == null) { return false; }
            return TotalSeconds == other.TotalSeconds;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) { return false; }
            TimeOfDay td = obj as TimeOfDay;
            if (td == null) { return false; }
            else { return Equals(td); }
        }
        public override int GetHashCode()
        {
            return TotalSeconds;
        }
        public DateTime ToDateTime(DateTime dt)
        {
            return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
        }
        public override string ToString()
        {
            return ToString("HH:mm:ss");
        }
        public string ToString(string format)
        {
            DateTime now = DateTime.Now;
            DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
            return dt.ToString(format);
        }
        public TimeSpan ToTimeSpan()
        {
            return new TimeSpan(Hour, Minute, Second);
        }
        public DateTime ToToday()
        {
            var now = DateTime.Now;
            return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
        }

        #region -- Static --
        public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
        public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
        public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 - ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds != t2.TotalSeconds;
            }
        }
        public static bool operator !=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 != dt2;
        }
        public static bool operator !=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 != dt2;
        }
        public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
        {
            DateTime now = DateTime.Now;
            DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
            TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
            DateTime dt2 = dt1 + ts;
            return new TimeOfDay(dt2);
        }
        public static bool operator <(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds < t2.TotalSeconds;
            }
        }
        public static bool operator <(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 < dt2;
        }
        public static bool operator <(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 < dt2;
        }
        public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                if (t1 == t2) { return true; }
                return t1.TotalSeconds <= t2.TotalSeconds;
            }
        }
        public static bool operator <=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 <= dt2;
        }
        public static bool operator <=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 <= dt2;
        }
        public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else { return t1.Equals(t2); }
        }
        public static bool operator ==(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 == dt2;
        }
        public static bool operator ==(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 == dt2;
        }
        public static bool operator >(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds > t2.TotalSeconds;
            }
        }
        public static bool operator >(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 > dt2;
        }
        public static bool operator >(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 > dt2;
        }
        public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
        {
            if (ReferenceEquals(t1, t2)) { return true; }
            else if (ReferenceEquals(t1, null)) { return true; }
            else
            {
                return t1.TotalSeconds >= t2.TotalSeconds;
            }
        }
        public static bool operator >=(TimeOfDay t1, DateTime dt2)
        {
            if (ReferenceEquals(t1, null)) { return false; }
            DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
            return dt1 >= dt2;
        }
        public static bool operator >=(DateTime dt1, TimeOfDay t2)
        {
            if (ReferenceEquals(t2, null)) { return false; }
            DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
            return dt1 >= dt2;
        }
        /// <summary>
        /// Input examples:
        /// 14:21:17            (2pm 21min 17sec)
        /// 02:15               (2am 15min 0sec)
        /// 2:15                (2am 15min 0sec)
        /// 2/1/2017 14:21      (2pm 21min 0sec)
        /// TimeOfDay=15:13:12  (3pm 13min 12sec)
        /// </summary>
        public static TimeOfDay Parse(string s)
        {
            // We will parse any section of the text that matches this
            // pattern: dd:dd or dd:dd:dd where the first doublet can
            // be one or two digits for the hour.  But minute and second
            // must be two digits.

            Match m = _TodRegex.Match(s);
            string text = m.Value;
            string[] fields = text.Split(':');
            if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
            int hour = Convert.ToInt32(fields[0]);
            int min = Convert.ToInt32(fields[1]);
            int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;

            return new TimeOfDay(hour, min, sec);
        }
        #endregion

        private void Init(int hour, int minute, int second)
        {
            if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
            if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
            if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
            Hour = hour;
            Minute = minute;
            Second = second;
        }
        private void Init(int hhmmss)
        {
            int hour = hhmmss / 10000;
            int min = (hhmmss - hour * 10000) / 100;
            int sec = (hhmmss - hour * 10000 - min * 100);
            Init(hour, min, sec);
        }
        private void Init(DateTime dt)
        {
            Init(dt.Hour, dt.Minute, dt.Second);
        }
    }
}

Java Loop every minute

If you are using a SpringBoot application it's as simple as

ScheduledProcess

@Log
@Component
public class ScheduledProcess {

    @Scheduled(fixedRate = 5000)
    public void run() {
        log.info("this runs every 5 seconds..");
    }

}

Application.class

@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

How to recursively find and list the latest modified files in a directory with subdirectories and times

GNU find (see man find) has a -printf parameter for displaying the files in Epoch mtime and relative path name.

redhat> find . -type f -printf '%T@ %P\n' | sort -n | awk '{print $2}'

Using %f with strftime() in Python to get microseconds

You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.

from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")

Should do the trick!

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

Use a default form value to avoid the error.

Instead of using the accepted answer of applying detectChanges() in ngAfterViewInit() (which also solved the error in my case), I decided instead to save a default value for a dynamically required form field, so that when the form is later updated, it's validity is not changed if the user decides to change an option on the form that would trigger the new required fields (and cause the submit button to be disabled).

This saved a tiny bit of code in my component, and in my case the error was avoided altogether.

Count of "Defined" Array Elements

If the undefined's are implicit then you can do:

var len = 0;
for (var i in arr) { len++ };

undefined's are implicit if you don't set them explicitly

//both are a[0] and a[3] are explicit undefined
var arr = [undefined, 1, 2, undefined];

arr[6] = 3;
//now arr[4] and arr[5] are implicit undefined

delete arr[1]
//now arr[1] is implicit undefined

arr[2] = undefined
//now arr[2] is explicit undefined

How to prevent colliders from passing through each other?

1.) Never use MESH COLLIDER. Use combination of box and capsule collider.

2.) Check constraints in RigidBody. If you tick Freeze Position X than it will pass through the object on the X axis. (Same for y axis).

How to mention C:\Program Files in batchfile

I use in my batch files - c:\progra~2\ instead of C:\Program Files (x86)\ and it works.

Swift: Display HTML data in a label or textView

I had problems to change attributes of text after that, and I could see others asking why...

So best answer is to use extension with NSMutableAttributedString instead:

extension String {

 var htmlToAttributedString: NSMutableAttributedString? {
    guard let data = data(using: .utf8) else { return nil }
    do {
        return try NSMutableAttributedString(data: data,
                                      options: [.documentType: NSMutableAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                      documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
 }

}

And then you can use it this way:

if let labelTextFormatted = text.htmlToAttributedString {
                let textAttributes = [
                    NSAttributedStringKey.foregroundColor: UIColor.white,
                    NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13)
                    ] as [NSAttributedStringKey: Any]
                labelTextFormatted.addAttributes(textAttributes, range: NSRange(location: 0, length: labelTextFormatted.length))
                self.contentText.attributedText = labelTextFormatted
            }

jQuery click / toggle between two functions

jQuery has two methods called .toggle(). The other one [docs] does exactly what you want for click events.

Note: It seems that at least since jQuery 1.7, this version of .toggle is deprecated, probably for exactly that reason, namely that two versions exist. Using .toggle to change the visibility of elements is just a more common usage. The method was removed in jQuery 1.9.

Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).


(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

DEMO

(Disclaimer: I don't say this is the best implementation! I bet it can be improved in terms of performance)

And then call it with:

$('#test').clickToggle(function() {   
    $(this).animate({
        width: "260px"
    }, 1500);
},
function() {
    $(this).animate({
        width: "30px"
    }, 1500);
});

Update 2:

In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. It can be found on GitHub.

Switching users inside Docker image to a non-root user

In case you need to perform privileged tasks like changing permissions of folders you can perform those tasks as a root user and then create a non-privileged user and switch to it:

From <some-base-image:tag>

# Switch to root user
USER root # <--- Usually you won't be needed it - Depends on base image

# Run privileged command
RUN apt install <packages>
RUN apt <privileged command>

# Set user and group
ARG user=appuser
ARG group=appuser
ARG uid=1000
ARG gid=1000
RUN groupadd -g ${gid} ${group}
RUN useradd -u ${uid} -g ${group} -s /bin/sh -m ${user} # <--- the '-m' create a user home directory

# Switch to user
USER ${uid}:${gid}

# Run non-privileged command
RUN apt <non-privileged command>

Angular HTML binding

We can always pass html content to innerHTML property to render html dynamic content but that dynamic html content can be infected or malicious also. So before passing dynamic content to innerHTML we should always make sure the content is sanitized (using DOMSanitizer) so that we can escaped all malicious content.

Try below pipe:

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) {
    }
    transform(value: string) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

Usage:
<div [innerHTML]="content | safeHtml"></div>

How to assign pointer address manually in C programming language?

let's say you want a pointer to point at the address 0x28ff4402, the usual way is

uint32_t *ptr;
ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
*ptr |= (1<<13) | (1<<10); //access the address how ever you want

So the short way is to use a MACRO,

#define ptr *(uint32_t *) (0x28ff4402)

Why is &#65279; appearing in my HTML?

Just use notepad ++ with encoding UTF-8 without BOM.

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In my case it was because I had message boxes. Once I commented that code out, it started working. I remembered that could be a problem when I looked at the event log as suggested in this thread. Thank you everyone!

How can I uninstall npm modules in Node.js?

I just install stylus by default under my home dir, so I just use npm uninstall stylus to detach it, or you can try npm rm <package_name> out.

Eclipse - Failed to create the java virtual machine

I had exactly the same problem, one day eclipse wouldn't open. Tried editing eclipse.ini to the correct java version 1.7, but still the same error. Eventually changed :

-Xms384m 
-Xmx384m

...and all working.

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

Checking for empty or null JToken in a JObject

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"];
if (token != null)
{
    // the "param" property exists
}

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions
{
    public static bool IsNullOrEmpty(this JToken token)
    {
        return (token == null) ||
               (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues) ||
               (token.Type == JTokenType.String && token.ToString() == String.Empty) ||
               (token.Type == JTokenType.Null);
    }
}

How to change the name of a Django app?

Fun problem! I'm going to have to rename a lot of apps soon, so I did a dry run.

This method allows progress to be made in atomic steps, to minimise disruption for other developers working on the app you're renaming.

See the link at the bottom of this answer for working example code.

  1. Prepare existing code for the move:
    • Create an app config (set name and label to defaults).
    • Add the app config to INSTALLED_APPS.
    • On all models, explicitly set db_table to the current value.
    • Doctor migrations so that db_table was "always" explicitly defined.
    • Ensure no migrations are required (checks previous step).
  2. Change the app label:

    • Set label in app config to new app name.
    • Update migrations and foreign keys to reference new app label.
    • Update templates for generic class-based views (the default path is <app_label>/<model_name>_<suffix>.html)
    • Run raw SQL to fix migrations and content_types app (unfortunately, some raw SQL is unavoidable). You can not run this in a migration.

      UPDATE django_migrations
         SET app = 'catalogue'
       WHERE app = 'shop';
      
      UPDATE django_content_type
         SET app_label = 'catalogue'
       WHERE app_label = 'shop';
      
    • Ensure no migrations are required (checks previous step).

  3. Rename the tables:
    • Remove "custom" db_table.
    • Run makemigrations so django can rename the table "to the default".
  4. Move the files:
    • Rename module directory.
    • Fix imports.
    • Update app config's name.
    • Update where INSTALLED_APPS references the app config.
  5. Tidy up:
    • Remove custom app config if it's no longer required.
    • If app config gone, don't forget to also remove it from INSTALLED_APPS.

Example solution: I've created app-rename-example, an example project where you can see how I renamed an app, one commit at a time.

The example uses Python 2.7 and Django 1.8, but I'm confident the same process will work on at least Python 3.6 and Django 2.1.

Subclipse svn:ignore

I was able to do this using TortoiseSVN directly from Windows explorer:

Right click on file to ignore->TortiseSVN->Delete and add to ignore list

I had to close then re-open the project in Eclipse, job done :)

What does it mean to "call" a function in Python?

when you invoke a function , it is termed 'calling' a function . For eg , suppose you've defined a function that finds the average of two numbers like this-

def avgg(a,b) :
        return (a+b)/2;

now, to call the function , you do like this .

x=avgg(4,6)
print x

value of x will be 5 .

Sublime Text 3 how to change the font size of the file sidebar?

On Ubuntu, for versions of Sublime older than 3.2, what worked for me was changing the dpi scale in Preferences > Settings — User by adding this line:

"dpi_scale": 1.10 

For Sublime 3.2, you can use the following line instead:

"ui_scale": 1.10

Adjust the scale value as needed. After this change, you have to restart Sublime Text for it to take effect.

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

How do you simulate Mouse Click in C#?

Some controls, like Button in System.Windows.Forms, have a "PerformClick" method to do just that.

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)

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

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

How do I measure request and response times at once using cURL?

Here's a Bash one-liner to hit the same server repeatedly:

for i in {1..1000}; do curl -s -o /dev/null -w "%{time_total}\n" http://server/get_things; done

Add Legend to Seaborn point plot

Old question, but there's an easier way.

sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])

This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.

IIS: Where can I find the IIS logs?

The 100% correct answer for the default location of the log files is...

%SystemDrive%\inetpub\logs\LogFiles

Yes you can enter this into the explorer address bar it'll work.

To be 100% sure, you need to look at the logging for the web site in IIS.

https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85

i.e.

  1. Open IIS Manager.
  2. Select the site or server in the Connections pane,
  3. Double-click Logging.
  4. The location of log files for the site can be found within the Directory field

EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won't be available.

Enable HTTP Logging

How to set session attribute in java?

I am try to catch your point.I hope it is helpful.....

if (session.isNew()){
     title = "Welcome to my website";
     session.setAttribute(userIDKey, userID);

Pandas: ValueError: cannot convert float NaN to integer

For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)

How to create jar file with package structure?

this bellow code gave me correct response

jar cvf MyJar.jar *.properties lib/*.jar -C bin .  

it added the (log4j) properties file, it added the jar files in lib. and then it went inside bin to retrieve the class files with package.

Laravel Request getting current path with query string

Try to use the following:

\Request::getRequestUri()

Groovy Shell warning "Could not open/create prefs root node ..."

This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.

The problem was in the JDK source code for WindowsPreferences.java. In this class, both nodes userRoot and systemRoot were declared static as in:

/**
 * User root node.
 */
static final Preferences userRoot =
     new WindowsPreferences(USER_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);

/**
 * System root node.
 */
static final Preferences systemRoot =
    new WindowsPreferences(SYSTEM_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);

This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs (= system tree) will be attempted to be created if it doesn't already exist.

So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot, thus causing the warning. It is an interesting subtle bug.

There's a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There's also a backport for Java8 which is in u202.

What you see is really a warning from the JDK's internal logger. It is not an exception. I believe that the warning can be safely ignored .... unless the user code is indeed wanting the system preferences, but that is very rarely the case.

Bonus info

The bug did not reveal itself in versions prior to Java 1.7.21, because up until then the JRE installer would create Registry key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs for you and this would effectively hide the bug. On the other hand you've never really been required to run an installer in order to have a JRE on your machine, or at least this hasn't been Sun/Oracle's intent. As you may be aware Oracle has been distributing the JRE for Windows in .tar.gz format for many years.

Connection timeout for SQL server

Hmmm...

As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.

When you get connection timeouts, it's typically a problem with one of the following:

  1. Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.

  2. Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.

  3. Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver instead of mysqlserver.webdomain.com), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?

  4. Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.

  5. The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.

  6. Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.

Things to try:

  1. Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.

  2. Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.

  3. Run your query in Management Studio, and see how long it takes.

Good luck!

Capture characters from standard input without waiting for enter to be pressed

The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.

#include <sys/filio.h>
int kbhit()
{
 int i;
 ioctl(0, FIONREAD, &i);
 return i; /* return a count of chars available to read */
}
main()
{
 int i = 0;
 intc='';
 system("stty raw -echo");
 printf("enter 'q' to quit \n");
 for (;c!='q';i++) {
    if (kbhit()) {
        c=getchar();
       printf("\n got %c, on iteration %d",c, i);
    }
}
 system("stty cooked echo");
}

Java: Clear the console

Create a method in your class like this: [as @Holger said here.]

public static void clrscr(){
    //Clears Screen in java
    try {
        if (System.getProperty("os.name").contains("Windows"))
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        else
            Runtime.getRuntime().exec("clear");
    } catch (IOException | InterruptedException ex) {}
}

This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).

As an alternate method is to write this code in clrscr():

for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
    System.out.print("\b"); // Prints a backspace

I will not recommend you to use this method.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

A failure occurred while executing com.android.build.gradle.internal.tasks

classpath 'com.android.tools.build:gradle:3.3.2' change class path and it will work

In Java, how can I determine if a char array contains a particular character?

You can iterate through the array or you can convert it to a String and use indexOf.

if (new String(charArray).indexOf('q') < 0) {
    break;
}

Creating a new String is a bit wasteful, but it's probably the tersest code. You can also write a method to imitate the effect without incurring the overhead.

Easiest way to copy a single file from host to Vagrant guest?

The best ans for me is to write the file / directory(to be copied) to the vagrant file directory, now any file present there is available to vagrant in path /vagrant.

That's it, no need of scp or any other methods,

similarly you can copy any file from VM to host by pasting in /vagrant directory.

console.log timestamps in Chrome?

Try this also:

this.log = console.log.bind( console, '[' + new Date().toUTCString() + ']' );

This function puts timestamp, filename and line number as same of built-in console.log.

Get day of week using NSDate

Swift 3 & 4

Retrieving the day of the week's number is dramatically simplified in Swift 3 because DateComponents is no longer optional. Here it is as an extension:

extension Date {
    func dayNumberOfWeek() -> Int? {
        return Calendar.current.dateComponents([.weekday], from: self).weekday 
    }
}

// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4

If you were looking for the written, localized version of the day of week:

extension Date {
    func dayOfWeek() -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        return dateFormatter.string(from: self).capitalized 
        // or use capitalized(with: locale) if you want
    }
}

print(Date().dayOfWeek()!) // Wednesday

Can I escape a double quote in a verbatim string literal?

For adding some more information, your example will work without the @ symbol (it prevents escaping with \), this way:

string foo = "this \"word\" is escaped!";

It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

How to center a (background) image within a div?

If your background image is a vertically aligned sprite sheet, you can horizontally center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: 50% [y position of sprite];
}

If your background image is a horizontally aligned sprite sheet, you can vertically center each sprite like this:

#doit {
    background-image: url('images/pic.png'); 
    background-repeat: none;
    background-position: [x position of sprite] 50%;
}

If your sprite sheet is compact, or you are not trying to center your background image in one of the aforementioned scenarios, these solutions do not apply.

Get current date/time in seconds

var seconds = new Date().getTime() / 1000;

....will give you the seconds since midnight, 1 Jan 1970

Reference

Git merge two local branches

If I understood your question, you want to merge branchB into branchA. To do so, first checkout branchA like below,

git checkout branchA

Then execute the below command to merge branchB into branchA:

git merge branchB

Markdown open a new window link

There is no such feature in markdown, however you can always use HTML inside markdown:

<a href="http://example.com/" target="_blank">example</a>

Default interface methods are only supported starting with Android N

In app-level gradle, you have to write these code:

android {
...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

They come from JavaVersion.java in Android.

An enumeration of Java versions.

Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html

After 9: http://openjdk.java.net/jeps/223

@canerkaseler

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

The ScriptManager must appear before any controls that need it

The ScriptManager is a control that needs to be added to the page you have created.

Take a look at this Sample AJAX Application.

<body>
    <form runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        ...
    </form>
</body>

Package opencv was not found in the pkg-config search path

with opencv 4.0;

  • add -DOPENCV_GENERATE_PKGCONFIG=ON to build arguments
  • pkg-config --cflags --libs opencv4 instead of opencv

null terminating a string

From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

How do I install TensorFlow's tensorboard?

Try typing which tensorboard in your terminal. It should exist if you installed with pip as mentioned in the tensorboard README (although the documentation doesn't tell you that you can now launch tensorboard without doing anything else).

You need to give it a log directory. If you are in the directory where you saved your graph, you can launch it from your terminal with something like:

tensorboard --logdir .

or more generally:

tensorboard --logdir /path/to/log/directory

for any log directory.

Then open your favorite web browser and type in localhost:6006 to connect.

That should get you started. As for logging anything useful in your training process, you need to use the TensorFlow Summary API. You can also use the TensorBoard callback in Keras.

How to read and write to a text file in C++?

Header files needed:

#include <iostream>
#include <fstream>

declare input file stream:

ifstream in("in.txt");

declare output file stream:

ofstream out("out.txt");

if you want to use variable for a file name, instead of hardcoding it, use this:

string file_name = "my_file.txt";
ifstream in2(file_name.c_str());

reading from file into variables (assume file has 2 int variables in):

int num1,num2;
in >> num1 >> num2;

or, reading a line a time from file:

string line;
while(getline(in,line)){
//do something with the line
}

write variables back to the file:

out << num1 << num2;

close the files:

in.close();
out.close();

Difference between string and char[] types in C++

Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.

Good tutorial for using HTML5 History API (Pushstate?)

The HTML5 history spec is quirky.

history.pushState() doesn't dispatch a popstate event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate event or use history.go() to navigate to the new state. The idea is that a router can listen to popstate events and do the navigation for you.

Some things to note:

  • history.pushState() and history.replaceState() don't dispatch popstate events.
  • history.back(), history.forward(), and the browser's back and forward buttons do dispatch popstate events.
  • history.go() and history.go(0) do a full page reload and don't dispatch popstate events.
  • history.go(-1) (back 1 page) and history.go(1) (forward 1 page) do dispatch popstate events.

You can use the history API like this to push a new state AND dispatch a popstate event.

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

Then listen for popstate events with a router.

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

CSS3 Rotate Animation

I have a rotating image using the same thing as you:

.knoop1 img{
    position:absolute;
    width:114px;
    height:114px;
    top:400px;
    margin:0 auto;
    margin-left:-195px;
    z-index:0;

    -webkit-transition-duration: 0.8s;
    -moz-transition-duration: 0.8s;
    -o-transition-duration: 0.8s;
    transition-duration: 0.8s;

    -webkit-transition-property: -webkit-transform;
    -moz-transition-property: -moz-transform;
    -o-transition-property: -o-transform;
     transition-property: transform;

     overflow:hidden;
}

.knoop1:hover img{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg); 
    -o-transform:rotate(360deg);
}

PHP append one array to another (not array_push or +)

array_merge is the elegant way:

$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b); 
// $merge is now equals to array('a','b','c','d');

Doing something like:

$merge = $a + $b;
// $merge now equals array('a','b')

Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.

Shortcut to comment out a block of code with sublime text

Just in case someone is using the Portuguese ABNT keyboard layout The shortcut is

Ctrl + ;

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

SQLAlchemy: how to filter date field?

if you want to get the whole period:

    from sqlalchemy import and_, func

    query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
                                              func.date(User.birthday) <= '1988-01-17'))

That means range: 1985-01-17 00:00 - 1988-01-17 23:59

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

I believe python arrays just admit values. So convert it to list:

kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

I am new to JavaScript development and ReactJS. I was unable to find an answer that works for me, until figuring it out by viewing the react-scripts code. Using ReactJS 15.4.1+ using react-scripts you can start with a custom host and/or port by using environment variables:

HOST='0.0.0.0' PORT=8080 npm start

Hopefully this helps newcomers like me.

Toggle Checkboxes on/off

if you want to toggle each box individually (or just one box works just as well):

I recommend using .each() , as it is easy to modify if you want different things to happen, and still relatively short and easy to read.

e.g. :

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});

on a side note... not sure why everyone uses .attr() or .prop() to (un)check things.

as far as I know, element.checked has always worked the same in all browsers?

Array.push() and unique items

Push always unique value in array

ab = [
     {"id":"1","val":"value1"},
     {"id":"2","val":"value2"},
     {"id":"3","val":"value3"}
   ];



var clickId = [];
var list = JSON.parse(ab);
$.each(list, function(index, value){
    if(clickId.indexOf(value.id) < 0){
        clickId.push(value.id);
    }
});

How to print GETDATE() in SQL Server with milliseconds in time?

This is equivalent to new Date().getTime() in JavaScript :

Use the below statement to get the time in seconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)

Use the below statement to get the time in milliseconds.

SELECT  cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)  * 1000

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

MySQL vs MongoDB 1000 reads

Honestly even if MongoDB is slower, MongoDB definitely makes me and you code faster.... no need to worry about silly table columns, row or entity migrations...

With MongoDB, you just instantiate a class and save!

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Why is Git better than Subversion?

First, concurrent version control seems like an easy problem to solve. It's not at all. Anyway...

SVN is quite non-intuitive. Git is even worse. [sarcastic-speculation] This might be because developers, that like hard problems like concurrent version control, don't have much interest in making a good UI. [/sarcastic-speculation]

SVN supporters think they don't need a distributed version-control system. I thought that too. But now that we use Git exclusively, I'm a believer. Now version control works for me AND the team/project instead of just working for the project. When I need a branch, I branch. Sometimes it's a branch that has a corresponding branch on the server, and sometimes it does not. Not to mention all the other advantages that I'll have to go study up on (thanks in part to the arcane and absurd lack of UI that is a modern version control system).

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

scipy.misc module has no attribute imread?

Running the following in a Jupyter Notebook, I had a similar error message:

from skimage import data
photo_data = misc.imread('C:/Users/ers.jpg')
type(photo_data)

'error' msg:

D:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\ipykernel_launcher.py:3: DeprecationWarning: imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead. This is separate from the ipykernel package so we can avoid doing imports until

And using the following I got it solved:

import matplotlib.pyplot
photo_data = matplotlib.pyplot.imread('C:/Users/ers.jpg')
type(photo_data)

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

I don't understand why you're using FirstOrDefault(x=> x.ID == key) when this could retrieve results much faster if you use Find(key). If you are querying with the Primary key of the table, the rule of thumb is to always use Find(key). FirstOrDefault should be used for predicate stuff like (x=> x.Username == username) etc.

this did not deserve a downvote as the heading of the question was not specific to linq on DB or Linq to List/IEnumerable etc.

How to decode JWT Token?

Extending on cooxkie answer, and dpix answer, when you are reading a jwt token (such as an access_token received from AD FS), you can merge the claims in the jwt token with the claims from "context.AuthenticationTicket.Identity" that might not have the same set of claims as the jwt token.

To Illustrate, in an Authentication Code flow using OpenID Connect,after a user is authenticated, you can handle the event SecurityTokenValidated which provides you with an authentication context, then you can use it to read the access_token as a jwt token, then you can "merge" tokens that are in the access_token with the standard list of claims received as part of the user identity:

    private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationOptions> context)
    {
        //get the current user identity
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)context.AuthenticationTicket.Identity;

        /*read access token from the current context*/
        string access_token = context.ProtocolMessage.AccessToken;

        JwtSecurityTokenHandler hand = new JwtSecurityTokenHandler();
        //read the token as recommended by Coxkie and dpix
        var tokenS = hand.ReadJwtToken(access_token);
        //here, you read the claims from the access token which might have 
        //additional claims needed by your application
        foreach (var claim in tokenS.Claims)
        {
            if (!claimsIdentity.HasClaim(claim.Type, claim.Value))
                claimsIdentity.AddClaim(claim);
        }

        return Task.FromResult(0);
    }

Difference between break and continue statement

First,i think you should know that there are two types of break and continue in Java which are labeled break,unlabeled break,labeled continue and unlabeled continue.Now, i will talk about the difference between them.

class BreakDemo {
public static void main(String[] args) {

    int[] arrayOfInts = 
        { 32, 87, 3, 589,
          12, 1076, 2000,
          8, 622, 127 };
    int searchfor = 12;

    int i;
    boolean foundIt = false;

    for (i = 0; i < arrayOfInts.length; i++) {
        if (arrayOfInts[i] == searchfor) {
            foundIt = true;
            break;//this is an unlabeled break,an unlabeled break statement terminates the innermost switch,for,while,do-while statement.
        }
    }

    if (foundIt) {
        System.out.println("Found " + searchfor + " at index " + i);
    } else {
        System.out.println(searchfor + " not in the array");
    }
}

An unlabeled break statement terminates the innermost switch ,for ,while ,do-while statement.

public class BreakWithLabelDemo {
public static void main(String[] args) {
    search:
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 5; j++) {
            System.out.println(i + " - " + j);
            if (j == 3)
                break search;//this is an labeled break.To notice the lab which is search.
        }
    }
}

A labeled break terminates an outer statement.if you javac and java this demo,you will get:

0 - 0
0 - 1
0 - 2
0 - 3
class ContinueDemo {
public static void main(String[] args) {

    String searchMe = "peter piper picked a " + "peck of pickled peppers";
    int max = searchMe.length();
    int numPs = 0;

    for (int i = 0; i < max; i++) {
        // interested only in p's
        if (searchMe.charAt(i) != 'p')
            continue;//this is an unlabeled continue.

        // process p's
        numPs++;
    }
    System.out.println("Found " + numPs + " p's in the string.");
}

An unlabeled continue statement skips the current iteration of a for,while,do-while statement.

public class ContinueWithLabelDemo {
public static void main(String[] args) {
    search:
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 5; j++) {
            System.out.println(i + " - " + j);
            if (j == 3)
                continue search;//this is an labeled continue.Notice the lab which is search
        }
    }
}

A labeled continue statement skips the current iteration of an outer loop marked with the given lable,if you javac and java the demo,you will get:

0 - 0
0 - 1
0 - 2
0 - 3
1 - 0
1 - 1
1 - 2
1 - 3
2 - 0
2 - 1
2 - 2
2 - 3

if you have any question , you can see the Java tutorial of this:enter link description here

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

XmlSerializer giving FileNotFoundException at constructor

Troubleshooting compilation errors on the other hand is very complicated. These problems manifest themselves in a FileNotFoundException with the message:

File or assembly name abcdef.dll, or one of its dependencies, was not found. File name: "abcdef.dll"
   at System.Reflection.Assembly.nLoad( ... )
   at System.Reflection.Assembly.InternalLoad( ... )
   at System.Reflection.Assembly.Load(...)
   at System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() 

You may wonder what a file not found exception has to do with instantiating a serializer object, but remember: the constructor writes C# files and tries to compile them. The call stack of this exception provides some good information to support that suspicion. The exception occurred while the XmlSerializer attempted to load an assembly generated by CodeDOM calling the System.Reflection.Assembly.Load method. The exception does not provide an explanation as to why the assembly that the XmlSerializer was supposed to create was not present. In general, the assembly is not present because the compilation failed, which may happen because, under rare circumstances, the serialization attributes produce code that the C# compiler fails to compile.

Note This error also occurs when the XmlSerializer runs under an account or a security environment that is not able to access the temp directory.

Source: http://msdn.microsoft.com/en-us/library/aa302290.aspx

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Best Regular Expression for Email Validation in C#

Updated answer for 2019.

Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Singleline);

public static bool IsValidEmailFormat(string emailInput)
{
    return _regex.IsMatch(emailInput);
}

Alternative Configuration for Regex:

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Compiled);

I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.

Thread Safety And Regex
Regex Best Practices

Iterating over Numpy matrix rows to apply a function each?

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

Count a list of cells with the same background color

I just created this and it looks easier. You get these 2 functions:

=GetColorIndex(E5)  <- returns color number for the cell

from (cell)

=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14

from (range of cells, color number you want to count)

example shows percent of cells with color 14

=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )

Create these 2 VBA functions in a Module (hit Alt-F11)

open + folders. double-click on Module1

Just paste this text below in, then close the module window (it must save it then):

Function GetColorIndex(Cell As Range)
  GetColorIndex = Cell.Interior.ColorIndex
End Function

Function CountColorIndexInRange(Rng As Range, TestColor As Long)
  Dim cnt
  Dim cl As Range
  cnt = 0

  For Each cl In Rng
    If GetColorIndex(cl) = TestColor Then
      Rem Debug.Print ">" & TestColor & "<"
      cnt = cnt + 1
    End If
  Next

  CountColorIndexInRange = cnt

End Function

Differences in boolean operators: & vs && and | vs ||

While the basic difference is that & is used for bitwise operations mostly on long, int or byte where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&.

The difference is more noticeable in some scenarios:

  1. Evaluating some of the expressions is time consuming
  2. Evaluating one of the expression can be done only if the previous one was true
  3. The expressions have some side-effect (intended or not)

First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.

For second point, see this example:

if ((a != null) & (a.isEmpty()))

This fails for null, as evaluating the second expression produces a NullPointerException. Logical operator && is lazy, if left operand is false, the result is false no matter what right operand is.

Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:

if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))

This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&, it works as intended and it stops after first failure.

As for a || b, it is equivalent of !(!a && !b), it stops if a is true, no more explanation needed.

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

This IP, site or mobile application is not authorized to use this API key

The Google Places API does not currently support Android or iOS keys generated from the Google APIs Console. Only Server and Browser keys are currently supported.

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

How to resolve 'npm should be run outside of the node repl, in your normal shell'

It's better to use the actual (msi) installer from nodejs.org instead of downloading the node executable only. The installer includes npm and makes it easier to manage your node installation. There is an installer for both 32-bit and 64-bit Windows.

Also a couple of other tidbits:

  • Installing modules globally doesn't do what you might expect. The only modules you should install globally (the -g flag in npm) are ones that install commands. So to install Express you would just do npm install express and that will install Express to your current working directory. If you were instead looking for the Express project generator (command), you need to do npm install -g express-generator for Express 4.

  • You can use node anywhere from your command prompt to execute scripts. For example if you have already written a separate script: node foo.js. Or you can open up the REPL (as you've already found out) by just selecting the node.js (start menu) shortcut or by just typing node in a command prompt.

Difference between SRC and HREF

A simple definition

  • SRC: If a resource can be placed inside the body tag (for image, script, iframe, frame)
  • HREF: If a resource cannot be placed inside the body tag and can only be linked (for html, css)

How do I install Maven with Yum?

I've just learned of a handy packaging tool called fpm recently. Stumbling upon this question I thought I might give it a try. Turns out, after reading @OrwellHindenberg's answer, it's easy to package maven into an RPM with fpm.

yum install -y gcc make rpm-build ruby-devel rubygems
gem install fpm

create a project directory and layout the directory structure of the package

mkdir maven-build
cd maven-build
mkdir -p etc/profile.d opt

create a file that we'll install to /etc/profile.d/maven.sh, we'll store this under the newly created etc/profile.d directory as maven.sh, with the following contents

export M3_HOME=/opt/apache-maven-3.1.0
export M3=$M3_HOME/bin
export PATH=$M3:$PATH

download and unpack the latest maven in the opt directory

wget http://www.eng.lsu.edu/mirrors/apache/maven/maven-3/3.1.0/binaries/apache-maven-3.1.0-bin.tar.gz
tar -xzf apache-maven-3.1.0-bin.tar.gz -C opt

finally, build the RPM

fpm -n maven-3.1.0 -s dir -t rpm etc opt

Now you can install maven through rpm

$ rpm -Uvh maven-3.1.0-1.0-1.x86_64.rpm 
Preparing...                ########################################### [100%]
   1:maven-3.1.0            ########################################### [100%]

and viola

$ which mvn
/opt/apache-maven-3.1.0/bin/mvn

not quite yum but closer to home ;)

How to remove the left part of a string?

Remove prefix from a string

# ...
if line.startswith(prefix):
   return line[len(prefix):]

Split on the first occurrence of the separator via str.partition()

def findvar(filename, varname="Path", sep="=") :
    for line in open(filename):
        if line.startswith(varname + sep):
           head, sep_, tail = line.partition(sep) # instead of `str.split()`
           assert head == varname
           assert sep_ == sep
           return tail

Parse INI-like file with ConfigParser

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
config.read(filename) # requires section headers to be present

path = config.get(section, 'path', raw=1) # case-insensitive, no interpolation

Other options

Error: fix the version conflict (google-services plugin)

Same error gets thrown when

apply plugin: 'com.google.gms.google-services'

is not added to bottom of the module build.gradle file.

How to convert answer into two decimal point

If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this

dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))

How to make 'submit' button disabled?

It is important that you include the "required" keyword inside each one of your mandatory input tags for it to work.

 <form (ngSubmit)="login(loginForm.value)" #loginForm="ngForm">
    ...
    <input ngModel required name="username" id="userName" type="text" class="form-control" placeholder="User Name..." />
    <button type="submit" [disabled]="loginForm.invalid" class="btn btn-primary">Login</button>

How to remove the last character from a bash grep output

cat file.txt | grep "company_name" | cut -d '=' -f 2 | cut -d ';' -f 1

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

For a minimum API level of 15, you'd want to use AppCompatActivity. So for example, your MainActivity would look like this:

public class MainActivity extends AppCompatActivity {
    ....
    ....
}

To use the AppCompatActivity, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:

compile 'com.android.support:appcompat-v7:22:2.0'

You can use this AppCompat as your main Activity, which can then be used to launch Fragments or other Activities (this depends on what kind of app you're building).

The BigNerdRanch book is a good resource, but yeah, it's outdated. Read it for general information on how Android works, but don't expect the specific classes they use to be up to date.

How to set a variable inside a loop for /F

The following should work:

setlocal EnableDelayedExpansion
for /F "tokens=*" %%a in ('type %FileName%') do (
    set "z=%%a"
    echo %z%
    echo %%a
)

Set scroll position

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

Is there an "if -then - else " statement in XPath?

Somewhat simpler XPath 1.0 solution, adapted from Tomalek's (posted here) and Dimitre's (here):

concat(substring($s1, 1 div number($cond)), substring($s2, 1 div number(not($cond))))

Note: I found an explicit number() was required to convert the bool to an int otherwise some XPath evaluators threw a type mismatch error. Depending on how strict your XPath processor is type-matching you may not need it.

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

How to select/get drop down option in Selenium 2

in ruby for constantly using, add follow:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value
            option.click
              return
           end
       end
    end
  end
end

and you will be able to select value:

browser.find_element(:xpath, ".//xpath").select("Value")

How to skip the first n rows in sql query

For SQL Server 2012 and later versions, the best method is @MajidBasirati's answer.

I also loved @CarlosToledo's answer, it's not limited to any SQL Server version but it's missing Order By Clauses. Without them, it may return wrong results.

For SQL Server 2008 and later I would use Common Table Expressions for better performance.

-- This example omits first 10 records and select next 5 records
;WITH MyCTE(Id) as
(
    SELECT TOP (10) Id 
    FROM MY_TABLE
    ORDER BY Id
)
SELECT TOP (5) * 
FROM MY_TABLE
    INNER JOIN MyCTE ON (MyCTE.Id <> MY_TABLE.Id) 
ORDER BY Id

How to capture the "virtual keyboard show/hide" event in Android?

Based on the Code from Nebojsa Tomcic I've developed the following RelativeLayout-Subclass:

import java.util.ArrayList;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public class KeyboardDetectorRelativeLayout extends RelativeLayout {

    public interface IKeyboardChanged {
        void onKeyboardShown();
        void onKeyboardHidden();
    }

    private ArrayList<IKeyboardChanged> keyboardListener = new ArrayList<IKeyboardChanged>();

    public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public KeyboardDetectorRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyboardDetectorRelativeLayout(Context context) {
        super(context);
    }

    public void addKeyboardStateChangedListener(IKeyboardChanged listener) {
        keyboardListener.add(listener);
    }

    public void removeKeyboardStateChangedListener(IKeyboardChanged listener) {
        keyboardListener.remove(listener);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
        final int actualHeight = getHeight();

        if (actualHeight > proposedheight) {
            notifyKeyboardShown();
        } else if (actualHeight < proposedheight) {
            notifyKeyboardHidden();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void notifyKeyboardHidden() {
        for (IKeyboardChanged listener : keyboardListener) {
            listener.onKeyboardHidden();
        }
    }

    private void notifyKeyboardShown() {
        for (IKeyboardChanged listener : keyboardListener) {
            listener.onKeyboardShown();
        }
    }

}

This works quite fine... Mark, that this solution will just work when Soft Input Mode of your Activity is set to "WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE"

Split text file into smaller multiple text file using command line

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=100
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
 CALL :select
 FOR /f "tokens=1*delims==" %%b IN ('set dfile') DO IF /i "%%b"=="dfile" >>"%%c" ECHO(%%a
)
GOTO :EOF
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
SET "dfile=%sourcedir%\file%fcount:~-2%.txt"
GOTO :EOF

Here's a native windows batch that should accomplish the task.

Now I'll not say that it'll be fast (less than 2 minutes for each 5Kline output file) or that it will be immune to batch character-sensitivites. Really depends on the characteristics of your target data.

I used a file named q25249516.txt containing 100Klines of data for my testing.


Revised quicker version

REM

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET /a fcount=199
SET /a llimit=5000
SET /a lcount=%llimit%
FOR /f "usebackqdelims=" %%a IN ("%sourcedir%\q25249516.txt") DO (
 CALL :select
 >>"%sourcedir%\file$$.txt" ECHO(%%a
)
SET /a lcount=%llimit%
:select
SET /a lcount+=1
IF %lcount% lss %llimit% GOTO :EOF
SET /a lcount=0
SET /a fcount+=1
MOVE /y "%sourcedir%\file$$.txt" "%sourcedir%\file%fcount:~-2%.txt" >NUL 2>nul
GOTO :EOF

Note that I used llimit of 50000 for testing. Will overwrite the early file numbers if llimit*100 is gearter than the number of lines in the file (cure by setting fcount to 1999 and use ~3 in place of ~2 in file-renaming line.)

typedef fixed length array

Arrays can't be passed as function parameters by value in C.

You can put the array in a struct:

typedef struct type24 {
    char byte[3];
} type24;

and then pass that by value, but of course then it's less convenient to use: x.byte[0] instead of x[0].

Your function type24_to_int32(char value[3]) actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value), and the 3 is ignored.

If you're happy passing by pointer, you could stick with the array and do:

type24_to_int32(const type24 *value);

This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:

(*value)[0]

I'm not sure that's really a gain, since if you accidentally write value[1] then something stupid happens.

What causes this error? "Runtime error 380: Invalid property value"

I had the same problem in masked edit box control that was used for Date and the error was due to Date format property in Region settings of windows. Changed "M/d/yyyy" to "dd/MM/yyyy" and everything worked out.

Should I use != or <> for not equal in T-SQL?

!=, despite being non-ANSI, is more in the true spirit of SQL as a readable language. It screams not equal. <> says it's to me (less than, greater than) which is just weird. I know the intention is that it's either less than or greater than hence not equal, but that's a really complicated way of saying something really simple.

I've just had to take some long SQL queries and place them lovingly into an XML file for a whole bunch of stupid reasons I won't go into.

Suffice to say XML is not down with <> at all and I had to change them to != and check myself before I riggedy wrecked myself.

php return 500 error but no error log

If you still have 500 error and no logs you can try to execute from command line:

php -f file.php

it will not work exactly like in a browser (from server) but if there is syntax error in your code, you will see error message in console.

jquery - return value using ajax result on success

The trouble is that you can not return a value from an asynchronous call, like an AJAX request, and expect it to work.

The reason is that the code waiting for the response has already executed by the time the response is received.

The solution to this problem is to run the necessary code inside the success: callback. That way it is accessing the data only when it is available.

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
            // Run the code here that needs
            //    to access the data returned
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

Another possibility (which is effectively the same thing) is to call a function inside your success: callback that passes the data when it is available.

function isSession(selector) {
    $.ajax({
        type: "POST",
        url: '/order.html',
        data: ({ issession : 1, selector: selector }),
        dataType: "html",
        success: function(data) {
                // Call this function on success
            someFunction( data );
            return data;
        },
        error: function() {
            alert('Error occured');
        }
    });
}

function someFunction( data ) {
    // Do something with your data
}

Finding out the name of the original repository you cloned from in Git

Edited for clarity:

This will work to to get the value if the remote.origin.url is in the form protocol://auth_info@git_host:port/project/repo.git. If you find it doesn't work, adjust the -f5 option that is part of the first cut command.

For the example remote.origin.url of protocol://auth_info@git_host:port/project/repo.git the output created by the cut command would contain the following:

-f1: protocol: -f2: (blank) -f3: auth_info@git_host:port -f4: project -f5: repo.git

If you are having problems, look at the output of the git config --get remote.origin.url command to see which field contains the original repository. If the remote.origin.url does not contain the .git string then omit the pipe to the second cut command.

#!/usr/bin/env bash
repoSlug="$(git config --get remote.origin.url | cut -d/ -f5 | cut -d. -f1)"
echo ${repoSlug}

No module named MySQLdb

If your are using SQLAlchemy and the error is in /site-packages/sqlalchemy/dialects/mysql/mysqldb.py:

from ...connectors.mysqldb import (
                        MySQLDBExecutionContext,
                        MySQLDBCompiler,
                        MySQLDBIdentifierPreparer,
                        MySQLDBConnector
                    )

so you may have missed mysqldb connector for SQLAlchemy and the solution is to re-install sqlalchemy after installing mysql-python module.

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

Check if list contains element that contains a string and get that element

You could use Linq's FirstOrDefault extension method:

string element = myList.FirstOrDefault(s => s.Contains(myString));

This will return the fist element that contains the substring myString, or null if no such element is found.

If all you need is the index, use the List<T> class's FindIndex method:

int index = myList.FindIndex(s => s.Contains(myString));

This will return the the index of fist element that contains the substring myString, or -1 if no such element is found.

How to get form input array into PHP array

Nonetheless, you can use below code as,

$a = array('name1','name2','name3');
$b = array('email1','email2','email3');

function f($a,$b){
    return "The name is $a and email is $b, thank you";
}

$c = array_map('f', $a, $b);

//echoing the result

foreach ($c as $val) {
    echo $val.'<br>';
}

Count frequency of words in a list and sort by frequency

You can use reduce() - A functional way.

words = "apple banana apple strawberry banana lemon"
reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {})

returns:

{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2}

Fastest JavaScript summation

one of the simplest, fastest, more reusable and flexible is:

Array.prototype.sum = function () {
    for(var total = 0,l=this.length;l--;total+=this[l]); return total;
}

// usage
var array = [1,2,3,4,5,6,7,8,9,10];
array.sum()

Error Dropping Database (Can't rmdir '.test\', errno: 17)

A database is represented by a directory under the data directory (usually /var/lib/mysql), and the directory is intended for storage of table data.

The DROP DATABASE statement will remove all table files and then remove the directory that represented the database. It will not, however, remove non-table files, whereby making it not possible to remove the directory.

MySQL displays an error message when it cannot remove the directory

you can really drop the database manually by removing any remaining files in the database directory and then the directory itself.

Delete worksheet in Excel using VBA

try this within your if statements:

Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

To make sure your code is safe, you can wrap it in

if (this.isMounted()) {
    this.setState({'time': remainTimeInfo});
}

to ensure that the component is still mounted.

ValueError: object too deep for desired array while using convolution

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

How come I can't remove the blue textarea border in Twitter Bootstrap?

.was-validated .form-control:valid,
.was-validated .form-control:invalid {
    background-image: none;
    
    box-shadow: none;
}
.was-validated .form-control:invalid:focus,
.was-validated .form-control:valid {

    box-shadow: none;
}
.form-control:focus {
    outline: none;
    box-shadow: none;
}

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

How to add text inside the doughnut chart using Chart.js?

None of the other answers resize the text based off the amount of text and the size of the doughnut. Here is a small script you can use to dynamically place any amount of text in the middle, and it will automatically resize it.

Example: http://jsfiddle.net/kdvuxbtj/

Doughnut With Dynamic Text in the Middle

It will take any amount of text in the doughnut sized perfect for the doughnut. To avoid touching the edges you can set a side-padding as a percentage of the diameter of the inside of the circle. If you don't set it, it will default to 20. You also the color, the font, and the text. The plugin takes care of the rest.

The plugin code will start with a base font size of 30px. From there it will check the width of the text and compare it against the radius of the circle and resize it based off the circle/text width ratio.

It has a default minimum font size of 20px. If the text would exceed the bounds at the minimum font size, it will wrap the text. The default line height when wrapping the text is 25px, but you can change it. If you set the default minimum font size to false, the text will become infinitely small and will not wrap.

It also has a default max font size of 75px in case there is not enough text and the lettering would be too big.

This is the plugin code

Chart.pluginService.register({
  beforeDraw: function(chart) {
    if (chart.config.options.elements.center) {
      // Get ctx from string
      var ctx = chart.chart.ctx;

      // Get options from the center object in options
      var centerConfig = chart.config.options.elements.center;
      var fontStyle = centerConfig.fontStyle || 'Arial';
      var txt = centerConfig.text;
      var color = centerConfig.color || '#000';
      var maxFontSize = centerConfig.maxFontSize || 75;
      var sidePadding = centerConfig.sidePadding || 20;
      var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
      // Start with a base font of 30px
      ctx.font = "30px " + fontStyle;

      // Get the width of the string and also the width of the element minus 10 to give it 5px side padding
      var stringWidth = ctx.measureText(txt).width;
      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

      // Find out how much the font can grow in width.
      var widthRatio = elementWidth / stringWidth;
      var newFontSize = Math.floor(30 * widthRatio);
      var elementHeight = (chart.innerRadius * 2);

      // Pick a new font size so it will not be larger than the height of label.
      var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
      var minFontSize = centerConfig.minFontSize;
      var lineHeight = centerConfig.lineHeight || 25;
      var wrapText = false;

      if (minFontSize === undefined) {
        minFontSize = 20;
      }

      if (minFontSize && fontSizeToUse < minFontSize) {
        fontSizeToUse = minFontSize;
        wrapText = true;
      }

      // Set font settings to draw it correctly.
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
      ctx.font = fontSizeToUse + "px " + fontStyle;
      ctx.fillStyle = color;

      if (!wrapText) {
        ctx.fillText(txt, centerX, centerY);
        return;
      }

      var words = txt.split(' ');
      var line = '';
      var lines = [];

      // Break words up into multiple lines if necessary
      for (var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = ctx.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > elementWidth && n > 0) {
          lines.push(line);
          line = words[n] + ' ';
        } else {
          line = testLine;
        }
      }

      // Move the center up depending on line height and number of lines
      centerY -= (lines.length / 2) * lineHeight;

      for (var n = 0; n < lines.length; n++) {
        ctx.fillText(lines[n], centerX, centerY);
        centerY += lineHeight;
      }
      //Draw text in center
      ctx.fillText(line, centerX, centerY);
    }
  }
});

And you use the following options in your chart object

options: {
  elements: {
    center: {
      text: 'Red is 2/3 the total numbers',
      color: '#FF6384', // Default is #000000
      fontStyle: 'Arial', // Default is Arial
      sidePadding: 20, // Default is 20 (as a percentage)
      minFontSize: 20, // Default is 20 (in px), set to false and text will not wrap.
      lineHeight: 25 // Default is 25 (in px), used for when text wraps
    }
  }
}

Credit to @Jenna Sloan for help with the math used in this solution.

How to sort an array of objects by multiple fields?

I was looking for something similar and ended up with this:

First we have one or more sorting functions, always returning either 0, 1 or -1:

const sortByTitle = (a, b): number => 
  a.title === b.title ? 0 : a.title > b.title ? 1 : -1;

You can create more functions for each other property you want to sort on.

Then I have a function that combines these sorting functions into one:

const createSorter = (...sorters) => (a, b) =>
  sorters.reduce(
    (d, fn) => (d === 0 ? fn(a, b) : d),
    0
  );

This can be used to combine the above sorting functions in a readable way:

const sorter = createSorter(sortByTitle, sortByYear)

items.sort(sorter)

When a sorting function returns 0 the next sorting function will be called for further sorting.

How do I update/upsert a document in Mongoose?

You can simply update the record with this and get the updated data in response

router.patch('/:id', (req, res, next) => {
    const id = req.params.id;
    Product.findByIdAndUpdate(id, req.body, {
            new: true
        },
        function(err, model) {
            if (!err) {
                res.status(201).json({
                    data: model
                });
            } else {
                res.status(500).json({
                    message: "not found any relative data"
                })
            }
        });
});

Android Use Done button on Keyboard to click button

And this is a Kotlin version:

editText.setOnEditorActionListener { v, actionId, event ->
  if(actionId == EditorInfo.IME_ACTION_DONE){
      //Put your action there
      true
  } else {
      false
  }
}

How do I use vim registers?

I was pleased when I discovered the 0 register. If you yank text without assigning it to a particular register, then it will be assigned to the 0 register, as well as being saved in the default " register. The difference between the 0 and " registers is that 0 is only populated with yanked text, whereas the default register is also populated with text deleted using d/D/x/X/c/C/s/S commands.

I find this useful when I want to copy some text, delete something and replace it with the copied text. The following steps illustrate an example:

  • Yank the text you want to copy with y[motion] - this text is saved in " and 0 registers
  • Delete the text you want to replace with d[motion] - this text is saved in " register
  • Paste the yanked text with "0p

where " is the command to use a register for the next command.

On the final step, if you were to paste from the default register (with p), it would use the text that you had just deleted (probably not what you intended).

Note that p or P pastes from the default register. The longhand equivalent would be ""p (or ""P) and "0 holds the last yank, "1holds the last delete or change.

For more info see :help registers.

Android device chooser - My device seems offline

I'm running JellyBean. I noticed for the first time that there is a "Developer Options" slider at the top of the Developer Options menu. Note that I'm not talking about the USB Debugging checkbox - which is a different option. I slid the Developer Options checkbox to "on" and was back in business. Unfortunately, I'm not sure if this is the whole story because I also ran the adb kill/start commands that David Caunt pointed out above.

Safe Area of Xcode 9

Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.

When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view.

For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0.

According to Apple, Xcode 9 - Release note
Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS.

enter image description here


Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide.

Safe Area Layout: enter image description here

AutoLayout

enter image description here


How to work with Safe Area Layout?

Follow these steps to find solution:

  • Enable 'Safe Area Layout', if not enabled.
  • Remove 'all constraint' if they shows connection with with Super view and re-attach all with safe layout anchor. OR Double click on a constraint and edit connection from super view to SafeArea anchor

Here is sample snapshot, how to enable safe area layout and edit constraint.

enter image description here

Here is result of above changes

enter image description here


Layout Design with SafeArea
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

enter image description here

Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned.

enter image description here

For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides.

enter image description here


Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:

Assuming we have the green view as a property in our view controller:

private let greenView = UIView()

We might have a function to set up the views and constraints called from viewDidLoad:

private func setupView() {
  greenView.translatesAutoresizingMaskIntoConstraints = false
  greenView.backgroundColor = .green
  view.addSubview(greenView)
}

Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:

 let margins = view.layoutMarginsGuide
    NSLayoutConstraint.activate([
      greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
      greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
 ])

Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

if #available(iOS 11, *) {
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
   greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
   guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
   ])

} else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
   greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
   bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
   ])
}


Result:

enter image description here


Following UIView extension, make it easy for you to work with SafeAreaLayout programatically.

extension UIView {

  // Top Anchor
  var safeAreaTopAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.topAnchor
    } else {
      return self.topAnchor
    }
  }

  // Bottom Anchor
  var safeAreaBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.bottomAnchor
    } else {
      return self.bottomAnchor
    }
  }

  // Left Anchor
  var safeAreaLeftAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.leftAnchor
    } else {
      return self.leftAnchor
    }
  }

  // Right Anchor
  var safeAreaRightAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.rightAnchor
    } else {
      return self.rightAnchor
    }
  }

}

Here is sample code in Objective-C:


Here is Apple Developer Official Documentation for Safe Area Layout Guide


Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout

Why does the C++ STL not provide any "tree" containers?

All STL container are externally represented as "sequences" with one iteration mechanism. Trees don't follow this idiom.

PostgreSQL error 'Could not connect to server: No such file or directory'

for what it's worth, I experienced this same error when I had a typo (md4 instead of md5) in my pg_hba.conf file (/etc/postgresql/9.5/main/pg_hba.conf)

If you got here as I did, double-check that file once to make sure there isn't anything ridiculous in there.

Call a method of a controller from another controller using 'scope' in AngularJS

The best approach for you to communicate between the two controllers is to use events.

Scope Documentation

In this check out $on, $broadcast and $emit.

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

Ideally in your usage you would write an event in controller 1 as:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Edit: Realised it was communication between two modules

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module. That way you can communicate to the other app.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

If you have a hard time remembering the default values (I know I have...) here's a short extract from BalusC's answer:

Component    | Submit          | Refresh
------------ | --------------- | --------------
f:ajax       | execute="@this" | render="@none"
p:ajax       | process="@this" | update="@none"
p:commandXXX | process="@form" | update="@none"

Can I have onScrollListener for a ScrollView?

Every instance of View calls getViewTreeObserver(). Now when holding an instance of ViewTreeObserver, you can add an OnScrollChangedListener() to it using the method addOnScrollChangedListener().

You can see more information about this class here.

It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY() or getScrollX() from within the listener though.

scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        int scrollY = rootScrollView.getScrollY(); // For ScrollView
        int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
        // DO SOMETHING WITH THE SCROLL COORDINATES
    }
});

Group dataframe and get sum AND count?

If you have lots of columns and only one is different you could do:

In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
                      Organisation Name   Amount
Company Name                                   
Vifor Pharma UK Ltd                  5  4207.93

Note you can then rename the Organisation Name column as you wish.

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

tooltips for Button

You should use both title and alt attributes to make it work in all browsers.

<button title="Hello World!" alt="Hello World!">Sample Button</button>

Uncaught TypeError: Cannot assign to read only property

If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.

var globalObject = {
    name:"a",
    age:20
}
function() {
    let localObject = {
    name:'a',
    age:21
    }
    this.globalObject = localObject;
}

Create a shortcut on Desktop

I Use simply for my app:

using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object  
...   
private static void CreateShortcut()
    {
        string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) 
            + Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        //shortcut...
        shortcut.Save();
    }

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

You have to just check whether your WAMP server is online or not.

To put your WAMP server online, follow these steps.

  1. Go to your WAMP server notification icon (in the task bar).
  2. Single click on the WAMP server icon.
  3. Select last option from the menu, that is, Put Online
  4. Your server will restart automatically (in the latest versions only). Otherwise, you have to restart your server manually.

And you are DONE...

How to get the contents of a webpage in a shell variable?

You can use wget command to download the page and read it into a variable as:

content=$(wget google.com -q -O -)
echo $content

We use the -O option of wget which allows us to specify the name of the file into which wget dumps the page contents. We specify - to get the dump onto standard output and collect that into the variable content. You can add the -q quiet option to turn off's wget output.

You can use the curl command for this aswell as:

content=$(curl -L google.com)
echo $content

We need to use the -L option as the page we are requesting might have moved. In which case we need to get the page from the new location. The -L or --location option helps us with this.

Compare given date with today

If you do things with time and dates Carbon is you best friend;

Install the package then:

$theDay = Carbon::make("2010-01-21 00:00:00.0");

$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))

lt = less than, gt = greater than

As in the question:

$theDay->gt(Carbon::today()) ? true : false;

and much more;

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

How to convert from Hex to ASCII in JavaScript?

I found a useful function present in web3 library.

var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)

How to display errors on laravel 4?

Just go to your app/storage/logs there logs of error available. Go to filename of today's date time and you will find latest error in your application.

OR

Open app/config/app.php and change setting

'debug' => false,

To

'debug' => true, 

OR

Go to .env file to your application and change the configuratuion

APP_LOG_LEVEL=debug

Simple pagination in javascript

Below is the pagination logic as a function


function Pagination(pageEleArr, numOfEleToDisplayPerPage) {
    this.pageEleArr = pageEleArr;
    this.numOfEleToDisplayPerPage = numOfEleToDisplayPerPage;
    this.elementCount = this.pageEleArr.length;
    this.numOfPages = Math.ceil(this.elementCount / this.numOfEleToDisplayPerPage);
    const pageElementsArr = function (arr, eleDispCount) {
        const arrLen = arr.length;
        const noOfPages = Math.ceil(arrLen / eleDispCount);
        let pageArr = [];
        let perPageArr = [];
        let index = 0;
        let condition = 0;
        let remainingEleInArr = 0;

        for (let i = 0; i < noOfPages; i++) {

            if (i === 0) {
                index = 0;
                condition = eleDispCount;
            }
            for (let j = index; j < condition; j++) {
                perPageArr.push(arr[j]);
            }
            pageArr.push(perPageArr);
            if (i === 0) {
                remainingEleInArr = arrLen - perPageArr.length;
            } else {
                remainingEleInArr = remainingEleInArr - perPageArr.length;
            }

            if (remainingEleInArr > 0) {
                if (remainingEleInArr > eleDispCount) {
                    index = index + eleDispCount;
                    condition = condition + eleDispCount;
                } else {
                    index = index + perPageArr.length;
                    condition = condition + remainingEleInArr;
                }
            }
            perPageArr = [];
        }
        return pageArr;
    }
    this.display = function (pageNo) {
        if (pageNo > this.numOfPages || pageNo <= 0) {
            return -1;
        } else {
            console.log('Inside else loop in display method');
            console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage));
            console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1]);
            return pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1];
        }
    }
}

const p1 = new Pagination(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
console.log(p1.elementCount);
console.log(p1.pageEleArr);
console.log(p1.numOfPages);
console.log(p1.numOfEleToDisplayPerPage);
console.log(p1.display(3));

Parsing ISO 8601 date in Javascript

The Date object handles 8601 as it's first parameter:

_x000D_
_x000D_
var d = new Date("2014-04-07T13:58:10.104Z");_x000D_
console.log(d.toString());
_x000D_
_x000D_
_x000D_

Can a java file have more than one class?

Yes, as many as you want!

BUT, only one "public" class in every file.

Html table tr inside td

You can check this just use table inside table like this

_x000D_
_x000D_
<!DOCTYPE html>
<html>

<head>
  <style>
    table,
    th,
    td {
      border: 1px solid black;
      border-collapse: collapse;
    }
  </style>
</head>

<body>
  <table style="width:100%">
    <tr>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
      <th>ABC</th>
    </tr>
    <tr>
      <td>Item1</td>
      <td>Item1</td>
      <td>
        <table style="width:100%">
          <tr>
            <td>name1</td>
            <td>price1</td>
          </tr>
          <tr>
            <td>name2</td>
            <td>price2</td>
          </tr>
          <tr>
            <td>name3</td>
            <td>price3</td>
          </tr>
        </table>
      </td>
      <td>item1</td>
    </tr>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
      <td>D</td>
    </tr>
    <tr>
      <td>E</td>
      <td>F</td>
      <td>G</td>
      <td>H</td>
    </tr>
    <tr>
      <td>E</td>
      <td>R</td>
      <td>T</td>
      <td>T</td>
    </tr>
  </table>
</body>

</html>
_x000D_
_x000D_
_x000D_

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

Android Studio - How to increase Allocated Heap Size

May help someone that get this problem:

I edit studio64.exe.vmoptions file, but failed to save.

So I opened this file with Notepad++ in Run as Administrator mode and then saved successfully.

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

HTML:

<div id="left"></div>
<div id="content">
        <textarea cols="2" rows="10" id="rules"></textarea>
</div>

CSS:

body{
    width:100%;
    border:1px solid black;
    border-radius:5px;

}
#left{
    width:20%;
height:400px;
    float:left;
    border: 1px solid black;
    display:block;
}
#content{
    width:78%;
    height:400px;
    float:left;
    border:1px solid black;
    text-align:center;
}
textarea
{
   margin-top:100px;
    width:98%;
}

DEMO: HERE

Convert DataTable to IEnumerable<T>

Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226

    public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
    {
        List<dynamic> result = new List<dynamic>();
        Dictionary<string, object> d;
        foreach (DataRow dr in dt.Rows)
        {
            d = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)
                d.Add(dc.ColumnName, dr[dc]);

            result.Add(GetDynamicObject(d));
        }
        return result.AsEnumerable<dynamic>();
    }

    public static dynamic GetDynamicObject(Dictionary<string, object> properties)
    {
        return new MyDynObject(properties);
    }

    public sealed class MyDynObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyDynObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }

Custom Python list sorting

Even better:

student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]

sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Taken from: https://docs.python.org/3/howto/sorting.html

Select info from table where row has max date

You can use a window MAX() like this:

SELECT
  *, 
  max_date = MAX(date) OVER (PARTITION BY group)
FROM table

to get max dates per group alongside other data:

group  date      cash  checks  max_date
-----  --------  ----  ------  --------
1      1/1/2013  0     0       1/3/2013
2      1/1/2013  0     800     1/1/2013
1      1/3/2013  0     700     1/3/2013
3      1/1/2013  0     600     1/5/2013
1      1/2/2013  0     400     1/3/2013
3      1/5/2013  0     200     1/5/2013

Using the above output as a derived table, you can then get only rows where date matches max_date:

SELECT
  group,
  date,
  checks
FROM (
  SELECT
    *, 
    max_date = MAX(date) OVER (PARTITION BY group)
  FROM table
) AS s
WHERE date = max_date
;

to get the desired result.

Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.

You can try the method at SQL Fiddle.

minimum double value in C/C++

If you do not have float exceptions enabled (which you shouldn't imho), you can simply say:

double neg_inf = -1/0.0;

This yields negative infinity. If you need a float, you can either cast the result

float neg_inf = (float)-1/0.0;

or use single precision arithmetic

float neg_inf = -1.0f/0.0f;

The result is always the same, there is exactly one representation of negative infinity in both single and double precision, and they convert to each other as you would expect.

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

How do I subtract minutes from a date in javascript?

This is what I found:

//First, start with a particular time
var date = new Date();

//Add two hours
var dd = date.setHours(date.getHours() + 2);

//Go back 3 days
var dd = date.setDate(date.getDate() - 3);

//One minute ago...
var dd = date.setMinutes(date.getMinutes() - 1);

//Display the date:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = new Date(dd);
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var displayDate = monthNames[monthIndex] + ' ' + day + ', ' + year;
alert('Date is now: ' + displayDate);

Sources:

http://www.javascriptcookbook.com/article/Perform-date-manipulations-based-on-adding-or-subtracting-time/

https://stackoverflow.com/a/12798270/1873386

Convert month int to month name

You can do something like this instead.

return new DateTime(2010, Month, 1).ToString("MMM");

Do the parentheses after the type name make a difference with new?

Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.

./configure : /bin/sh^M : bad interpreter

This usually happens when you have edited a file from Windows and now trying to execute that from some unix based machine.

The solution presented on Linux Forum worked for me (many times):

perl -i -pe's/\r$//;' <file name here>

Hope this helps.

PS: you need to have perl installed on your unix/linux machine.

cannot find zip-align when publishing app

i solved by RUN as Administrator @ your SDK Manager.exe in directory C:\Program Files\Android SDK

after that u'll get updated build tools an any repository

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

How does BitLocker affect performance?

My current work machine came with bitlocker, and being an upgrade from the prior model. It only seemed faster to me. What I have found, however, is that bitlocker is more bullet proof than truecrypt, when it comes to accurately laying down the data. I do a lot of work in SAS which constantly writes backup copies to disk as it moves along and shoots a variety of output types to disk at the end. SAS works fine writing output from multithreaded processes back to bitlocker and doesn't seem to know it's there. This has not been the case for me with truecrypt. I'm not sure what happens or how, but I found that processes got out of synch when working with source/output data in a truecrypt container, which is what I installed on my second work computer since it had no bitlocker. The constant backups were shooting to an SSD while the truecrypt results were on a regular HD. Maybe that speed difference helped trip it up. Whatever the cause, I had to quit using truecrypt on that second computer because it made my SAS results out of synch with respect to processing order and it screwed up some of my processes and data. Scary stuff in my world.

I work with people who have successfully used Truecrypt on the exact same computer, but they weren't using a disk intensive app. like SAS.

Bitlocker to Go, the encryption which bitlocker applies to thumb-drives, does slow things down quite a bit when it comes to read/write times. It's not too hard to use as long as you remember your password on the thumbdrive, and are willing to wait for it to format/initialize the drive, but in my experience it made access to the flash drive about 4 times as slow. Don't know why it would slow down a thumb drive and not a disk but that's how it was for me and my coworker.

Based on my success with bitlocker at work, I bought Windows Pro for my home computer to get bitlocker and plan to encrypt some directories with it for things like financials.

Python Flask, how to set content type

Try like this:

from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    return Response(xml, mimetype='text/xml')

The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).

Response (and request) objects are documented here: http://werkzeug.pocoo.org/docs/wrappers/

C# string replace

Make sure you properly escape the quotes.

  string line = "\"Text\",\"Text\",\"Text\",";

  string result = line.Replace("\",\"", ";");

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

How to restrict SSH users to a predefined set of commands after login?

[Disclosure: I wrote sshdo which is described below]

If you want the login to be interactive then setting up a restricted shell is probably the right answer. But if there is an actual set of commands that you want to allow (and nothing else) and it's ok for these commands to be executed individually via ssh (e.g. ssh user@host cmd arg blah blah), then a generic command whitelisting control for ssh might be what you need. This is useful when the commands are scripted somehow at the client end and doesn't require the user to actually type in the ssh command.

There's a program called sshdo for doing this. It controls which commands may be executed via incoming ssh connections. It's available for download at:

http://raf.org/sshdo/ (read manual pages here) https://github.com/raforg/sshdo/

It has a training mode to allow all commands that are attempted, and a --learn option to produce the configuration needed to allow learned commands permanently. Then training mode can be turned off and any other commands will not be executed.

It also has an --unlearn option to stop allowing commands that are no longer in use so as to maintain strict least privilege as requirements change over time.

It is very fussy about what it allows. It won't allow a command with any arguments. Only complete shell commands can be allowed.

But it does support simple patterns to represent similar commands that vary only in the digits that appear on the command line (e.g. sequence numbers or date/time stamps).

It's like a firewall or whitelisting control for ssh commands.

And it supports different commands being allowed for different users.

Perform Segue programmatically and pass parameters to the destination view

Swift 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ExampleSegueIdentifier" {
        if let destinationVC = segue.destination as? ExampleSegueVC {
            destinationVC.exampleString = "Example"
        }
    }
}

Swift 3:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ExampleSegueIdentifier" {
            if let destinationVC = segue.destinationViewController as? ExampleSegueVC {
                destinationVC.exampleString = "Example"
            }
        }
    }

When should I use curly braces for ES6 import?

This is a default import:

// B.js
import A from './A'

It only works if A has the default export:

// A.js
export default 42

In this case it doesn’t matter what name you assign to it when importing:

// B.js
import A from './A'
import MyA from './A'
import Something from './A'

Because it will always resolve to whatever is the default export of A.


This is a named import called A:

import { A } from './A'

It only works if A contains a named export called A:

export const A = 42

In this case the name matters because you’re importing a specific thing by its export name:

// B.js
import { A } from './A'
import { myA } from './A' // Doesn't work!
import { Something } from './A' // Doesn't work!

To make these work, you would add a corresponding named export to A:

// A.js
export const A = 42
export const myA = 43
export const Something = 44

A module can only have one default export, but as many named exports as you'd like (zero, one, two, or many). You can import them all together:

// B.js
import A, { myA, Something } from './A'

Here, we import the default export as A, and named exports called myA and Something, respectively.

// A.js
export default 42
export const myA = 43
export const Something = 44

We can also assign them all different names when importing:

// B.js
import X, { myA as myX, Something as XSomething } from './A'

The default exports tend to be used for whatever you normally expect to get from the module. The named exports tend to be used for utilities that might be handy, but aren’t always necessary. However it is up to you to choose how to export things: for example, a module might have no default export at all.

This is a great guide to ES modules, explaining the difference between default and named exports.

How to link a folder with an existing Heroku app

for existing repository

type in terminal

$ heroku git:remote -a example

enter image description here

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I faced this error becouse I sent the Query string with wrong format

http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &

so make sure your Query String or passed parameter in the right format

How to read file from relative path in Java project? java.io.File cannot find the path specified

While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

Cannot add a project to a Tomcat server in Eclipse

Steps I used to resolve it:

  1. Double click on Tomcat Server in the Servers tab.
  2. In a dropdown next to Runtime Environment:, select Apache Tomcat your version
  3. Click on save.

Now, you should be able to add to server on right click "Add and Remove".

Note: Additionally, when on clear/run, you get an error for multiple instances, open server.xml and ensure that it contains a single instance of each application and not multiple.

PHP - print all properties of an object

To get more information use this custom TO($someObject) function:

I wrote this simple function which not only displays the methods of a given object, but also shows its properties, encapsulation and some other useful information like release notes if given.

function TO($object){ //Test Object
                if(!is_object($object)){
                    throw new Exception("This is not a Object"); 
                    return;
                }
                if(class_exists(get_class($object), true)) echo "<pre>CLASS NAME = ".get_class($object);
                $reflection = new ReflectionClass(get_class($object));
                echo "<br />";
                echo $reflection->getDocComment();

                echo "<br />";

                $metody = $reflection->getMethods();
                foreach($metody as $key => $value){
                    echo "<br />". $value;
                }

                echo "<br />";

                $vars = $reflection->getProperties();
                foreach($vars as $key => $value){
                    echo "<br />". $value;
                }
                echo "</pre>";
            }

To show you how it works I will create now some random example class. Lets create class called Person and lets place some release notes just above the class declaration:

        /**
         * DocNotes -  This is description of this class if given else it will display false
         */
        class Person{
            private $name;
            private $dob;
            private $height;
            private $weight;
            private static $num;

            function __construct($dbo, $height, $weight, $name) {
                $this->dob = $dbo;
                $this->height = (integer)$height;
                $this->weight = (integer)$weight;
                $this->name = $name;
                self::$num++;

            }
            public function eat($var="", $sar=""){
                echo $var;
            }
            public function potrzeba($var =""){
                return $var;
            }
        }

Now lets create a instance of a Person and wrap it with our function.

    $Wictor = new Person("27.04.1987", 170, 70, "Wictor");
    TO($Wictor);

This will output information about the class name, parameters and methods including encapsulation information and the number of parameters, names of parameters for each method, method location and lines of code where it exists. See the output below:

CLASS NAME = Person
/**
             * DocNotes -  This is description of this class if given else it will display false
             */

Method [  public method __construct ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 75 - 82

  - Parameters [4] {
    Parameter #0 [  $dbo ]
    Parameter #1 [  $height ]
    Parameter #2 [  $weight ]
    Parameter #3 [  $name ]
  }
}

Method [  public method eat ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 83 - 85

  - Parameters [2] {
    Parameter #0 [  $var = '' ]
    Parameter #1 [  $sar = '' ]
  }
}

Method [  public method potrzeba ] {
  @@ C:\xampp\htdocs\www\kurs_php_zaawansowany\index.php 86 - 88

  - Parameters [1] {
    Parameter #0 [  $var = '' ]
  }
}


Property [  private $name ]

Property [  private $dob ]

Property [  private $height ]

Property [  private $weight ]

Property [ private static $num ]

Inserting data into a MySQL table using VB.NET

Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean

Private Sub Insert_Car()

Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"

Dim cmd = new MySqlCommand(sql, conn)

    cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
    cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
    cmd.Paramaters.AddwithValue("@model", txtModel.Text)
    cmd.Paramaters.AddwithValue("@color", txtColor.Text)
    cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
    cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
    cmd.Paramaters.AddwithValue("@code", txtCode.Text)

    Try
        conn.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            ireturn = True
        End If  
        conn.Close()


    Catch ex as Exception
        ireturn = False
        conn.Close()
    End Try

Return ireturn

End Sub

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

Add a default value to a column through a migration

Execute:

rails generate migration add_column_to_table column:boolean

It will generate this migration:

class AddColumnToTable < ActiveRecord::Migration
  def change
    add_column :table, :column, :boolean
  end
end

Set the default value adding :default => 1

add_column :table, :column, :boolean, :default => 1

Run:

rake db:migrate

How do I get the height and width of the Android Navigation Bar programmatically?

Actually the navigation bar on tablets (at least Nexus 7) has different size in portrait and landscape so this function should look like this:

private int getNavigationBarHeight(Context context, int orientation) {
    Resources resources = context.getResources();

    int id = resources.getIdentifier(
            orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",
            "dimen", "android");
    if (id > 0) {
        return resources.getDimensionPixelSize(id);
    }
    return 0;
}

findAll() in yii

If you use findAll(), I recommend you to use this:

$data_email = EmailArchive::model()->findAll(
                  array(
                      'condition' => 'email_id = :email_id',
                      'params'    => array(':email_id' => $id)
                  )
              );

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

MongoDB "root" user

I noticed a lot of these answers, use this command:

use admin

which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator":

> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "admin.administrator",
        "user" : "administrator",
        "db" : "admin",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

I emphasize "admin.administrator", for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:

development:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
      options:
        connect_timeout: 15
        retry_writes: false

This references the following environment variable:

export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'

Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".

So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:

$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' }  ] })
> db.getUsers()
[
    {
        "_id" : "mysite_development.administrator",
        "user" : "administrator",
        "db" : "mysite_development",
        "roles" : [
            {
                "role" : "root",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

Notice that the _id and db changed to reference the specific database my application depends on:

"_id" : "mysite_development.administrator",
"db" : "mysite_development",

After making this change, the error went away and I was able to connect to MongoDB fine inside my application.

Extra Notes:

In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:

db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])

There is also a db.updateUser command, albiet typically used to update the user password.

Installing jQuery?

There is no installation per se.

You download jQuery and include it in your html files like this:

<script src="jquery.js" type="text/javascript"></script>

Of course, modify the filename so that it's the same as the downloaded script file.

Done!

Why would you use String.Equals over ==?

Both methods do the same functionally - they compare values.
As is written on MSDN:

But if one of your string instances is null, these methods are working differently:

string x = null;
string y = "qq";
if (x == y) // returns false
    MessageBox.Show("true");
else
    MessageBox.Show("false");

if (x.Equals(y)) // returns System.NullReferenceException: Object reference not set to an instance of an object. - because x is null !!!
    MessageBox.Show("true");
else
    MessageBox.Show("false");

PHP output showing little black diamonds with a question mark

This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.

The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:

  • All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).
  • Your web-server is configured to serve files with charset=iso-8859-1
  • Alternatively, you can override the webservers settings from within the PHP-document, using header.
  • In addition, you may insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.
  • You may also specify the accept-charset attribute on your <form> elements.
  • Database tables are defined with encoding as latin1
  • The database connection between PHP to and database is set to latin1

If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.

A note on meta-tags, since everybody misunderstands what they are:

When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the Content-Type header, which specifies the mimetype of the file (Eg. text/html) as well as the encoding (aka charset). While most webservers will send a Content-Type header with charset info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with http-equiv="Content-Type". It's important to realise that the meta-tag is only interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.

This page has a very good explanation of these things.

Margin on child element moves parent element

An alternative solution I found before I knew the correct answer was to add a transparent border to the parent element.

Your box will use extra pixels though...

.parent {
    border:1px solid transparent;
}

SQL Error: ORA-00922: missing or invalid option

The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)

Generally, there is no benefit to declaring a column as CHAR(3) rather than VARCHAR2(3). Declaring a column as CHAR(3) doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3) and then add a CHECK constraint that LENGTH(takeoff_at) = 3.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)

Since both takeoff_at and destination are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight table and this new airport_code table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.

And from a naming convention standpoint, since both takeoff_at and destination are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code and arrival_airport_code, for example, would be much more meaningful.

'tsc command not found' in compiling typescript

You are all messing with the global installations and -path files. Just a little error might damage every project you have ever written, and you will spend the rest of the night trying to get a console.log('hi') to work again.

If you have run npm i typescript --save-dev in your project - just try to run:

npx tsc 

And see if it works before messing with global stuff (unless of course you really know what you are doing)

Use 'class' or 'typename' for template parameters?

In response to Mike B, I prefer to use 'class' as, within a template, 'typename' has an overloaded meaning, but 'class' does not. Take this checked integer type example:

template <class IntegerType>
class smart_integer {
public: 
    typedef integer_traits<Integer> traits;
    IntegerType operator+=(IntegerType value){
        typedef typename traits::larger_integer_t larger_t;
        larger_t interm = larger_t(myValue) + larger_t(value); 
        if(interm > traits::max() || interm < traits::min())
            throw overflow();
        myValue = IntegerType(interm);
    }
}

larger_integer_t is a dependent name, so it requires 'typename' to preceed it so that the parser can recognize that larger_integer_t is a type. class, on the otherhand, has no such overloaded meaning.

That... or I'm just lazy at heart. I type 'class' far more often than 'typename', and thus find it much easier to type. Or it could be a sign that I write too much OO code.

append to url and refresh page

this should work (not tested!)

var url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
}else{
   url += '?param=1'
}
window.location.href = url;

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

No need to uninstall it or going crazy with symbolic links, just use an alias. I faced the same problem when upgrading to python 3.7.1.
Just install the new python version using brew install python then in your .bash_profile create an alias pointing to the new python version; like this: alias python="/usr/local/bin/python3" then save and run source ~/.bash_profile.
Done.

Convert python datetime to timestamp in milliseconds

For those who searches for an answer without parsing and loosing milliseconds, given dt_obj is a datetime:

python3 only, elegant

int(dt_obj.timestamp() * 1000)

both python2 and python3 compatible:

import time

int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)