Programs & Examples On #Mdd

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

I had the same issues and i had dialogComponent in EntryComponents and it still did not work. this is how I was able to solve the problem. the link is here to a previously answered post:

https://stackoverflow.com/a/64224799/14385758

SQL Server date format yyyymmdd

You can do as follows:

Select Format(test.Time, 'yyyyMMdd')
From TableTest test

can not find module "@angular/material"

import {MatButtonModule} from '@angular/material/button';

Angular2 Material Dialog css, dialog size

sharing the latest on mat-dialog two ways of achieving this... 1) either you set the width and height during the open e.g.

let dialogRef = dialog.open(NwasNtdSelectorComponent, {
    data: {
        title: "NWAS NTD"
    },
    width: '600px',
    height: '600px',
    panelClass: 'epsSelectorPanel'
});

or 2) use the panelClass and style it accordingly.

1) is easiest but 2) is better and more configurable.

How to insert current datetime in postgresql insert query

You can of course format the result of current_timestamp(). Please have a look at the various formatting functions in the official documentation.

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

This error can come not only because of the Date conversions

This error can come when we try to pass date whereas varchar is expected
or
when we try to pass varchar whereas date is expected.

Use to_char(sysdate,'YYYY-MM-DD') when varchar is expected

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter definition, e.g.:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

One should set the optional fields if they will appear. And the rest of code should be exactly the same.

What is the final version of the ADT Bundle?

It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

How to Convert datetime value to yyyymmddhhmmss in SQL server?

Another option I have googled, but contains several replace ...

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

Android difference between Two Dates

You can generalize this into a function that lets you choose the output format

private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
    long restDatesinMillis = date1.getTime()-date2.getTime();
    Date restdate = new Date(restDatesinMillis);

    return format.format(restdate);
}

Now is a simple function call like this, difference in hours, minutes and seconds:

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

try {
    Date date1 = formater.parse(dateEnd);
    Date date2 = formater.parse(dateInit);

    String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));

    txtTime.setText(result);
} catch (ParseException e) {
    e.printStackTrace();
}

How to get correct timestamp in C#

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

Check if a string matches a regex in Bash script

A good way to test if a string is a correct date is to use the command date:

if date -d "${DATE}" >/dev/null 2>&1
then
  # do what you need to do with your date
else
  echo "${DATE} incorrect date" >&2
  exit 1
fi

from comment: one can use formatting

if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ] 

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

O/P:

20170115072120

With punctuation:

current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;

O/P:

2017-01-15 07:25:33

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

How to get 2 digit year w/ Javascript?

var currentYear =  (new Date()).getFullYear();   
var twoLastDigits = currentYear%100;

var formatedTwoLastDigits = "";

if (twoLastDigits <10 ) {
    formatedTwoLastDigits = "0" + twoLastDigits;
} else {
    formatedTwoLastDigits = "" + twoLastDigits;
}

How to read a CSV file from a URL with Python?

To increase performance when downloading a large file, the below may work a bit more efficiently:

import requests
from contextlib import closing
import csv

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
    for row in reader:
        # Handle each row here...
        print row   

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

how to re-format datetime string in php?

try this

$datetime = "20130409163705"; 
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));

the output:

[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5

How to Write text file Java

In java 7 can now do

try(BufferedWriter w = ....)
{
  w.write(...);
}
catch(IOException)
{
}

and w.close will be done automatically

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

How to convert String to Date value in SAS?

You don't need substr or strip.

input(monyy,date9.);

Convert YYYYMMDD to DATE

The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?

To find the values that are causing issues (so you (or whoever designed this table) can fix them):

SELECT GRADUATION_DATE FROM mydb
  WHERE ISDATE(GRADUATION_DATE) = 0;

Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.

ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;

Now you don't have to worry about the formatting - you can always format as YYYYMMDD or YYYY-MM-DD on the client, or using CONVERT in SQL. When you have a valid date as a string literal, you can use:

SELECT CONVERT(CHAR(10), '20120101', 120);

...but this is better done on the client (if at all).

There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

Using IF ELSE in Oracle

You can use Decode as well:

SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
      AND A.ITEM_KEY = b.item_key
      AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
                         and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item

Is java.sql.Timestamp timezone specific?

It is specific from your driver. You need to supply a parameter in your Java program to tell it the time zone you want to use.

java -Duser.timezone="America/New_York" GetCurrentDateTimeZone

Further this:

to_char(new_time(sched_start_time, 'CURRENT_TIMEZONE', 'NEW_TIMEZONE'), 'MM/DD/YY HH:MI AM')

May also be of value in handling the conversion properly. Taken from here

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Here is a bare bones version:

Let's say that you have a date in Cell A1 in the format you described. For example: 19760210.

Then this formula will give you the date you want:

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).

On my system (Excel 2010) it works with strings or floats.

Convert string to datetime in vb.net

As an alternative, if you put a space between the date and time, DateTime.Parse will recognize the format for you. That's about as simple as you can get it. (If ParseExact was still not being recognized)

How do I convert the date from one format to another date object in another format without using any deprecated classes?

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

             String fromDateFormat = "dd/MM/yyyy";
             String fromdate = 15/03/2018; //Take any date

             String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
             String dateStringFrom;

             Date DF = new Date();


              try
              {
                 //DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
                 DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
                 FromDF.setLenient(false);  // this is important!
                 Date FromDate = FromDF.parse(fromdate);
                 dateStringFrom = new 
                 SimpleDateFormat(CheckFormat).format(FromDate);
                 DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
                 DF=FromDF1.parse(dateStringFrom);
                 System.out.println(dateStringFrom);
              }
              catch(Exception ex)
              {

                  System.out.println("Date error");

              }

output:- 15/03/2018
         15 Mar 2018

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

In my case, I was getting this error message only in Production but not when run locally, even though my application's binaries were identical.

In my application, I'm using a custom DbModelStore so that the runtime-generated EDMX is saved to disk and loaded from disk on startup (instead of regenerating it from scratch) to reduce application startup time - and due to a bug in my code I wasn't invalidating the EDMX file on-disk - so Production was using an older version of the EDMX file from disk that referenced an older version of my application's types from before I renamed the type-name in the exception error message.

Deleting the cache file and restarting the application fixed it.

Get the difference between two dates both In Months and days in sql

The solution I post will consider a month with 30 days

  select CONCAT (CONCAT (num_months,' MONTHS '), CONCAT ((days-(num_months)*30),' DAYS '))
  from ( 
  SELECT floor(Months_between(To_date('20120325', 'YYYYMMDD'),
   To_date('20120101', 'YYYYMMDD')))
   num_months,
   ( To_date('20120325', 'YYYYMMDD') - To_date('20120101', 'YYYYMMDD') )
   days
  FROM   dual);

Convert string to date in bash

This worked for me :

date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'

then you can format output adding parameter '+%Y%m%d'

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

Recommended date format for REST GET API

Always use UTC:

For example I have a schedule component that takes in one parameter DATETIME. When I call this using a GET verb I use the following format where my incoming parameter name is scheduleDate.

Example:
https://localhost/api/getScheduleForDate?scheduleDate=2003-11-21T01:11:11Z

Change Placeholder Text using jQuery

If the input is inside the div than you can try this:

$('#div_id input').attr("placeholder", "placeholder text");

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

How to change Git log date formats

You can use the field truncation option to avoid quite so many %x08 characters. For example:

git log --pretty='format:%h %s%n\t%<(12,trunc)%ci%x08%x08, %an <%ae>'

is equivalent to:

git log --pretty='format:%h %s%n\t%ci%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08, %an <%ae>'

And quite a bit easier on the eyes.

Better still, for this particular example, using %cd will honor the --date=<format>, so if you want YYYY-MM-DD, you can do this and avoid %< and %x08 entirely:

git log --date=short --pretty='format:%h %s%n\t%cd, %an <%ae>'

I just noticed this was a bit circular with respect to the original post but I'll leave it in case others arrived here with the same search parameters I did.

Cannot drop database because it is currently in use

I wanted to call out that I used a script that is derived from two of the answers below.

Props to @Hitesh Mistry and @unruledboy

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'[[[DatabaseName]]]'

DECLARE @SQL varchar(max)

SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

EXEC(@SQL)

alter database [[[DatabaseName]]] set single_user with rollback immediate

DROP DATABASE [[[DatabaseName]]]

Return date as ddmmyyyy in SQL Server

SELECT REPLACE(CONVERT(VARCHAR(10), THEDATE, 103), '/', '') AS [DDMMYYYY]

As seen here: http://www.sql-server-helper.com/tips/date-formats.aspx

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

javascript date to string

Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

Get current time as formatted string in Go?

Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)

t := time.Now()
fmt.Println(t.Format("20060102150405"))

Online demo (with date fixed in the past in the playground, never mind)

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

Calculate age given the birth date in the format YYYYMMDD

see this example you get full year month day information from here

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    var da = today.getDate() - birthDate.getDate();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    if(m<0){
        m +=12;
    }
    if(da<0){
        da +=30;
    }
    return age+" years "+ Math.abs(m) + "months"+ Math.abs(da) + " days";
}
alert('age: ' + getAge("1987/08/31"));    
[http://jsfiddle.net/tapos00/2g70ue5y/][1]

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

From C# 6:

var dateTimeUtcAsString = $"{DateTime.UtcNow:o}";

The result will be: "2019-01-15T11:46:33.2752667Z"

Get String in YYYYMMDD format from JS date object?

I didn't like adding to the prototype. An alternative would be:

_x000D_
_x000D_
var rightNow = new Date();_x000D_
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");_x000D_
_x000D_
<!-- Next line is for code snippet output only -->_x000D_
document.body.innerHTML += res;
_x000D_
_x000D_
_x000D_

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

C# DateTime to "YYYYMMDDHHMMSS" format

You've practically written the format yourself.

yourdate.ToString("yyyyMMddHHmmss")

  • MM = two digit month
  • mm = two digit minutes
  • HH = two digit hour, 24 hour clock
  • hh = two digit hour, 12 hour clock

Everything else should be self-explanatory.

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

It means that one of the dependent dlls is compiled with a different run-time library.

Project -> Properties -> C/C++ -> Code Generation -> Runtime Library

Go over all the libraries and see that they are compiled in the same way.

More about this error in this link:

warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Java SimpleDateFormat for time zone with a colon separator?

Try setLenient(false).

Addendum: It looks like you're recognizing variously formatted Date strings. If you have to do entry, you might like looking at this example that extends InputVerifier.

How to format a DateTime in PowerShell

The question is answered, but there is some more information missing:

Variable vs. Cmdlet

You have a value in the $Date variable and the -f operator does work in this form: 'format string' -f values. If you call Get-Date -format "yyyyMMdd" you call a cmdlet with some parameters. The value "yyyyMMdd" is the value for parameter Format (try help Get-Date -param Format).

-f operator

There are plenty of format strings. Look at least at part1 and part2. She uses string.Format('format string', values'). Think of it as 'format-string' -f values, because the -f operator works very similarly as string.Format method (although there are some differences (for more information look at question at Stack Overflow: How exactly does the RHS of PowerShell's -f operator work?).

Formatting "yesterday's" date in python

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')

Convert varchar into datetime in SQL Server

DECLARE @d char(8)
SET @d = '06082020'    /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (@d AS INT), '##/##/####') as DATETIME)

Result returned is the original date string in @d as a DateTime.

How to decrypt an encrypted Apple iTunes iPhone backup?

Security researchers Jean-Baptiste Bédrune and Jean Sigwald presented how to do this at Hack-in-the-box Amsterdam 2011.

Since then, Apple has released an iOS Security Whitepaper with more details about keys and algorithms, and Charlie Miller et al. have released the iOS Hacker’s Handbook, which covers some of the same ground in a how-to fashion. When iOS 10 first came out there were changes to the backup format which Apple did not publicize at first, but various people reverse-engineered the format changes.

Encrypted backups are great

The great thing about encrypted iPhone backups is that they contain things like WiFi passwords that aren’t in regular unencrypted backups. As discussed in the iOS Security Whitepaper, encrypted backups are considered more “secure,” so Apple considers it ok to include more sensitive information in them.

An important warning: obviously, decrypting your iOS device’s backup removes its encryption. To protect your privacy and security, you should only run these scripts on a machine with full-disk encryption. While it is possible for a security expert to write software that protects keys in memory, e.g. by using functions like VirtualLock() and SecureZeroMemory() among many other things, these Python scripts will store your encryption keys and passwords in strings to be garbage-collected by Python. This means your secret keys and passwords will live in RAM for a while, from whence they will leak into your swap file and onto your disk, where an adversary can recover them. This completely defeats the point of having an encrypted backup.

How to decrypt backups: in theory

The iOS Security Whitepaper explains the fundamental concepts of per-file keys, protection classes, protection class keys, and keybags better than I can. If you’re not already familiar with these, take a few minutes to read the relevant parts.

Now you know that every file in iOS is encrypted with its own random per-file encryption key, belongs to a protection class, and the per-file encryption keys are stored in the filesystem metadata, wrapped in the protection class key.

To decrypt:

  1. Decode the keybag stored in the BackupKeyBag entry of Manifest.plist. A high-level overview of this structure is given in the whitepaper. The iPhone Wiki describes the binary format: a 4-byte string type field, a 4-byte big-endian length field, and then the value itself.

    The important values are the PBKDF2 ITERations and SALT, the double protection salt DPSL and iteration count DPIC, and then for each protection CLS, the WPKY wrapped key.

  2. Using the backup password derive a 32-byte key using the correct PBKDF2 salt and number of iterations. First use a SHA256 round with DPSL and DPIC, then a SHA1 round with ITER and SALT.

    Unwrap each wrapped key according to RFC 3394.

  3. Decrypt the manifest database by pulling the 4-byte protection class and longer key from the ManifestKey in Manifest.plist, and unwrapping it. You now have a SQLite database with all file metadata.

  4. For each file of interest, get the class-encrypted per-file encryption key and protection class code by looking in the Files.file database column for a binary plist containing EncryptionKey and ProtectionClass entries. Strip the initial four-byte length tag from EncryptionKey before using.

    Then, derive the final decryption key by unwrapping it with the class key that was unwrapped with the backup password. Then decrypt the file using AES in CBC mode with a zero IV.

How to decrypt backups: in practice

First you’ll need some library dependencies. If you’re on a mac using a homebrew-installed Python 2.7 or 3.7, you can install the dependencies with:

CFLAGS="-I$(brew --prefix)/opt/openssl/include" \
LDFLAGS="-L$(brew --prefix)/opt/openssl/lib" \    
    pip install biplist fastpbkdf2 pycrypto

In runnable source code form, here is how to decrypt a single preferences file from an encrypted iPhone backup:

#!/usr/bin/env python3.7
# coding: UTF-8

from __future__ import print_function
from __future__ import division

import argparse
import getpass
import os.path
import pprint
import random
import shutil
import sqlite3
import string
import struct
import tempfile
from binascii import hexlify

import Crypto.Cipher.AES # https://www.dlitz.net/software/pycrypto/
import biplist
import fastpbkdf2
from biplist import InvalidPlistException


def main():
    ## Parse options
    parser = argparse.ArgumentParser()
    parser.add_argument('--backup-directory', dest='backup_directory',
                    default='testdata/encrypted')
    parser.add_argument('--password-pipe', dest='password_pipe',
                        help="""\
Keeps password from being visible in system process list.
Typical use: --password-pipe=<(echo -n foo)
""")
    parser.add_argument('--no-anonymize-output', dest='anonymize',
                        action='store_false')
    args = parser.parse_args()
    global ANONYMIZE_OUTPUT
    ANONYMIZE_OUTPUT = args.anonymize
    if ANONYMIZE_OUTPUT:
        print('Warning: All output keys are FAKE to protect your privacy')

    manifest_file = os.path.join(args.backup_directory, 'Manifest.plist')
    with open(manifest_file, 'rb') as infile:
        manifest_plist = biplist.readPlist(infile)
    keybag = Keybag(manifest_plist['BackupKeyBag'])
    # the actual keys are unknown, but the wrapped keys are known
    keybag.printClassKeys()

    if args.password_pipe:
        password = readpipe(args.password_pipe)
        if password.endswith(b'\n'):
            password = password[:-1]
    else:
        password = getpass.getpass('Backup password: ').encode('utf-8')

    ## Unlock keybag with password
    if not keybag.unlockWithPasscode(password):
        raise Exception('Could not unlock keybag; bad password?')
    # now the keys are known too
    keybag.printClassKeys()

    ## Decrypt metadata DB
    manifest_key = manifest_plist['ManifestKey'][4:]
    with open(os.path.join(args.backup_directory, 'Manifest.db'), 'rb') as db:
        encrypted_db = db.read()

    manifest_class = struct.unpack('<l', manifest_plist['ManifestKey'][:4])[0]
    key = keybag.unwrapKeyForClass(manifest_class, manifest_key)
    decrypted_data = AESdecryptCBC(encrypted_db, key)

    temp_dir = tempfile.mkdtemp()
    try:
        # Does anyone know how to get Python’s SQLite module to open some
        # bytes in memory as a database?
        db_filename = os.path.join(temp_dir, 'db.sqlite3')
        with open(db_filename, 'wb') as db_file:
            db_file.write(decrypted_data)
        conn = sqlite3.connect(db_filename)
        conn.row_factory = sqlite3.Row
        c = conn.cursor()
        # c.execute("select * from Files limit 1");
        # r = c.fetchone()
        c.execute("""
            SELECT fileID, domain, relativePath, file
            FROM Files
            WHERE relativePath LIKE 'Media/PhotoData/MISC/DCIM_APPLE.plist'
            ORDER BY domain, relativePath""")
        results = c.fetchall()
    finally:
        shutil.rmtree(temp_dir)

    for item in results:
        fileID, domain, relativePath, file_bplist = item

        plist = biplist.readPlistFromString(file_bplist)
        file_data = plist['$objects'][plist['$top']['root'].integer]
        size = file_data['Size']

        protection_class = file_data['ProtectionClass']
        encryption_key = plist['$objects'][
            file_data['EncryptionKey'].integer]['NS.data'][4:]

        backup_filename = os.path.join(args.backup_directory,
                                    fileID[:2], fileID)
        with open(backup_filename, 'rb') as infile:
            data = infile.read()
            key = keybag.unwrapKeyForClass(protection_class, encryption_key)
            # truncate to actual length, as encryption may introduce padding
            decrypted_data = AESdecryptCBC(data, key)[:size]

        print('== decrypted data:')
        print(wrap(decrypted_data))
        print()

        print('== pretty-printed plist')
        pprint.pprint(biplist.readPlistFromString(decrypted_data))

##
# this section is mostly copied from parts of iphone-dataprotection
# http://code.google.com/p/iphone-dataprotection/

CLASSKEY_TAGS = [b"CLAS",b"WRAP",b"WPKY", b"KTYP", b"PBKY"]  #UUID
KEYBAG_TYPES = ["System", "Backup", "Escrow", "OTA (icloud)"]
KEY_TYPES = ["AES", "Curve25519"]
PROTECTION_CLASSES={
    1:"NSFileProtectionComplete",
    2:"NSFileProtectionCompleteUnlessOpen",
    3:"NSFileProtectionCompleteUntilFirstUserAuthentication",
    4:"NSFileProtectionNone",
    5:"NSFileProtectionRecovery?",

    6: "kSecAttrAccessibleWhenUnlocked",
    7: "kSecAttrAccessibleAfterFirstUnlock",
    8: "kSecAttrAccessibleAlways",
    9: "kSecAttrAccessibleWhenUnlockedThisDeviceOnly",
    10: "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly",
    11: "kSecAttrAccessibleAlwaysThisDeviceOnly"
}
WRAP_DEVICE = 1
WRAP_PASSCODE = 2

class Keybag(object):
    def __init__(self, data):
        self.type = None
        self.uuid = None
        self.wrap = None
        self.deviceKey = None
        self.attrs = {}
        self.classKeys = {}
        self.KeyBagKeys = None #DATASIGN blob
        self.parseBinaryBlob(data)

    def parseBinaryBlob(self, data):
        currentClassKey = None

        for tag, data in loopTLVBlocks(data):
            if len(data) == 4:
                data = struct.unpack(">L", data)[0]
            if tag == b"TYPE":
                self.type = data
                if self.type > 3:
                    print("FAIL: keybag type > 3 : %d" % self.type)
            elif tag == b"UUID" and self.uuid is None:
                self.uuid = data
            elif tag == b"WRAP" and self.wrap is None:
                self.wrap = data
            elif tag == b"UUID":
                if currentClassKey:
                    self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey
                currentClassKey = {b"UUID": data}
            elif tag in CLASSKEY_TAGS:
                currentClassKey[tag] = data
            else:
                self.attrs[tag] = data
        if currentClassKey:
            self.classKeys[currentClassKey[b"CLAS"]] = currentClassKey

    def unlockWithPasscode(self, passcode):
        passcode1 = fastpbkdf2.pbkdf2_hmac('sha256', passcode,
                                        self.attrs[b"DPSL"],
                                        self.attrs[b"DPIC"], 32)
        passcode_key = fastpbkdf2.pbkdf2_hmac('sha1', passcode1,
                                            self.attrs[b"SALT"],
                                            self.attrs[b"ITER"], 32)
        print('== Passcode key')
        print(anonymize(hexlify(passcode_key)))
        for classkey in self.classKeys.values():
            if b"WPKY" not in classkey:
                continue
            k = classkey[b"WPKY"]
            if classkey[b"WRAP"] & WRAP_PASSCODE:
                k = AESUnwrap(passcode_key, classkey[b"WPKY"])
                if not k:
                    return False
                classkey[b"KEY"] = k
        return True

    def unwrapKeyForClass(self, protection_class, persistent_key):
        ck = self.classKeys[protection_class][b"KEY"]
        if len(persistent_key) != 0x28:
            raise Exception("Invalid key length")
        return AESUnwrap(ck, persistent_key)

    def printClassKeys(self):
        print("== Keybag")
        print("Keybag type: %s keybag (%d)" % (KEYBAG_TYPES[self.type], self.type))
        print("Keybag version: %d" % self.attrs[b"VERS"])
        print("Keybag UUID: %s" % anonymize(hexlify(self.uuid)))
        print("-"*209)
        print("".join(["Class".ljust(53),
                    "WRAP".ljust(5),
                    "Type".ljust(11),
                    "Key".ljust(65),
                    "WPKY".ljust(65),
                    "Public key"]))
        print("-"*208)
        for k, ck in self.classKeys.items():
            if k == 6:print("")

            print("".join(
                [PROTECTION_CLASSES.get(k).ljust(53),
                str(ck.get(b"WRAP","")).ljust(5),
                KEY_TYPES[ck.get(b"KTYP",0)].ljust(11),
                anonymize(hexlify(ck.get(b"KEY", b""))).ljust(65),
                anonymize(hexlify(ck.get(b"WPKY", b""))).ljust(65),
            ]))
        print()

def loopTLVBlocks(blob):
    i = 0
    while i + 8 <= len(blob):
        tag = blob[i:i+4]
        length = struct.unpack(">L",blob[i+4:i+8])[0]
        data = blob[i+8:i+8+length]
        yield (tag,data)
        i += 8 + length

def unpack64bit(s):
    return struct.unpack(">Q",s)[0]
def pack64bit(s):
    return struct.pack(">Q",s)

def AESUnwrap(kek, wrapped):
    C = []
    for i in range(len(wrapped)//8):
        C.append(unpack64bit(wrapped[i*8:i*8+8]))
    n = len(C) - 1
    R = [0] * (n+1)
    A = C[0]

    for i in range(1,n+1):
        R[i] = C[i]

    for j in reversed(range(0,6)):
        for i in reversed(range(1,n+1)):
            todec = pack64bit(A ^ (n*j+i))
            todec += pack64bit(R[i])
            B = Crypto.Cipher.AES.new(kek).decrypt(todec)
            A = unpack64bit(B[:8])
            R[i] = unpack64bit(B[8:])

    if A != 0xa6a6a6a6a6a6a6a6:
        return None
    res = b"".join(map(pack64bit, R[1:]))
    return res

ZEROIV = "\x00"*16
def AESdecryptCBC(data, key, iv=ZEROIV, padding=False):
    if len(data) % 16:
        print("AESdecryptCBC: data length not /16, truncating")
        data = data[0:(len(data)/16) * 16]
    data = Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_CBC, iv).decrypt(data)
    if padding:
        return removePadding(16, data)
    return data

##
# here are some utility functions, one making sure I don’t leak my
# secret keys when posting the output on Stack Exchange

anon_random = random.Random(0)
memo = {}
def anonymize(s):
    if type(s) == str:
        s = s.encode('utf-8')
    global anon_random, memo
    if ANONYMIZE_OUTPUT:
        if s in memo:
            return memo[s]
        possible_alphabets = [
            string.digits,
            string.digits + 'abcdef',
            string.ascii_letters,
            "".join(chr(x) for x in range(0, 256)),
        ]
        for a in possible_alphabets:
            if all((chr(c) if type(c) == int else c) in a for c in s):
                alphabet = a
                break
        ret = "".join([anon_random.choice(alphabet) for i in range(len(s))])
        memo[s] = ret
        return ret
    else:
        return s

def wrap(s, width=78):
    "Return a width-wrapped repr(s)-like string without breaking on \’s"
    s = repr(s)
    quote = s[0]
    s = s[1:-1]
    ret = []
    while len(s):
        i = s.rfind('\\', 0, width)
        if i <= width - 4: # "\x??" is four characters
            i = width
        ret.append(s[:i])
        s = s[i:]
    return '\n'.join("%s%s%s" % (quote, line ,quote) for line in ret)

def readpipe(path):
    if stat.S_ISFIFO(os.stat(path).st_mode):
        with open(path, 'rb') as pipe:
            return pipe.read()
    else:
        raise Exception("Not a pipe: {!r}".format(path))

if __name__ == '__main__':
    main()

Which then prints this output:

Warning: All output keys are FAKE to protect your privacy
== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES                                                                         4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES                                                                         09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES                                                                         e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES                                                                         902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES                                                                         a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES                                                                         09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES                                                                         0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES                                                                         b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES                                                                         417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES                                                                         b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES                                                                         9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== Passcode key
ee34f5bb635830d698074b1e3e268059c590973b0f1138f1954a2a4e1069e612

== Keybag
Keybag type: Backup keybag (1)
Keybag version: 3
Keybag UUID: dc6486c479e84c94efce4bea7169ef7d
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Class                                                WRAP Type       Key                                                              WPKY                                                             Public key
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NSFileProtectionComplete                             2    AES        64e8fc94a7b670b0a9c4a385ff395fe9ba5ee5b0d9f5a5c9f0202ef7fdcb386f 4c80b6da07d35d393fc7158e18b8d8f9979694329a71ceedee86b4cde9f97afec197ad3b13c5d12b
NSFileProtectionCompleteUnlessOpen                   2    AES        22a218c9c446fbf88f3ccdc2ae95f869c308faaa7b3e4fe17b78cbf2eeaf4ec9 09e8a0a9965f00f213ce06143a52801f35bde2af0ad54972769845d480b5043f545fa9b66a0353a6
NSFileProtectionCompleteUntilFirstUserAuthentication 2    AES        1004c6ca6e07d2b507809503180edf5efc4a9640227ac0d08baf5918d34b44ef e966b6a0742878ce747cec3fa1bf6a53b0d811ad4f1d6147cd28a5d400a8ffe0bbabea5839025cb5
NSFileProtectionNone                                 2    AES        2e809a0cd1a73725a788d5d1657d8fd150b0e360460cb5d105eca9c60c365152 902f46847302816561e7df57b64beea6fa11b0068779a65f4c651dbe7a1630f323682ff26ae7e577
NSFileProtectionRecovery?                            3    AES        9a078d710dcd4a1d5f70ea4062822ea3e9f7ea034233e7e290e06cf0d80c19ca a3935fed024cd9bc11d0300d522af8e89accfbe389d7c69dca02841df46c0a24d0067dba2f696072

kSecAttrAccessibleWhenUnlocked                       2    AES        606e5328816af66736a69dfe5097305cf1e0b06d6eb92569f48e5acac3f294a4 09a1856c7e97a51a9c2ecedac8c3c7c7c10e7efa931decb64169ee61cb07a0efb115050fd1e33af1
kSecAttrAccessibleAfterFirstUnlock                   2    AES        6a4b5292661bac882338d5ebb51fd6de585befb4ef5f8ffda209be8ba3af1b96 0509d215f2f574efa2f192efc53c460201168b26a175f066b5347fc48bc76c637e27a730b904ca82
kSecAttrAccessibleAlways                             2    AES        c0ed717947ce8d1de2dde893b6026e9ee1958771d7a7282dd2116f84312c2dd2 b7ac3c4f1e04896144ce90c4583e26489a86a6cc45a2b692a5767b5a04b0907e081daba009fdbb3c
kSecAttrAccessibleWhenUnlockedThisDeviceOnly         3    AES        80d8c7be8d5103d437f8519356c3eb7e562c687a5e656cfd747532f71668ff99 417526e67b82e7c6c633f9063120a299b84e57a8ffee97b34020a2caf6e751ec5750053833ab4d45
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly     3    AES        a875a15e3ff901351c5306019e3b30ed123e6c66c949bdaa91fb4b9a69a3811e b0e17b0cf7111c6e716cd0272de5684834798431c1b34bab8d1a1b5aba3d38a3a42c859026f81ccc
kSecAttrAccessibleAlwaysThisDeviceOnly               3    AES        1e7756695d337e0b06c764734a9ef8148af20dcc7a636ccfea8b2eb96a9e9373 9b3bdc59ae1d85703aa7f75d49bdc600bf57ba4a458b20a003a10f6e36525fb6648ba70e6602d8b2

== decrypted data:
'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD '
'PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist versi'
'on="1.0">\n<dict>\n\t<key>DCIMLastDirectoryNumber</key>\n\t<integer>100</integ'
'er>\n\t<key>DCIMLastFileNumber</key>\n\t<integer>3</integer>\n</dict>\n</plist'
'>\n'

== pretty-printed plist
{'DCIMLastDirectoryNumber': 100, 'DCIMLastFileNumber': 3}

Extra credit

The iphone-dataprotection code posted by Bédrune and Sigwald can decrypt the keychain from a backup, including fun things like saved wifi and website passwords:

$ python iphone-dataprotection/python_scripts/keychain_tool.py ...

--------------------------------------------------------------------------------------
|                              Passwords                                             |
--------------------------------------------------------------------------------------
|Service           |Account          |Data           |Access group  |Protection class|
--------------------------------------------------------------------------------------
|AirPort           |Ed’s Coffee Shop |<3FrenchRoast  |apple         |AfterFirstUnlock|
...

That code no longer works on backups from phones using the latest iOS, but there are some golang ports that have been kept up to date allowing access to the keychain.

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

How to select and change value of table cell with jQuery?

Using eq() you can target the third cell in the table:

$('#table_header td').eq(2).html('new content');

If you wanted to target every third cell in each row, use the nth-child-selector:

$('#table_header td:nth-child(3)').html('new content');

PHP substring extraction. Get the string before the first '/' or the whole string

You could create a helper function to take care of that:

/**
 * Return string before needle if it exists.
 *
 * @param string $str
 * @param mixed $needle
 * @return string
 */
function str_before($str, $needle)
{
    $pos = strpos($str, $needle);

    return ($pos !== false) ? substr($str, 0, $pos) : $str;
}

Here's a use case:

$sing = 'My name is Luka. I live on the second floor.';

echo str_before($sing, '.'); // My name is Luka

How can I find a specific element in a List<T>?

public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));

Angular and debounce

It could be implemented as Directive

import { Directive, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { NgControl } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[ngModel][onDebounce]',
})
export class DebounceDirective implements OnInit, OnDestroy {
  @Output()
  public onDebounce = new EventEmitter<any>();

  @Input('debounce')
  public debounceTime: number = 300;

  private isFirstChange: boolean = true;
  private subscription: Subscription;

  constructor(public model: NgControl) {
  }

  ngOnInit() {
    this.subscription =
      this.model.valueChanges
        .debounceTime(this.debounceTime)
        .distinctUntilChanged()
        .subscribe(modelValue => {
          if (this.isFirstChange) {
            this.isFirstChange = false;
          } else {
            this.onDebounce.emit(modelValue);
          }
        });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}

use it like

<input [(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)">

component sample

import { Component } from "@angular/core";

@Component({
  selector: 'app-sample',
  template: `
<input[(ngModel)]="value" (onDebounce)="doSomethingWhenModelIsChanged($event)">
<input[(ngModel)]="value" (onDebounce)="asyncDoSomethingWhenModelIsChanged($event)">
`
})
export class SampleComponent {
  value: string;

  doSomethingWhenModelIsChanged(value: string): void {
    console.log({ value });
  }

  async asyncDoSomethingWhenModelIsChanged(value: string): Promise<void> {
    return new Promise<void>(resolve => {
      setTimeout(() => {
        console.log('async', { value });
        resolve();
      }, 1000);
    });
  }
} 

How to quit a java app from within the program

This should do it in the correct way:

mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowListener() {

@Override
public void windowClosing(WindowEvent e) {
    if (doQuestion("Really want to exit?")) {
      mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainFrame.dispose();
    }
}

How do I unbind "hover" in jQuery?

Another solution is .die() for events who that attached with .live().

Ex.:

// attach click event for <a> tags
$('a').live('click', function(){});

// deattach click event from <a> tags
$('a').die('click');

You can find a good refference here: Exploring jQuery .live() and .die()

( Sorry for my english :"> )

How do I do a HTTP GET in Java?

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

Check if Python Package is installed

If you mean a python script, just do something like this:

Python 3.3+ use sys.modules and find_spec:

import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

Python 3:

try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

Python 2:

try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

What's a clean way to stop mongod on Mac OS X?

If the service is running via brew, you can stop it using the following command:

brew services stop mongodb

How to force garbage collector to run?

Since I'm too low reputation to comment, I will post this as an answer since it saved me after hours of struggeling and it may help somebody else:

As most people state GC.Collect(); is NOT recommended to do this normally, except in edge cases. As an example of this running garbage collection was exactly the solution to my scenario.

My program runs a long running operation on a file in a thread and afterwards deletes the file from the main thread. However: when the file operation throws an exception .NET does NOT release the filelock until the garbage is actually collected, EVEN when the long running task is encapsulated in a using statement. Therefore the program has to force garbage collection before attempting to delete the file.

In code:

        var returnvalue = 0;
        using (var t = Task.Run(() => TheTask(args, returnvalue)))
        {
            //TheTask() opens a file and then throws an exception. The exception itself is handled within the task so it does return a result (the errorcode)
            returnvalue = t.Result;
        }
        //Even though at this point the Thread is closed the file is not released untill garbage is collected
        System.GC.Collect();
        DeleteLockedFile();

How to store decimal values in SQL Server?

request.input("name", sql.Decimal, 155.33)              // decimal(18, 0)
request.input("name", sql.Decimal(10), 155.33)          // decimal(10, 0)
request.input("name", sql.Decimal(10, 2), 155.33)       // decimal(10, 2)

How to create a directory if it doesn't exist using Node.js?

I had to create sub-directories if they didn't exist. I used this:

const path = require('path');
const fs = require('fs');

function ensureDirectoryExists(p) {
    //console.log(ensureDirectoryExists.name, {p});
    const d = path.dirname(p);
    if (d && d !== p) {
        ensureDirectoryExists(d);
    }
    if (!fs.existsSync(d)) {
        fs.mkdirSync(d);
    }
}

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

android:drawableLeft margin and/or padding

<TextView
    android:layout_width="wrap_content"
    android:layout_height="32dp"
    android:background="@drawable/a"
    android:drawableLeft="@drawable/concern_black"
    android:gravity="center"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:drawablePadding="10dp"
    android:text="text"/>

note: layout_width needs to be wrap_content and use paddingLeft paddingRight drawablePadding to control gap. If you specify layout_width value is will has gap between icon and text, I think once give the layout_width a specify value, the padding will measure.

Install NuGet via PowerShell script

This also seems to do it. PS Example:

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

show all tags in git log

git log --no-walk --tags --pretty="%h %d %s" --decorate=full

This version will print the commit message as well:

 $ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f  (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762  (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998  (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484  (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7  (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b  (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe  (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1  (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.

PHP error: Notice: Undefined index:

I did define all the variables that was the first thing I checked. I know it's not required in PHP, but old habits die hard. Then I sanatized the info like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name1"])) {
    $name1Err = " First Name is a required field.";
  } else {
      $name1 = test_input($_POST["name1"]);
    // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]*$/",$name1)) {
      $name1Err = "Only letters and white space allowed";

of course test_input is another function that does a trim, strilashes, and htmlspecialchars. I think the input is pretty well sanitized. Not trying to be rude just showing what I did. When it came to the email I also checked to see if it was the proper format. I think the real answer is in the fact that some variables are local and some are global. I have got it working without errors for now so, while I'm extremely busy right now I'll accept shutting off errors as my answer. Don't worry I'll figure it out it's just not vitally important right now!

Keyboard shortcut to comment lines in Sublime Text 3

On OSX Yosemite, I fixed this by going System Preferences, Keyboard, then Shortcuts. Under App Shortcuts, disable Show Help menu which was bound to CMD+SHIFT+7.

keyboard settings

My keyboard layout is Norwegian, with English as the OS language.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to get Android application id?

To track installations, you could for example use a UUID as an identifier, and simply create a new one the first time an app runs after installation. Here is a sketch of a class named “Installation” with one static method Installation.id(Context context). You could imagine writing more installation-specific data into the INSTALLATION file.

public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {

    if (sID == null) {  
       File installation = new File(context.getFilesDir(), INSTALLATION);
       try {
           if (!installation.exists())
               writeInstallationFile(installation);
           sID = readInstallationFile(installation);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
    }
   return sID;
}

private static String readInstallationFile(File installation) throws IOException {
   RandomAccessFile f = new RandomAccessFile(installation, "r");
   byte[] bytes = new byte[(int) f.length()];
   f.readFully(bytes);
   f.close();
   return new String(bytes);
}

private static void writeInstallationFile(File installation) throws IOException {
   FileOutputStream out = new FileOutputStream(installation);
   String id = UUID.randomUUID().toString();
   out.write(id.getBytes());
   out.close();
}

}

Yon can see more at https://github.com/MShoaibAkram/Android-Unique-Application-ID

Where is SQLite database stored on disk?

A SQLite database is a regular file. It is created in your script current directory.

How to go back (ctrl+z) in vi/vim

On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.

How can I label points in this scatterplot?

I have tried directlabels package for putting text labels. In the case of scatter plots it's not still perfect, but much better than manually adjusting the positions, specially in the cases that you are preparing the draft plots and not the final one - so you need to change and make plot again and again -.

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

How to use format() on a moment.js duration?

How about native javascript?

var formatTime = function(integer) {
    if(integer < 10) {
        return "0" + integer; 
    } else {
        return integer;
    }
}

function getDuration(ms) {
    var s1 = Math.floor(ms/1000);
    var s2 = s1%60;
    var m1 = Math.floor(s1/60);
    var m2 = m1%60;
    var h1 = Math.floor(m1/60);
    var string = formatTime(h1) +":" + formatTime(m2) + ":" + formatTime(s2);
    return string;
}

What is the most compatible way to install python modules on a Mac?

Please see Python OS X development environment. The best way is to use MacPorts. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:

sudo port install python26 python_select
sudo port select --set python python26

OR

sudo port install python30 python_select
sudo port select --set python python30

Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:

sudo port install py26-packagename

OR

sudo port install py30-packagename

In the above commands, replace packagename with the name of the package, for example:

sudo port install py26-setuptools

These commands will automatically install the package (and its dependencies) for the given Python version.

For a full list of available packages for Python, type:

port list | grep py26-

OR

port list | grep py30-

Which command you use depends on which version of Python you chose to install.

What is the difference between printf() and puts() in C?

puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.

Create instance of generic type in Java?

Here's an implementation of createContents that uses TypeTools to resolve the raw class represented by E:

E createContents() throws Exception {
  return TypeTools.resolveRawArgument(SomeContainer.class, getClass()).newInstance();
}

This approach only works if SomeContainer is subclassed so the actual value of E is captured in a type definition:

class SomeStringContainer extends SomeContainer<String>

Otherwise the value of E is erased at runtime and is not recoverable.

How do I split a string so I can access item x?

I've been using vzczc's answer using recursive cte's for some time, but have wanted to update it to handle a variable length separator and also to handle strings with leading and lagging "separators" such as when you have a csv file with records such as:

"Bob","Smith","Sunnyvale","CA"

or when you are dealing with six part fqn's as shown below. I use these extensively for logging of the subject_fqn for auditing, error handling, etc. and parsename only handles four parts:

[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]

Here is my updated version, and thanks to vzczc's for his original post!

select * from [utility].[split_string](N'"this"."string"."gets"."split"."and"."removes"."leading"."and"."trailing"."quotes"', N'"."', N'"', N'"');

select * from [utility].[split_string](N'"this"."string"."gets"."split"."but"."leaves"."leading"."and"."trailing"."quotes"', N'"."', null, null);

select * from [utility].[split_string](N'[netbios_name].[machine_name].[instance].[database].[schema].[table].[column]', N'].[', N'[', N']');

create function [utility].[split_string] ( 
  @input       [nvarchar](max) 
  , @separator [sysname] 
  , @lead      [sysname] 
  , @lag       [sysname]) 
returns @node_list table ( 
  [index]  [int] 
  , [node] [nvarchar](max)) 
  begin 
      declare @separator_length [int]= len(@separator) 
              , @lead_length    [int] = isnull(len(@lead), 0) 
              , @lag_length     [int] = isnull(len(@lag), 0); 
      -- 
      set @input = right(@input, len(@input) - @lead_length); 
      set @input = left(@input, len(@input) - @lag_length); 
      -- 
      with [splitter]([index], [starting_position], [start_location]) 
           as (select cast(@separator_length as [bigint]) 
                      , cast(1 as [bigint]) 
                      , charindex(@separator, @input) 
               union all 
               select [index] + 1 
                      , [start_location] + @separator_length 
                      , charindex(@separator, @input, [start_location] + @separator_length) 
               from   [splitter] 
               where  [start_location] > 0) 
      -- 
      insert into @node_list 
                  ([index],[node]) 
        select [index] - @separator_length                   as [index] 
               , substring(@input, [starting_position], case 
                                                            when [start_location] > 0 
                                                                then 
                                                              [start_location] - [starting_position] 
                                                            else 
                                                              len(@input) 
                                                        end) as [node] 
        from   [splitter]; 
      -- 
      return; 
  end; 
go 

How to normalize a histogram in MATLAB?

There is an excellent three part guide for Histogram Adjustments in MATLAB (broken original link, archive.org link), the first part is on Histogram Stretching.

internet explorer 10 - how to apply grayscale filter?

Inline SVG can be used in IE 10 and 11 and Edge 12.

I've created a project called gray which includes a polyfill for these browsers. The polyfill switches out <img> tags with inline SVG: https://github.com/karlhorky/gray

To implement, the short version is to download the jQuery plugin at the GitHub link above and add after jQuery at the end of your body:

<script src="/js/jquery.gray.min.js"></script>

Then every image with the class grayscale will appear as gray.

<img src="/img/color.jpg" class="grayscale">

You can see a demo too if you like.

How to display a list inline using Twitter's Bootstrap

To complete Raymond's answer

Bootstrap 2.3.2

<ul class="inline">
  <li>...</li>
</ul>

Bootstrap 3

<ul class="list-inline">
  <li>...</li>
</ul>

Bootstrap 4

<ul class="list-inline">
  <li class="list-inline-item">Lorem ipsum</li>
  <li class="list-inline-item">Phasellus iaculis</li>
  <li class="list-inline-item">Nulla volutpat</li>
</ul>

source: http://v4-alpha.getbootstrap.com/content/typography/#inline

How to use ESLint with Jest

Add environment only for __tests__ folder

You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:

extends: <relative_path to .eslintrc>
env:
    jest: true

If you have only one __tests__folder, this solution is the best since it scope jest environment only where it is needed.

Dealing with many test folders

If you have more test folders (OPs case), I'd still suggest to add those files. And if you have tons of those folders can add them with a simple zsh script:

#!/usr/bin/env zsh

for folder in **/__tests__/ ;do
    count=$(($(tr -cd '/' <<< $folder | wc -c)))
    echo $folder : $count
    cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
    jest: true
EOF
done

This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above. This script has to be launched within the folder containing your parent .eslintrc.

Calling javascript function in iframe

When you access resultFrame through document.all it only pulls it as an HTML element, not a window frame. You get the same issue if you have a frame fire an event using a "this" self-reference.

Replace:

document.all.resultFrame.Reset();

With:

window.frames.resultFrame.Reset();

Or:

document.all.resultFrame.contentWindow.Reset();

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

This worked for me ....

#include <stdio.h>
#include <time.h>   /* Needed for struct timespec */


int nsleep(long miliseconds)
{
   struct timespec req, rem;

   if(miliseconds > 999)
   {   
        req.tv_sec = (int)(miliseconds / 1000);                            /* Must be Non-Negative */
        req.tv_nsec = (miliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */
   }   
   else
   {   
        req.tv_sec = 0;                         /* Must be Non-Negative */
        req.tv_nsec = miliseconds * 1000000;    /* Must be in range of 0 to 999999999 */
   }   

   return nanosleep(&req , &rem);
}

int main()
{
   int ret = nsleep(2500);
   printf("sleep result %d\n",ret);
   return 0;
}

Lombok annotations do not compile under Intellij idea

If you're using Intellij on Mac, this setup finally worked for me.

Installations: Intellij

  1. Go to Preferences, search for Plugins.
  2. Type "Lombok" in the plugin search box. Lombok is a non-bundled plugin, so it won't show at first.
  3. Click "Browse" to search for non-bundled plugins
  4. The "Lombok Plugin" should show up. Select it.
  5. Click the green "Install" button.
  6. Click the "Restart Intellij IDEA" button.

Settings:

  1. Enable Annotation processor

    • Go to Preferences -> Build, Execution,Deployment -->Preferences -> Compiler -> Annotation Processors
    • File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors
  2. Check if Lombok plugin is enabled

    • IntelliJ IDEA-> Preferences -> Other Settings -> Lombok plugin -> Enable Lombok
  3. Add Lombok jar in Global Libraries and project dependencies.

    • File --> Project Structure --> Global libraries (Add lombok.jar)
  4. File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok

  5. Restart Intellij

How to create and download a csv file from php script?

I don't have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.

Correct line should look like this:

header('Content-Disposition: attachment;filename="'.$filename.'";');

In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:

header('Content-Type: application/csv; charset=UTF-8');

Also, I find it more elegant to use rewind() instead of fseek():

rewind($f);

Thanks for your solution!

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I found that following these instructions helped with finding what the problem was. For me, that was the killer, not knowing what was broken.

http://mythinkpond.wordpress.com/2011/07/01/tomcat-6-infamous-severe-error-listenerstart-message-how-to-debug-this-error/

Quoting from the link

In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here: http://tomcat.apache.org/tomcat-6.0-doc/logging.html

So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.

And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!

Sample logging.properties file:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

.m2 , settings.xml in Ubuntu

As per Where is Maven Installed on Ubuntu it will first create your settings.xml on /usr/share/maven2/, then you can copy to your home folder as jens mentioned

$ cp /usr/share/maven3/conf/settings.xml ~/.m2/settings.xml

Git will not init/sync/update new submodules

I had the same problem today and figured out that because I typed git submodule init then I had those line in my .git/config:

[submodule]
   active = .

I removed that and typed:

git submodule update --init --remote

And everything was back to normal, my submodule updated in its subdirectory as usual.

How to remove outliers from a dataset

Nobody has posted the simplest answer:

x[!x %in% boxplot.stats(x)$out]

Also see this: http://www.r-statistics.com/2011/01/how-to-label-all-the-outliers-in-a-boxplot/

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

SELECT DISTINCT on one column

SELECT min (id) AS 'ID', min(sku) AS 'SKU', Product
    FROM TestData
    WHERE sku LIKE 'FOO%' -- If you want only the sku that matchs with FOO%
    GROUP BY product 
    ORDER BY 'ID'

How to recover the deleted files using "rm -R" command in linux server?

Short answer: You can't. rm removes files blindly, with no concept of 'trash'.

Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i by default, but not all do.

Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete.

In the future, use rm with caution. Either create a del alias that provides interactivity, or use a file manager.

AutoComplete TextBox in WPF

I have published a WPF Auto Complete Text Box in WPF at CodePlex.com. You can download and try it from https://wpfautocomplete.codeplex.com/.

Python regex to match dates

As the question title asks for a regex that finds many dates, I would like to propose a new solution, although there are many solutions already.

In order to find all dates of a string that are in this millennium (2000 - 2999), for me it worked the following:

dates = re.findall('([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])(.|-|\/)([1-9]|1[0-2]|0[0-9])(.|-|\/)(20[0-9][0-9])',dates_ele)

dates = [''.join(dates[i]) for i in range(len(dates))]

This regex is able to find multiple dates in the same string, like bla Bla 8.05/2020 \n BLAH bla15/05-2020 blaa. As one could observe, instead of / the date can have . or -, not necessary at the same time.

Some explaining

More specifically it can find dates of format day , moth year. Day is an one digit integer or a zero followed by one digit integer or 1 or 2 followed by an one digit integer or a 3 followed by 0 or 1. Month is an one digit integer or a zero followed by one digit integer or 1 followed by 0, 1, or 2. Year is the number 20 followed by any number between 00 and 99.

Useful notes

One can add more date splitting symbols by adding | symbol at the end of both (.|-|\/). For example for adding -- one would do (.|-|\/|--)

To have years outside of this millennium one has to modify (20[0-9][0-9]) to ([0-9][0-9][0-9][0-9])

How to determine if a number is positive or negative?

This code covers all cases and types:

public static boolean isNegative(Number number) {
    return (Double.doubleToLongBits(number.doubleValue()) & Long.MIN_VALUE) == Long.MIN_VALUE;
}

This method accepts any of the wrapper classes (Integer, Long, Float and Double) and thanks to auto-boxing any of the primitive numeric types (int, long, float and double) and simply checks it the high bit, which in all types is the sign bit, is set.

It returns true when passed any of:

  • any negative int/Integer
  • any negative long/Long
  • any negative float/Float
  • any negative double/Double
  • Double.NEGATIVE_INFINITY
  • Float.NEGATIVE_INFINITY

and false otherwise.

Routing with multiple Get methods in ASP.NET Web API

using Routing.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Routing.Controllers
{
    public class StudentsController : ApiController
    {
        static List<Students> Lststudents =
              new List<Students>() { new Students { id=1, name="kim" },
           new Students { id=2, name="aman" },
            new Students { id=3, name="shikha" },
            new Students { id=4, name="ria" } };

        [HttpGet]
        public IEnumerable<Students> getlist()
        {
            return Lststudents;
        }

        [HttpGet]
        public Students getcurrentstudent(int id)
        {
            return Lststudents.FirstOrDefault(e => e.id == id);
        }
        [HttpGet]
        [Route("api/Students/{id}/course")]
        public IEnumerable<string> getcurrentCourse(int id)
        {
            if (id == 1)
                return new List<string>() { "emgili", "hindi", "pun" };
            if (id == 2)
                return new List<string>() { "math" };
            if (id == 3)
                return new List<string>() { "c#", "webapi" };
            else return new List<string>() { };
        }

        [HttpGet]
        [Route("api/students/{id}/{name}")]
        public IEnumerable<Students> getlist(int id, string name)
        { return Lststudents.Where(e => e.id == id && e.name == name).ToList(); }

        [HttpGet]
        public IEnumerable<string> getlistcourse(int id, string name)
        {
            if (id == 1 && name == "kim")
                return new List<string>() { "emgili", "hindi", "pun" };
            if (id == 2 && name == "aman")
                return new List<string>() { "math" };
            else return new List<string>() { "no data" };
        }
    }
}

How to run an application as "run as administrator" from the command prompt?

Try this:

runas.exe /savecred /user:administrator "%sysdrive%\testScripts\testscript1.ps1" 

It saves the password the first time and never asks again. Maybe when you change the administrator password you will be prompted again.

How to process POST data in Node.js?

1) Install 'body-parser' from npm.

2) Then in your app.ts

var bodyParser = require('body-parser');

3) then you need to write

app.use(bodyParser.json())

in app.ts module

4) keep in mind that you include

app.use(bodyParser.json())

in the top or before any module declaration.

Ex:

app.use(bodyParser.json())
app.use('/user',user);

5) Then use

var postdata = req.body;

Is there a function to split a string in PL/SQL?

There is a simple way folks. Use REPLACE function. Here is an example of comma separated string ready to be passed to IN clause.

In PL/SQL:

StatusString :=   REPLACE('Active,Completed', ',', ''',''');

In SQL Plus:

Select  REPLACE('Active,Completed', ',', ''',''') from dual;

Unit testing with Spring Security

The problem is that Spring Security does not make the Authentication object available as a bean in the container, so there is no way to easily inject or autowire it out of the box.

Before we started to use Spring Security, we would create a session-scoped bean in the container to store the Principal, inject this into an "AuthenticationService" (singleton) and then inject this bean into other services that needed knowledge of the current Principal.

If you are implementing your own authentication service, you could basically do the same thing: create a session-scoped bean with a "principal" property, inject this into your authentication service, have the auth service set the property on successful auth, and then make the auth service available to other beans as you need it.

I wouldn't feel too bad about using SecurityContextHolder. though. I know that it's a static / Singleton and that Spring discourages using such things but their implementation takes care to behave appropriately depending on the environment: session-scoped in a Servlet container, thread-scoped in a JUnit test, etc. The real limiting factor of a Singleton is when it provides an implementation that is inflexible to different environments.

How do I convert a number to a numeric, comma-separated formatted string?

Although formatting belongs to the Presentation layer, SQL Server 2012 and above versions provide FORMAT() function which provides one of the quickest and easiest way to format output. Here are some tips & examples:

Syntax: Format( value, format [, culture ] )

Returns: Format function returns NVarchar string formatted with the specified format and with optional culture. (Returns NULL for invalid format-string.)

Note: The Format() function is consistent across CLR / all .NET languages and provides maximum flexibility to generate formatted output.

Following are few format types that can be achieved using this function:

  • Numeric/Currency formatting - 'C' for currency, 'N' number without currency symbol, 'x' for Hexa-decimals.

  • Date/Time formatting - 'd' short date, 'D' long date, 'f' short full date/time, 'F' long full date/time, 't' short time, 'T' long time, 'm' month+day, 'y' year+month.

  • Custom formatting - you can form your own-custom format using certain symbols/characters, such as dd, mm, yyyy etc. (for Dates). hash (#) currency symbols (£ $ etc.), comma(,) and so on. See examples below.

Examples:

Examples of Built-in Numeric/Currency Formats:

?   select FORMAT(1500350.75, 'c', 'en-gb') --> £1,500,350.75
?   select FORMAT(1500350.75, 'c', 'en-au') --> $1,500,350.75
?   select FORMAT(1500350.75, 'c', 'en-in') --> ? 15,00,350.75

Examples of Built-in Date Formats:

?   select FORMAT(getdate(), 'd', 'en-gb') --> 20/06/2017
?   select FORMAT(getdate(), 'D', 'fr-fr') --> mardi 20 juin 2017
?   select FORMAT(getdate(), 'F', 'en-us') --> Tuesday, June 20, 2017 10:41:39 PM
?   select FORMAT(getdate(), 'T', 'en-gb') --> 22:42:29

Examples of Custom Formatting:

?   select FORMAT(GETDATE(), 'ddd  dd/MM/yyyy')  --> Tue 20/06/2017
?   select FORMAT(GETDATE(), 'dddd dd-MMM-yyyy') --> Tuesday 20-Jun-2017
?   select FORMAT(GETDATE(), 'dd.MMMM.yyyy HH:mm:ss') --> 20.June.2017 22:47:20
?   select FORMAT(123456789.75,'$#,#.00')  --> $123,456,789.75
?   select FORMAT(123456789.75,'£#,#.0')   --> £123,456,789.8

See MSDN for more information on FORMAT() function.

For SQL Server 2008 or below convert the output to MONEY first then to VARCHAR (passing "1" for the 3rd argument of CONVERT() function to specify the "style" of output-format), e.g.:

?   select CONVERT(VARCHAR, CONVERT(MONEY, 123456789.75), 1)    --> 123,456,789.75

How can I check the extension of a file?

os.path provides many functions for manipulating paths/filenames. (docs)

os.path.splitext takes a path and splits the file extension from the end of it.

import os

filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]

for fp in filepaths:
    # Split the extension from the path and normalise it to lowercase.
    ext = os.path.splitext(fp)[-1].lower()

    # Now we can simply use == to check for equality, no need for wildcards.
    if ext == ".mp3":
        print fp, "is an mp3!"
    elif ext == ".flac":
        print fp, "is a flac file!"
    else:
        print fp, "is an unknown file format."

Gives:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

Appending to an object

As an alternative, in ES6, spread syntax might be used. ${Object.keys(alerts).length + 1} returns next id for alert.

_x000D_
_x000D_
let alerts = { _x000D_
    1: {app:'helloworld',message:'message'},_x000D_
    2: {app:'helloagain',message:'another message'}_x000D_
};_x000D_
_x000D_
alerts = {_x000D_
  ...alerts, _x000D_
  [`${Object.keys(alerts).length + 1}`]: _x000D_
  { _x000D_
    app: `helloagain${Object.keys(alerts).length + 1}`,message: 'next message' _x000D_
  } _x000D_
};_x000D_
_x000D_
console.log(alerts);
_x000D_
_x000D_
_x000D_

What causes "Unable to access jarfile" error?

Just came across the same problem trying to make a bad USB...

I tried to run this command in admin cmd

java -jar c:\fw\ducky\duckencode.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

But got this error:

Error: unable to access jarfile c:\fw\ducky\duckencode.jar

Solution

1st step

Right click the jarfile in question. Click properties. Click the unblock tab in bottom right corner. The file was blocked, because it was downloaded and not created on my PC.

2nd step

In the cmd I changed the directory to where the jar file is located.

cd C:\fw\ducky\

Then I typed dir and saw the file was named duckencode.jar.jar

So in cmd I changed the original command to reference the file with .jar.jar

java -jar c:\fw\ducky\duckencode.jar.jar -I c:\fw\ducky\HelloWorld.txt  -o c:\fw\ducky\inject.bin

That command executed without error messages and the inject.bin I was trying to create was now located in the directory.

Hope this helps.

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

What’s the best way to check if a file exists in C++? (cross platform)

I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:

ifstream file(argv[1]);
if (!file)
{
    // Can't open file
}

It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.

How to echo out the values of this array?

var_dump($value)

it solved my problem, hope yours too.

@RequestParam vs @PathVariable

Both the annotations behave exactly in same manner.

Only 2 special characters '!' and '@' are accepted by the annotations @PathVariable and @RequestParam.

To check and confirm the behavior I have created a spring boot application that contains only 1 controller.

 @RestController 
public class Controller 
{
    @GetMapping("/pvar/{pdata}")
    public @ResponseBody String testPathVariable(@PathVariable(name="pdata") String pathdata)
    {
        return pathdata;
    }

    @GetMapping("/rpvar")
    public @ResponseBody String testRequestParam(@RequestParam("param") String paramdata)
    {
        return paramdata;
    }
}

Hitting following Requests I got the same response:

  1. localhost:7000/pvar/!@#$%^&*()_+-=[]{}|;':",./<>?
  2. localhost:7000/rpvar?param=!@#$%^&*()_+-=[]{}|;':",./<>?

!@ was received as response in both the requests

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I have been running into the same error when I add the following maven dependency in my project:

<artifactId>aws-encryption-sdk-java</artifactId>

The error came up only when I ran the shade jar file produced by maven-shade-plugin. I was able to overcome the error by using the jar produced by maven-assembly-plugin.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

Setting this attribute to ObjectMapper instance works,

objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

What is "with (nolock)" in SQL Server?

The text book example for legitimate usage of the nolock hint is report sampling against a high update OLTP database.

To take a topical example. If a large US high street bank wanted to run an hourly report looking for the first signs of a city level run on the bank, a nolock query could scan transaction tables summing cash deposits and cash withdrawals per city. For such a report the tiny percentage of error caused by rolled back update transactions would not reduce the value of the report.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Here's a simple solution, using TypeScript:

  convertDateStringToDate(dateStr) {
    //  Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
    let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    let date = new Date(dateStr);
    let str = date.getDate()
                + '/' + months[date.getMonth()]
                + '/' + date.getFullYear()
    return str;
  }

(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)

How to delete the top 1000 rows from a table using Sql Server 2008?

SET ROWCOUNT 1000;

DELETE FROM [MyTable] WHERE .....

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

How do you change the size of figures drawn with matplotlib?

The first link in Google for 'matplotlib figure size' is AdjustingImageSize (Google cache of the page).

Here's a test script from the above page. It creates test[1-3].png files of different sizes of the same image:

#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib

"""

import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.

import pylab
import numpy as np

# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

pylab.plot(x,y)
F = pylab.gcf()

# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI

# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image

# Now make the image twice as big, making all the fonts and lines
# bigger too.

F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.

Output:

using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8.  6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16.  12.]
Size in Inches [ 16.  12.]

Two notes:

  1. The module comments and the actual output differ.

  2. This answer allows easily to combine all three images in one image file to see the difference in sizes.

How do I get the IP address into a batch-file variable?

This will print the IP addresses in the output of ipconfig:

@echo off
set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
echo Network Connection Test
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do echo Your IP Address is: %%f

To only print the first IP address, just add goto :eof (or another label to jump to instead of :eof) after the echo, or in a more readable form:

set ip_address_string="IPv4 Address"
rem Uncomment the following line when using older versions of Windows without IPv6 support (by removing "rem")
rem set ip_address_string="IP Address"
for /f "usebackq tokens=2 delims=:" %%f in (`ipconfig ^| findstr /c:%ip_address_string%`) do (
    echo Your IP Address is: %%f
    goto :eof
)

A more configurable way would be to actually parse the output of ipconfig /all a little bit, that way you can even specify the adapter whose IP address you want:

@echo off
setlocal enabledelayedexpansion
::just a sample adapter here:
set "adapter=Ethernet adapter VirtualBox Host-Only Network"
set adapterfound=false
echo Network Connection Test
for /f "usebackq tokens=1-2 delims=:" %%f in (`ipconfig /all`) do (
    set "item=%%f"
    if /i "!item!"=="!adapter!" (
        set adapterfound=true
    ) else if not "!item!"=="!item:IP Address=!" if "!adapterfound!"=="true" (
        echo Your IP Address is: %%g
        set adapterfound=false
    )
)

How can I delete a file from a Git repository?

More generally, git help will help with at least simple questions like this:

zhasper@berens:/media/Kindle/documents$ git help
usage: git [--version] [--exec-path[=GIT_EXEC_PATH]] [--html-path] [-p|--paginate|--no-pager] [--bare] [--git-dir=GIT_DIR] [--work-tree=GIT_WORK_TREE] [--help] COMMAND [ARGS]

The most commonly used git commands are:
   add        Add file contents to the index
   :
   rm         Remove files from the working tree and from the index

How to get Tensorflow tensor dimensions (shape) as int values?

To get the shape as a list of ints, do tensor.get_shape().as_list().

To complete your tf.shape() call, try tensor2 = tf.reshape(tensor, tf.TensorShape([num_rows*num_cols, 1])). Or you can directly do tensor2 = tf.reshape(tensor, tf.TensorShape([-1, 1])) where its first dimension can be inferred.

How do I install and use curl on Windows?

I was looking for the download process of Curl and every where they said copy curl.exe file in System32 but they haven't provided the direct link. so here it is enjoy, find curl.exe easily in bin folder just

unzip it and then go to bin folder there you get exe file

link to download curl generic

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How do I convert a Python program to a runnable .exe Windows program?

Understand that every 'freezing' application for Python will not really secure your code in any way. Every packaging system for a stand-alone executable Python 'program' will include a lot of the Python libraries and interpreter, which will make your program pretty large.

That said, PyInstaller has done a nearly flawless job with everything I've thrown at it. Currently it only supports up to Python 2.7 but Pyinstaller's support for a varied set of libraries large and small is unmatched in other 'freeze' type programs for Python.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Okay adding to @null's awesome post about using the Asset Catalog.

You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.


After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets in Xcode.

By Default this should be

  • AppIcon
  • LaunchImage

[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)


What is created now each build is the following data structures in your .app:

For App Icons:

iPhone

  • AppIcon57x57.png (iPhone non retina) [Notice the Icon name prefix]
  • [email protected] (iPhone retina)

And the same format for each of the other icon resolutions.

iPad

  • AppIcon72x72~ipad.png (iPad non retina)
  • AppIcon72x72@2x~ipad.png (iPad retina)

(For iPad it is slightly different postfix)


Main Problem

Now I noticed that in my Info.plist in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)" after completing the creation of the Asset Catalog.

If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.

Final Solution:

Add the following key to you main .plist

I suggest you open your main .plist with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon57x57.png</string>
            <string>[email protected]</string>
            <string>AppIcon72x72~ipad.png</string>
            <string>AppIcon72x72@2x~ipad.png</string>
        </array>
    </dict>
</dict>

Please Note I have only included my example resolutions, you will need to add them all.


If you want to add this Key in Xcode without an external editor, Use the following:

  • Icon files (iOS 5) - Dictionary
  • Primary Icon - Dictionary
  • Icon files - Array
  • Item 0 - String = AppIcon57x57.png And for each other item / app icon.

Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.

Do not add the following to any .plist: Just an example of what Xcode will now generate for your final payload

<key>IconPaths</key>
<array>
    <string>Applications/Example.app/AppIcon57x57.png</string>
    <string>Applications/Example.app/[email protected]</string>
    <string>Applications/Example.app/AppIcon72x72~ipad.png</string>
    <string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>

Django Reverse with arguments '()' and keyword arguments '{}' not found

Resolve is also more straightforward

from django.urls import resolve

resolve('edit_project', project_id=4)

Documentation on this shortcut

From a Sybase Database, how I can get table description ( field names and types)?

     SELECT
DB_NAME() TABLE_CATALOG,
NULL TABLE_SCHEMA,
so.name TABLE_NAME,
sc.name COLUMN_NAME,
sc.colid ORDINAL_POSITION,
NULL COLUMN_DEFAULT,
CASE WHEN st.allownulls=1 THEN 'YES'
 ELSE 'NO'
END IS_NULLABLE,
st.name DATA_TYPE,
CASE WHEN st.name like '%char%' THEN st.length
END CHARACTER_MAXIMUM_LENGTH,
CASE WHEN st.name like '%char%' THEN st.length
END*2 CHARACTER_OCTET_LENGTH,
CASE WHEN st.name in ('numeric','int') THEN st.length
END NUMERIC_MAXIMUM_LENGTH,
CASE WHEN st.name in ('numeric','int') THEN st.prec
END NUMERIC_PRECISION,
NULL NUMERIC_PRECISION_RADIX,
CASE WHEN st.name in ('numeric','int') THEN st.scale
END NUMERIC_SCALE,
CASE WHEN st.name in ('datetime') THEN st.prec
END DATETIME_PRECISION,
NULL CHARACTER_SET_CATALOG,
NULL CHARACTER_SET_SCHEMA,
NULL COLLATION_CATALOG,
NULL COLLATION_SCHEMA,
NULL DOMAIN_CATALOG,
NULL DOMAIN_SCHEMA,
NULL DOMAIN_NAME
FROM 
sysobjects so
INNER JOIN 
syscolumns sc
ON sc.id = so.id
inner join systypes st on st.usertype = sc.usertype 
WHERE so.name = 'TableName'

nginx showing blank PHP pages

In case anyone is having this issue but none of the above answers solve their problems, I was having this same issue and had the hardest time tracking it down since my config files were correct, my ngnix and php-fpm jobs were running fine, and there were no errors coming through any error logs.

Dumb mistake but I never checked the Short Open Tag variable in my php.ini file which was set to short_open_tag = Off. Since my php files were using <? instead of <?php, the pages were showing up blank. Short Open Tag should have been set to On in my case.

Hope this helps someone.

CodeIgniter: How to get Controller, Action, URL information

Use This Code anywhere in class or libraries

    $current_url =& get_instance(); //  get a reference to CodeIgniter
    $current_url->router->fetch_class(); // for Class name or controller
    $current_url->router->fetch_method(); // for method name

Single statement across multiple lines in VB.NET without the underscore character

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to protect Excel workbook using VBA?

To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.

If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".

Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I've opened a similar question in the Doctrine user mailing list and got a really simple answer;

consider the many to many relation as an entity itself, and then you realize you have 3 objects, linked between them with a one-to-many and many-to-one relation.

http://groups.google.com/group/doctrine-user/browse_thread/thread/d1d87c96052e76f7/436b896e83c10868#436b896e83c10868

Once a relation has data, it's no more a relation !

How do you do block comments in YAML?

One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.

In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

Woo Images!

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

Can I stretch text using CSS?

Technically, no. But what you can do is use a font size that is as tall as you would like the stretched font to be, and then condense it horizontally with font-stretch.

What is the 'dynamic' type in C# 4.0 used for?

It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:

For example, you might use the following code to increment a counter in XML in C#.

Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);

By using the DLR, you could use the following code instead for the same operation.

scriptobj.Count += 1;

MSDN lists these advantages:

  • Simplifies Porting Dynamic Languages to the .NET Framework
  • Enables Dynamic Features in Statically Typed Languages
  • Provides Future Benefits of the DLR and .NET Framework
  • Enables Sharing of Libraries and Objects
  • Provides Fast Dynamic Dispatch and Invocation

See MSDN for more details.

Get all messages from Whatsapp

I'm not sure if WhatsApp really stores it's stuff in a sqlite database stored in the private app space but it may be worth a try to do the same I suggested here. You will need root access for this.

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In case you are appending to the DOM, make sure the content is compatible:

modal.find ('div.modal-body').append (content) // check content

How to convert an array of key-value tuples into an object

I much more recommend you to use ES6 with it's perfect Object.assign() method.

Object.assign({}, ...array.map(([ key, value ]) => ({ [key]: value })));

What happening here - Object.assign() do nothing but take key:value from donating object and puts pair in your result. In this case I'm using ... to split new array to multiply pairs (after map it looks like [{'cardType':'iDEBIT'}, ... ]). So in the end, new {} receives every key:property from each pair from mapped array.

How to remove the querystring and get only the url?

Here is a simple solution if you are using Laravel:

Str::before($request->getRequestUri(), '?')

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".

TypeError: unsupported operand type(s) for /: 'str' and 'str'

The first thing you should do is learn to read error messages. What does it tell you -- that you can't use two strings with the divide operator.

So, ask yourself why they are strings and how do you make them not-strings. They are strings because all input is done via strings. And the way to make then not-strings is to convert them.

One way to convert a string to an integer is to use the int function. For example:

percent = (int(pyc) / int(tpy)) * 100

Reinitialize Slick js after successful ajax call

I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.

try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:

jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});

Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}); the first ajax call and once it is initialized then follow above steps, you may wanna use if else

The data-toggle attributes in Twitter Bootstrap

Any attribute that starts with data- is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel and other attributes for purposes other than their original intended purposes (rel was often used to hold data for things like advanced tooltips).

In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).

html5doctor has a good article on the data- attribute.

Cycle 2 is another example of extensive use of the data- attribute.

Angular 4 HttpClient Query Parameters

search property of type URLSearchParams in RequestOptions class is deprecated in angular 4. Instead, you should use params property of type URLSearchParams.

Android : change button text and background color

Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:

<MaterialButton
  app:backgroundTint="@color/my_color"
  android:textColor="@android:color/white"/>

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

How to add line breaks to an HTML textarea?

If you just need to send the value of the testarea to server with line breaks use nl2br

MySQL wait_timeout Variable - GLOBAL vs SESSION

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800

At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.

SET @@GLOBAL.wait_timeout=300

After you set the global variable, the session variable automatically grabs the value.

SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300

Next time when the server restarts, the session variables will be set to the default value i.e. 28800.

P.S. I m using MySQL 5.6.16

Wordpress plugin install: Could not create directory

For me the problem was FTP server that WP is using to upload update. It had writting disabled in configuration, so just enabling it fixed the problem.

Shame on WordPress for providing such misleading error message.

Instagram API - How can I retrieve the list of people a user is following on Instagram

Shiva's answer doesn't apply anymore. The API call "/users/{user-id}/follows" is not supported by Instagram for some time (it was disabled in 2016).

For a while you were able to get only your own followers/followings with "/users/self/follows" endpoint, but Instagram disabled that feature in April 2018 (with the Cambridge Analytica issue). You can read about it here.

As far as I know (at this moment) there isn't a service available (official or unofficial) where you can get the followers/followings of a user (even your own).

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

How does the SQL injection from the "Bobby Tables" XKCD comic work?

It drops the students table.

The original code in the school's program probably looks something like

q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";

This is the naive way to add text input into a query, and is very bad, as you will see.

After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --) and the last name textbox LName.Text (let's call it Derper) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this

INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')

which, in plain English, roughly translates to the two queries:

Add a new record to the Students table with a Name value of 'Robert'

and

Delete the Students table

Everything past the second query is marked as a comment: --', 'Derper')

The ' in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in valid SQL.

Edited again as per dan04's astute comment

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

What are the applications of binary trees?

A binary tree is a tree data structure in which each node has at most two child nodes, usually distinguished as "left" and "right". Nodes with children are parent nodes, and child nodes may contain references to their parents. Outside the tree, there is often a reference to the "root" node (the ancestor of all nodes), if it exists. Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child. In a binary tree a degree of every node is maximum two.

Binary Tree

Binary trees are useful, because as you can see in the picture, if you want to find any node in the tree, you only have to look a maximum of 6 times. If you wanted to search for node 24, for example, you would start at the root.

  • The root has a value of 31, which is greater than 24, so you go to the left node.
  • The left node has a value of 15, which is less than 24, so you go to the right node.
  • The right node has a value of 23, which is less than 24, so you go to the right node.
  • The right node has a value of 27, which is greater than 24, so you go to the left node.
  • The left node has a value of 25, which is greater than 24, so you go to the left node.
  • The node has a value of 24, which is the key we are looking for.

This search is illustrated below: Tree search

You can see that you can exclude half of the nodes of the entire tree on the first pass. and half of the left subtree on the second. This makes for very effective searches. If this was done on 4 billion elements, you would only have to search a maximum of 32 times. Therefore, the more elements contained in the tree, the more efficient your search can be.

Deletions can become complex. If the node has 0 or 1 child, then it's simply a matter of moving some pointers to exclude the one to be deleted. However, you can not easily delete a node with 2 children. So we take a short cut. Let's say we wanted to delete node 19.

Delete 1

Since trying to determine where to move the left and right pointers to is not easy, we find one to substitute it with. We go to the left sub-tree, and go as far right as we can go. This gives us the next greatest value of the node we want to delete.

Delete 3

Now we copy all of 18's contents, except for the left and right pointers, and delete the original 18 node.

Delete 4


To create these images, I implemented an AVL tree, a self balancing tree, so that at any point in time, the tree has at most one level of difference between the leaf nodes (nodes with no children). This keeps the tree from becoming skewed and maintains the maximum O(log n) search time, with the cost of a little more time required for insertions and deletions.

Here is a sample showing how my AVL tree has kept itself as compact and balanced as possible.

enter image description here

In a sorted array, lookups would still take O(log(n)), just like a tree, but random insertion and removal would take O(n) instead of the tree's O(log(n)). Some STL containers use these performance characteristics to their advantage so insertion and removal times take a maximum of O(log n), which is very fast. Some of these containers are map, multimap, set, and multiset.

Example code for an AVL tree can be found at http://ideone.com/MheW8

How to read a .xlsx file using the pandas Library in iPython?

If you use read_excel() on a file opened using the function open(), make sure to add rb to the open function to avoid encoding errors

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

Save Screen (program) output to a file

You can also use Control-a + H to save loggings into screenlog.n file. One more Control-a + H to turn off.

C-a H: Begins/ends logging of the current window to the file "screenlog.n".

Woocommerce get products

Do not use WP_Query() or get_posts(). From the WooCommerce doc:

wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.

You can retrieve the products you want like this:

$args = array(
    'category' => array( 'hoodies' ),
    'orderby'  => 'name',
);
$products = wc_get_products( $args );

WooCommerce documentation

Note: the category argument takes an array of slugs, not IDs.

React onClick function fires on render

For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...

replace this <a onClick={props.signOut()}>Log Out</a>

with this <a onClick={props.signOut}>Log Out</a> ... !

How to make for loops in Java increase by increments other than 1

Since nobody else has actually tackled Could someone please explain this to me? I believe I will:

j++ is shorthand, it's not an actual operation (ok it really IS, but bear with me for the explanation)

j++ is really equal to the operation j = j + 1; except it's not a macro or something that does inline replacement. There are a lot of discussions on here about the operations of i+++++i and what that means (because it could be intepreted as i++ + ++i OR (i++)++ + i

Which brings us to: i++ versus ++i. They are called the post-increment and pre-increment operators. Can you guess why they are so named? The important part is how they're used in assignments. For instance, you could do: j=i++; or j=++i; We shall now do an example experiment:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i++;
k = ++i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

What are the values of i, j, and k?

I'll give you the answers and let you work it out ;)

i = 7, j = 5, k = 7; That's the power of the pre and post increment operators, and the hazards of using them wrong. But here's the alternate way of writing that same order of operations:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i;
i = i + 1; //post-increment

i = i + 1; //pre-increment
k = i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

Ok, now that I've shown you how the ++ operator works, let's examine why it doesn't work for j+3 ... Remember how I called it a "shorthand" earlier? That's just it, see the second example, because that's effectively what the compiler does before using the command (it's more complicated than that, but that's not for first explanations). So you'll see that the "expanded shorthand" has i = AND i + 1 which is all that your request has.

This goes back to math. A function is defined where f(x) = mx + b or an equation y = mx + b so what do we call mx + b ... it's certainly not a function or equation. At most it is an expression. Which is all j+3 is, an expression. An expression without assignment does us no good, but it does take up CPU time (assuming the compiler doesn't optimize it out).


I hope that clarifies things for you and gives you some room to ask new questions. Cheers!

Kotlin's List missing "add", "remove", Map missing "put", etc?

https://kotlinlang.org/docs/reference/collections.html

According to above link List<E> is immutable in Kotlin. However this would work:

var list2 = ArrayList<String>()
list2.removeAt(1)

How can I set up an editor to work with Git on Windows?

This works for PowerShell and cmder 1.2 (when used with PowerShell). In file ~/.gitconfig:

[core]
    editor = 'c:/program files/sublime text 3/subl.exe' -w

How can I make Sublime Text the default editor for Git?

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Using CSS to affect div style inside iframe

Use Jquery and wait till the source is loaded, This is how I have achieved(Used angular interval, you can use javascript setInterval method):

var addCssToIframe = function() {
    if ($('#myIframe').contents().find("head") != undefined) {
        $('#myIframe')
                .contents()
                .find("head")
                .append(
                        '<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
        $interval.cancel(addCssInterval);
    }
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Send XML data to webservice using php curl

After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:

//Store your XML Request in a variable
    $input_xml = '<AvailRequest>
            <Trip>ONE</Trip>
            <Origin>BOM</Origin>
            <Destination>JFK</Destination>
            <DepartDate>2013-09-15</DepartDate>
            <ReturnDate>2013-09-16</ReturnDate>
            <AdultPax>1</AdultPax>
            <ChildPax>0</ChildPax>
            <InfantPax>0</InfantPax>
            <Currency>INR</Currency>
            <PreferredClass>E</PreferredClass>
            <Eticket>true</Eticket>
            <Clientid>777ClientID</Clientid>
            <Clientpassword>*Your API Password</Clientpassword>
            <Clienttype>ArzooINTLWS1.0</Clienttype>
            <PreferredAirline></PreferredAirline>
    </AvailRequest>';

Now I've made a little changes in the above curl_setopt declaration as follows:

    $url = "http://59.162.33.102:9301/Avalability";

        //setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" . $input_xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        curl_close($ch);

        //convert the XML result into array
        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        print_r('<pre>');
        print_r($array_data);
        print_r('</pre>');

That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.

react native get TextInput value

Every thing is OK for me by this procedure:

<Input onChangeText={this.inputOnChangeText} />

and also:

inputOnChangeText = (e) => {
  this.setState({
    username: e
  })
}

How to workaround 'FB is not defined'?

Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'
     && FB != null ) {
    // run the app
} else {
    // alert the user
}

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.

Global approach

Configure Git line endings handling on Linux or OS X:

git config --global core.autocrlf input

Configure Git line endings handling on Windows:

git config --global core.autocrlf true

Per-repo approach:

In the root of your repo, create a .gitattributes file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings where line-ending-settings is one of the following:

  • text
  • binary (files that Git should not modify line endings for - as this can cause some image types such as PNGs not to render in a browser)

The text value can be configured further to instruct Git on how to handle line endings for matching files:

  • text - Changes line endings to OS native line endings.
  • text eol=crlf - Converts line endings to CRLF on checkout.
  • text eol=lf - Converts line endings to LF on checkout.
  • text=auto - Sensible default that leaves line handle up to Git's discretion.

Here is the content of a sample .gitattributes file:

# Set the default behavior for all files.
* text=auto

# Normalized and converts to 
# native line endings on checkout.
*.c text
*.h text

# Convert to CRLF line endings on checkout.
*.sln text eol=crlf

# Convert to LF line endings on checkout.
*.sh text eol=lf

# Binary files.
*.png binary
*.jpg binary

More on how to refresh your repo after changing line endings settings here. Tldr:

backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.

git add . -u

git commit -m "Saving files before refreshing line endings"

Remove the index and force Git to rescan the working directory.

rm .git/index

Rewrite the Git index to pick up all the new line endings.

git reset

Show the rewritten, normalized files.

In some cases, this is all that needs to be done. Others may need to complete the following additional steps:

git status

Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.

git add -u

It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."

Rewrite the .gitattributes file.

git add .gitattributes

Commit the changes to your repository.

git commit -m "Normalize all the line endings"

Could not reserve enough space for object heap

If you're running 32bit JVM, change heap size to smaller would probabaly help. You can do this by passing args to java directly or through enviroment variables like following,

java -Xms128M -Xmx512M
JAVA_OPTS="-Xms128M -Xmx512M"

For 64bit JVM, bigger heap size like -Xms512M -Xmx1536M should work.

Run java -version or java -d32, java--d64 for Java7 to check which version you're running.

CSS Div stretch 100% page height

Use position absolute. Note that this isn't how we are generally used to using position absolute which requires manually laying things out or having floating dialogs. This will automatically stretch when you resize the window or the content. I believe that this requires standards mode but will work in IE6 and above.

Just replace the div with id 'thecontent' with your content (the specified height there is just for illustration, you don't have to specify a height on the actual content.

<div style="position: relative; width: 100%;">
      <div style="position: absolute; left: 0px; right: 33%; bottom: 0px; top: 0px; background-color: blue; width: 33%;" id="navbar">nav bar</div>
      <div style="position: relative; left: 33%; width: 66%; background-color: yellow;" id="content">
         <div style="height: 10000px;" id="thecontent"></div>
      </div>
</div>

The way that this works is that the outer div acts as a reference point for the nav bar. The outer div is stretched out by the content of the 'content' div. The nav bar uses absolute positioning to stretch itself out to the height of its parent. For the horizontal alignment we make the content div offset itself by the same width of the navbar.

This is made much easier with CSS3 flex box model, but that's not available in IE yet and has some of it's own quirks.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

Starting of Tomcat failed from Netbeans

None of the answers here solved my issue (as at February 2020), so I raised an issue at https://issues.apache.org/jira/browse/NETBEANS-3903 and Netbeans fixed the issue!

They're working on a pull request so the fix will be in a future .dmg installer soon, but in the meantime you can copy a file referenced in the bug and replace one in your netbeans modules folder.

Tip - if you right click on Applications > Netbeans and choose Show Package Contents Show Package Contents then you can find and replace the file org-netbeans-modules-tomcat5.jar that they refer to in your Netbeans folder, e.g. within /Applications/NetBeans/Apache NetBeans 11.2.app/Contents/Resources/NetBeans/netbeans/enterprise/modules

How can I convert JSON to a HashMap using Gson?

Here is what I have been using:

public static HashMap<String, Object> parse(String json) {
    JsonObject object = (JsonObject) parser.parse(json);
    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (!value.isJsonPrimitive()) {
            map.put(key, parse(value.toString()));
        } else {
            map.put(key, value.getAsString());
        }
    }
    return map;
}

How do I resize a Google Map with JavaScript after it has loaded?

The popular answer google.maps.event.trigger(map, "resize"); didn't work for me alone.

Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.

$(document).ready(function() {
    google.maps.event.addListener(map, "idle", function(){
        google.maps.event.trigger(map, 'resize'); 
    });
}); 

This was my answer that worked for me.

Xcode 4: create IPA file instead of .xcarchive

I had this same problem, using an old version of the route-me library. I "skipped" all the libraries, and the libraries inside of libraries (proj4), but I still had the same problem. Turns out that route-me and proj4 were installing public header files, even when the libraries were being skipped, which was messing it up in the same way! So I just went into the route-me and proj4 targets "Build Phases" tab, opened "Copy Headers", opened "Public", and dragged those headers from "Public" into "Project". Now they don't get installed in $(BUILD)/usr/local/include, and I'm able to make an ipa file from the archive!

I hope Apple fixes this horrible usability problem with XCode. It gives absolutely no indication of what's wrong, it just doesn't work. I hate dimmed out controls that don't tell you anything about why they're dimmed out. How about instead of ignoring clicks, the disabled controls could pop up a message telling you why the hell they're disabled when you click on them in frustration?

How can I make sticky headers in RecyclerView? (Without external lib)

you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:

  • can interact with the sticy header (tap/long press/swipe)
  • the sticky header hides and reveals itself properly...even if each view holder has a different height (some other answers here don't handle that properly, causing the wrong headers to show, or the headers to jump up and down)

see an example of the 2 files being used in this small github project i whipped up

Using jquery to get all checked checkboxes with a certain class name

HTML

 <p> <input type="checkbox" name="fruits" id="fruits"  value="1" /> Apple </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="2" /> Banana </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="3" /> Mango </p>
 <p> <input type="checkbox" name="fruits" id="fruits"  value="4" /> Grape </p>

Jquery

for storing the selected fruit values define array.

 fruitArray = [];

$.each will iterate the checked check boxes and pushed into array.

 $.each($("input[name='fruits']:checked"), function (K, V) {    
    fruitArray.push(V.value);        
});

                                       

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

Check if textbox has empty value

if (inp.val().length > 0) {
    // do something
}

if you want anything more complicated, consider regex or use the validation plugin which takes care of this for you

C++ Structure Initialization

You can even pack Gui13's solution into single initialization statement:

struct address {
                 int street_no;
                 char *street_name;
                 char *city;
                 char *prov;
                 char *postal_code;
               };


address ta = (ta = address(), ta.city = "Hamilton", ta.prov = "Ontario", ta);

Disclaimer: I don't recommend this style

How to place two divs next to each other?

You can sit elements next to each other by using the CSS float property:

#first {
float: left;
}
#second {
float: left;
}

You'd need to make sure that the wrapper div allows for the floating in terms of width, and margins etc are set correctly.

showing that a date is greater than current date

If you're using SQL Server it would be something like this:

DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90

Visual Studio replace tab with 4 spaces?

For VS2010 and above (VS2010 needs a plugin). If you have checked/set the options of the tab size in Visual Studio but it still won't work. Then check if you have a .editorconfig file in your project! This will override the Visual Studio settings. Edit the tab-size in that file.

This can happen if you install an Angular application in your project with the Angular-Cli.

See MSDN blog

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

Force sidebar height 100% using CSS (with a sticky bottom image)?

Try this. It forces navbar to grow as content added, and keeps main area centered.

   <html>
        <head>
            <style>
                    section.sidebar {
          width: 250px;
          min-height:100vh;
          position: sticky;
          top: 0;
          bottom: 0;
          background-color: green;
        }

        section.main { position:sticky; top:0;bottom:0;background-color: red; margin-left: 250px;min-height:100vh; }
            </style>
            <script lang="javascript">
            var i = 0;
            function AddOne()
            {
                for(i = 0;i<20;i++)
                {
                var node = document.createElement("LI");
                var textnode = document.createTextNode(' Water ' + i.toString());

                node.appendChild(textnode);
                document.getElementById("list").appendChild(node);
                }


            }
            </script>
        </head>
        <body>
                <section class="sidebar">
                    <button id="add" onclick="AddOne()">Add</button>
                    <ul id="list">
                        <li>bullshit 1</li>
                    </ul>
                </section>
                <section class="main">I'm the main section.</section>
        </body>    
    </html>

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

Creating a file only if it doesn't exist in Node.js

With async / await and Typescript I would do:

import * as fs from 'fs'

async function upsertFile(name: string) {
  try {
    // try to read file
    await fs.promises.readFile(name)
  } catch (error) {
    // create empty file, because it wasn't found
    await fs.promises.writeFile(name, '')
  }
}

XAMPP Start automatically on Windows 7 startup

Go to the Config button (up right) and select the Autostart for Apache.enter image description here

Appending to an empty DataFrame in Pandas?

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

Timeout on a function call

You may use the signal package if you are running on UNIX:

In [1]: import signal

# Register an handler for the timeout
In [2]: def handler(signum, frame):
   ...:     print("Forever is over!")
   ...:     raise Exception("end of time")
   ...: 

# This function *may* run for an indetermined time...
In [3]: def loop_forever():
   ...:     import time
   ...:     while 1:
   ...:         print("sec")
   ...:         time.sleep(1)
   ...:         
   ...:         

# Register the signal function handler
In [4]: signal.signal(signal.SIGALRM, handler)
Out[4]: 0

# Define a timeout for your function
In [5]: signal.alarm(10)
Out[5]: 0

In [6]: try:
   ...:     loop_forever()
   ...: except Exception, exc: 
   ...:     print(exc)
   ....: 
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time

# Cancel the timer if the function returned before timeout
# (ok, mine won't but yours maybe will :)
In [7]: signal.alarm(0)
Out[7]: 0

10 seconds after the call signal.alarm(10), the handler is called. This raises an exception that you can intercept from the regular Python code.

This module doesn't play well with threads (but then, who does?)

Note that since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:

def loop_forever():
    while 1:
        print('sec')
        try:
            time.sleep(10)
        except:
            continue

How do you install Boost on MacOS?

In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:

sudo port install boost +universal

Send form data with jquery ajax json

You can use serialize() like this:

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});

In python, how do I cast a class object to a dict

There are at least five six ways. The preferred way depends on what your use case is.

Option 1:

Simply add an asdict() method.

Based on the problem description I would very much consider the asdict way of doing things suggested by other answers. This is because it does not appear that your object is really much of a collection:

class Wharrgarbl(object):

    ...

    def asdict(self):
        return {'a': self.a, 'b': self.b, 'c': self.c}

Using the other options below could be confusing for others unless it is very obvious exactly which object members would and would not be iterated or specified as key-value pairs.

Option 1a:

Inherit your class from 'typing.NamedTuple' (or the mostly equivalent 'collections.namedtuple'), and use the _asdict method provided for you.

from typing import NamedTuple

class Wharrgarbl(NamedTuple):
    a: str
    b: str
    c: str
    sum: int = 6
    version: str = 'old'

Using a named tuple is a very convenient way to add lots of functionality to your class with a minimum of effort, including an _asdict method. However, a limitation is that, as shown above, the NT will include all the members in its _asdict.

If there are members you don't want to include in your dictionary, you'll need to modify the _asdict result:

from typing import NamedTuple

class Wharrgarbl(NamedTuple):
    a: str
    b: str
    c: str
    sum: int = 6
    version: str = 'old'

    def _asdict(self):
        d = super()._asdict()
        del d['sum']
        del d['version']
        return d

Another limitation is that NT is read-only. This may or may not be desirable.

Option 2:

Implement __iter__.

Like this, for example:

def __iter__(self):
    yield 'a', self.a
    yield 'b', self.b
    yield 'c', self.c

Now you can just do:

dict(my_object)

This works because the dict() constructor accepts an iterable of (key, value) pairs to construct a dictionary. Before doing this, ask yourself the question whether iterating the object as a series of key,value pairs in this manner- while convenient for creating a dict- might actually be surprising behavior in other contexts. E.g., ask yourself the question "what should the behavior of list(my_object) be...?"

Additionally, note that accessing values directly using the get item obj["a"] syntax will not work, and keyword argument unpacking won't work. For those, you'd need to implement the mapping protocol.

Option 3:

Implement the mapping protocol. This allows access-by-key behavior, casting to a dict without using __iter__, and also provides unpacking behavior ({**my_obj}) and keyword unpacking behavior if all the keys are strings (dict(**my_obj)).

The mapping protocol requires that you provide (at minimum) two methods together: keys() and __getitem__.

class MyKwargUnpackable:
    def keys(self):
        return list("abc")
    def __getitem__(self, key):
        return dict(zip("abc", "one two three".split()))[key]

Now you can do things like:

>>> m=MyKwargUnpackable()
>>> m["a"]
'one'
>>> dict(m)  # cast to dict directly
{'a': 'one', 'b': 'two', 'c': 'three'}
>>> dict(**m)  # unpack as kwargs
{'a': 'one', 'b': 'two', 'c': 'three'}

As mentioned above, if you are using a new enough version of python you can also unpack your mapping-protocol object into a dictionary comprehension like so (and in this case it is not required that your keys be strings):

>>> {**m}
{'a': 'one', 'b': 'two', 'c': 'three'}

Note that the mapping protocol takes precedence over the __iter__ method when casting an object to a dict directly (without using kwarg unpacking, i.e. dict(m)). So it is possible- and sometimes convenient- to cause the object to have different behavior when used as an iterable (e.g., list(m)) vs. when cast to a dict (dict(m)).

EMPHASIZED: Just because you CAN use the mapping protocol, does NOT mean that you SHOULD do so. Does it actually make sense for your object to be passed around as a set of key-value pairs, or as keyword arguments and values? Does accessing it by key- just like a dictionary- really make sense?

If the answer to these questions is yes, it's probably a good idea to consider the next option.

Option 4:

Look into using the 'collections.abc' module.

Inheriting your class from 'collections.abc.Mapping or 'collections.abc.MutableMapping signals to other users that, for all intents and purposes, your class is a mapping * and can be expected to behave that way.

You can still cast your object to a dict just as you require, but there would probably be little reason to do so. Because of duck typing, bothering to cast your mapping object to a dict would just be an additional unnecessary step the majority of the time.

This answer might also be helpful.

As noted in the comments below: it's worth mentioning that doing this the abc way essentially turns your object class into a dict-like class (assuming you use MutableMapping and not the read-only Mapping base class). Everything you would be able to do with dict, you could do with your own class object. This may be, or may not be, desirable.

Also consider looking at the numerical abcs in the numbers module:

https://docs.python.org/3/library/numbers.html

Since you're also casting your object to an int, it might make more sense to essentially turn your class into a full fledged int so that casting isn't necessary.

Option 5:

Look into using the dataclasses module (Python 3.7 only), which includes a convenient asdict() utility method.

from dataclasses import dataclass, asdict, field, InitVar

@dataclass
class Wharrgarbl(object):
    a: int
    b: int
    c: int
    sum: InitVar[int]  # note: InitVar will exclude this from the dict
    version: InitVar[str] = "old"

    def __post_init__(self, sum, version):
        self.sum = 6  # this looks like an OP mistake?
        self.version = str(version)

Now you can do this:

    >>> asdict(Wharrgarbl(1,2,3,4,"X"))
    {'a': 1, 'b': 2, 'c': 3}

Option 6:

Use typing.TypedDict, which has been added in python 3.8.

NOTE: option 6 is likely NOT what the OP, or other readers based on the title of this question, are looking for. See additional comments below.

class Wharrgarbl(TypedDict):
    a: str
    b: str
    c: str

Using this option, the resulting object is a dict (emphasis: it is not a Wharrgarbl). There is no reason at all to "cast" it to a dict (unless you are making a copy).

And since the object is a dict, the initialization signature is identical to that of dict and as such it only accepts keyword arguments or another dictionary.

    >>> w = Wharrgarbl(a=1,b=2,b=3)
    >>> w
    {'a': 1, 'b': 2, 'c': 3}
    >>> type(w)
    <class 'dict'>

Emphasized: the above "class" Wharrgarbl isn't actually a new class at all. It is simply syntactic sugar for creating typed dict objects with fields of different types for the type checker.

As such this option can be pretty convenient for signaling to readers of your code (and also to a type checker such as mypy) that such a dict object is expected to have specific keys with specific value types.

But this means you cannot, for example, add other methods, although you can try:

class MyDict(TypedDict):
    def my_fancy_method(self):
        return "world changing result"

...but it won't work:

>>> MyDict().my_fancy_method()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'my_fancy_method'

* "Mapping" has become the standard "name" of the dict-like duck type

Difference between Method and Function?

There is no functions in c#. There is methods (typical method:public void UpdateLeaveStatus(EmployeeLeave objUpdateLeaveStatus)) link to msdn and functors - variable of type Func<>

What is the use of DesiredCapabilities in Selenium WebDriver?

Desired capabilities comes in handy while doing remote or parallel execution using selenium grid. We will be parametrizing the browser details and passing in to selenium server using desired capabilities class.

Another usage is, test automation using Appium as shown below

// Created object of DesiredCapabilities class. 
DesiredCapabilities capabilities = new DesiredCapabilities(); 
// Set android deviceName desired capability. Set your device name. 
capabilities.setCapability("deviceName", "your Device Name"); 
// Set BROWSER_NAME desired capability. 
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome"); 
// Set android VERSION desired capability. Set your mobile device's OS version. 
capabilities.setCapability(CapabilityType.VERSION, "5.1"); 
// Set android platformName desired capability. It's Android in our case here. 
capabilities.setCapability("platformName", "Android"); 

Can Selenium WebDriver open browser windows silently in the background?

It may be in options. Here is the identical Java code.

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setHeadless(true);
        WebDriver driver = new ChromeDriver(chromeOptions);

Unable to start MySQL server

See this post https://bugs.mysql.com/bug.php?id=67917 Sometimes a temp directory is missing. I had the same error like "InnoDB: Error: unable to create temporary file; errno: 2"

How to export a MySQL database to JSON?

Using MySQL Shell you can out put directly to JSON using only terminal

echo "Your SQL query" | mysqlsh --sql --result-format=json --uri=[username]@localhost/[schema_name]

How to add Certificate Authority file in CentOS 7

Maybe late to the party but in my case it was RHEL 6.8:

Copy certificate.crt issued by hosting to:

/etc/pki/ca-trust/source/anchors/

Then:

update-ca-trust force-enable (ignore not found warnings)
update-ca-trust extract

Hope it helps

What is the definition of "interface" in object oriented programming

Personally I see an interface like a template. If a interface contains the definition for the methods foo() and bar(), then you know every class which uses this interface has the methods foo() and bar().

Changing ViewPager to enable infinite page scrolling

Its hacked by CustomPagerAdapter:

MainActivity.java:

import android.content.Context;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<String> numberList = new ArrayList<String>();
    private CustomPagerAdapter mCustomPagerAdapter;
    private ViewPager mViewPager;
    private Handler handler;
    private Runnable runnable;

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

        numberList.clear();
        for (int i = 0; i < 10; i++) {
        numberList.add(""+i);
        }

        mViewPager = (ViewPager)findViewById(R.id.pager);
        mCustomPagerAdapter = new CustomPagerAdapter(MainActivity.this);
        EndlessPagerAdapter mAdapater = new EndlessPagerAdapter(mCustomPagerAdapter);
        mViewPager.setAdapter(mAdapater);


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int modulo = position%numberList.size();
                Log.i("Current ViewPager View's Position", ""+modulo);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {

                mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1);
                handler.postDelayed(runnable, 1000);
            }
        };

        handler.post(runnable);

    }

    @Override
    protected void onDestroy() {
        if(handler!=null){
            handler.removeCallbacks(runnable);
        }
        super.onDestroy();
    }

    private class CustomPagerAdapter extends PagerAdapter {

        Context mContext;
        LayoutInflater mLayoutInflater;

        public CustomPagerAdapter(Context context) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return numberList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((LinearLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View itemView = mLayoutInflater.inflate(R.layout.row_item_viewpager, container, false);

            TextView textView = (TextView) itemView.findViewById(R.id.txtItem);
            textView.setText(numberList.get(position));
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((LinearLayout) object);
        }
    }

    private class EndlessPagerAdapter extends PagerAdapter {

        private static final String TAG = "EndlessPagerAdapter";
        private static final boolean DEBUG = false;

        private final PagerAdapter mPagerAdapter;

        EndlessPagerAdapter(PagerAdapter pagerAdapter) {
            if (pagerAdapter == null) {
                throw new IllegalArgumentException("Did you forget initialize PagerAdapter?");
            }
            if ((pagerAdapter instanceof FragmentPagerAdapter || pagerAdapter instanceof FragmentStatePagerAdapter) && pagerAdapter.getCount() < 3) {
                throw new IllegalArgumentException("When you use FragmentPagerAdapter or FragmentStatePagerAdapter, it only supports >= 3 pages.");
            }
            mPagerAdapter = pagerAdapter;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (DEBUG) Log.d(TAG, "Destroy: " + getVirtualPosition(position));
            mPagerAdapter.destroyItem(container, getVirtualPosition(position), object);

            if (mPagerAdapter.getCount() < 4) {
                mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
            }
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            mPagerAdapter.finishUpdate(container);
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE; // this is the magic that we can scroll infinitely.
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mPagerAdapter.getPageTitle(getVirtualPosition(position));
        }

        @Override
        public float getPageWidth(int position) {
            return mPagerAdapter.getPageWidth(getVirtualPosition(position));
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return mPagerAdapter.isViewFromObject(view, o);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (DEBUG) Log.d(TAG, "Instantiate: " + getVirtualPosition(position));
            return mPagerAdapter.instantiateItem(container, getVirtualPosition(position));
        }

        @Override
        public Parcelable saveState() {
            return mPagerAdapter.saveState();
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
            mPagerAdapter.restoreState(state, loader);
        }

        @Override
        public void startUpdate(ViewGroup container) {
            mPagerAdapter.startUpdate(container);
        }

        int getVirtualPosition(int realPosition) {
            return realPosition % mPagerAdapter.getCount();
        }

        PagerAdapter getPagerAdapter() {
            return mPagerAdapter;
        }

    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="180dp">
    </android.support.v4.view.ViewPager>

</RelativeLayout>

row_item_viewpager.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtItem"
        android:textAppearance="@android:style/TextAppearance.Large"/>

</LinearLayout>

Done

How can I pass data from Flask to JavaScript in a template?

Well, I have a tricky method for this job. The idea is as follow-

Make some invisible HTML tags like <label>, <p>, <input> etc. in HTML body and make a pattern in tag id, for example, use list index in tag id and list value at tag class name.

Here I have two lists maintenance_next[] and maintenance_block_time[] of the same length. I want to pass these two list's data to javascript using the flask. So I take some invisible label tag and set its tag name is a pattern of list index and set its class name as value at index.

_x000D_
_x000D_
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
_x000D_
_x000D_

After this, I retrieve the data in javascript using some simple javascript operation.

_x000D_
_x000D_
<script>_x000D_
var total_len = {{ total_len }};_x000D_
_x000D_
for (var i = 0; i < total_len; i++) {_x000D_
    var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
    var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
    _x000D_
    //Do what you need to do with tm1 and tm2._x000D_
    _x000D_
    console.log(tm1);_x000D_
    console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

What is the maximum possible length of a .NET string?

200 megs... at which point your app grinds to a virtual halt, has about a gig working set memory, and the o/s starts to act like you'll need to reboot.

static void Main(string[] args)
{
    string s = "hello world";
    for(;;)
    {
        s = s + s.Substring(0, s.Length/10);
        Console.WriteLine(s.Length);
    }
}

12
13
14
15
16
17
18
...
158905664
174796230
192275853
211503438

Saving image from PHP URL

I wasn't able to get any of the other solutions to work, but I was able to use wget:

$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';

exec("cd $tempDir && wget --quiet $imageUrl");

if (!file_exists("$tempDir/image.jpg")) {
    throw new Exception('Failed while trying to download image');
}

if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
    throw new Exception('Failed while trying to move image file from temp dir to final dir');
}

How to change the text of a button in jQuery?

If you have button'ed your button this seems to work:

<button id="button">First caption</button>

$('#button').button();//make it nice
var text="new caption";
$('#button').children().first().html(text);

Why not use tables for layout in HTML?

To respond to the "tables are slower" argument - you're thinking rendering time, which is the wrong metric. Very often, developers will write out a huge table to do the entire layout for a page - which adds significantly to the size of the page to be downloaded. Like it or not, there's still a ton of dialup users out there.

See also: overusing ViewState

How to implement drop down list in flutter?

It had happened to me when I replace the default value with a new dynamic value. But, somehow your code may be dependent on that default value. So try keeping a constant with default value stored somewhere to fallback.

const defVal = 'abcd';
String dynVal = defVal;

// dropdown list whose value is dynVal that keeps changing with onchanged
// when rebuilding or setState((){})

dynVal = defVal;
// rebuilding here...

Allow only numbers and dot in script

_x000D_
_x000D_
function isNumberKey(evt,id)_x000D_
{_x000D_
 try{_x000D_
        var charCode = (evt.which) ? evt.which : event.keyCode;_x000D_
  _x000D_
        if(charCode==46){_x000D_
            var txt=document.getElementById(id).value;_x000D_
            if(!(txt.indexOf(".") > -1)){_x000D_
 _x000D_
                return true;_x000D_
            }_x000D_
        }_x000D_
        if (charCode > 31 && (charCode < 48 || charCode > 57) )_x000D_
            return false;_x000D_
_x000D_
        return true;_x000D_
 }catch(w){_x000D_
  alert(w);_x000D_
 }_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
  </head>_x000D_
  <body>_x000D_
    <INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to dump a dict to a json file?

import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

This is an easier way to do it.

In the second line of code the file result.json gets created and opened as the variable fp.

In the third line your dict sample gets written into the result.json!

jquery .live('click') vs .click()

As 'live' will handle events for future elements that match the current selector, you may choose click as you don't want that to happen - you only want to handle the current selected elements.

Also, I suspect (though have no evidence) that there is a slight efficiency using 'click' over 'live'.

Lee

ES6 modules implementation, how to load a json file

First of all you need to install json-loader:

npm i json-loader --save-dev

Then, there are two ways how you can use it:

  1. In order to avoid adding json-loader in each import you can add to webpack.config this line:

    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      // other loaders 
    ]
    

    Then import json files like this

    import suburbs from '../suburbs.json';
    
  2. Use json-loader directly in your import, as in your example:

    import suburbs from 'json!../suburbs.json';
    

Note: In webpack 2.* instead of keyword loaders need to use rules.,

also webpack 2.* uses json-loader by default

*.json files are now supported without the json-loader. You may still use it. It's not a breaking change.

v2.1.0-beta.28

How do I pass data to Angular routed components?

Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):

Prepare object before sending:

export class AdminUserListComponent {

  users : User[];

  constructor( private router : Router) { }

  modifyUser(i) {

    let navigationExtras: NavigationExtras = {
      queryParams: {
          "user": JSON.stringify(this.users[i])
      }
    };

    this.router.navigate(["admin/user/edit"],  navigationExtras);
  }

}

Receive your object in destination component:

export class AdminUserEditComponent  {

  userWithRole: UserWithRole;      

  constructor( private route: ActivatedRoute) {}

  ngOnInit(): void {
    super.ngOnInit();

      this.route.queryParams.subscribe(params => {
        this.userWithRole.user = JSON.parse(params["user"]);
      });
  }

}

How can I enter latitude and longitude in Google Maps?

First is latitude, second longitude. Different than many constructors in mapbox.

Here are examples of formats that work:

  • Degrees, minutes, and seconds (DMS): 41°24'12.2"N 2°10'26.5"E
  • Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418
  • Decimal degrees (DD): 41.40338, 2.17403

Tips for formatting your coordinates

  • Use the degree symbol instead of “d”.
  • Use periods as decimals, not commas.
    • Incorrect: 41,40338, 2,17403.
    • Correct: 41.40338, 2.17403.
  • List your latitude coordinates before longitude coordinates.
  • Check that the first number in your latitude coordinate is between -90 and 90 and the first number in your longitude coordinate is between -180 and 180.

https://support.google.com/maps/answer/18539

what's the easiest way to put space between 2 side-by-side buttons in asp.net

#btnClear{margin-left:100px;}

Or add a class to the buttons and have:

.yourClass{margin-left:100px;}

This achieves this - http://jsfiddle.net/QU93w/

Update built-in vim on Mac OS X

Don't overwrite the built-in Vim.

Instead, install it from source in a different location or via Homebrew or MacPorts in their default location then add this line to your .bashrc or .profile:

alias vim='/path/to/your/own/vim'

and/or change your $PATH so that it looks into its location before the default location.

The best thing to do, in my opinion, is to simply download the latest MacVim which comes with a very complete vim executable and use it in Terminal.app like so.

alias vim='/Applications/MacVim.app/Contents/MacOS/Vim' # or something like that, YMMV

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

Try this:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

How to test if a file is a directory in a batch script?

A variation of @batchman61's approach (checking the Directory attribute).

This time I use an external 'find' command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

@ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
    ECHO %1 is a directory
)

Outputs yes on:

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
  • Directories which you have no read permission on (e.g. "C:\System Volume Information")

Handlebars.js Else If

Handlebars now supports {{else if}} as of 3.0.0. Therefore, your code should now work.

You can see an example under "conditionals" (slightly revised here with an added {{else}}:

    {{#if isActive}}
      <img src="star.gif" alt="Active">
    {{else if isInactive}}
      <img src="cry.gif" alt="Inactive">
    {{else}}
      <img src="default.gif" alt="default">
    {{/if}}

http://handlebarsjs.com/block_helpers.html

Why do I always get the same sequence of random numbers with rand()?

Seeding the rand()

void srand (unsigned int seed)

This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.

To produce a different pseudo-random series each time your program is run, do srand (time (0))

Make button width fit to the text

just add display: inline-block; property and removed width.

Multiple ping script in Python

Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.

import subprocess
import os
with open(os.devnull, "wb") as limbo:
        for n in xrange(200, 240):
                ip="10.2.7.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                        stdout=limbo, stderr=limbo).wait()
                if result:
                        print ip, "inactive"
                else:
                        print ip, "active"

Just change the ip= for your scheme and the xrange for the hosts.

Centering a background image, using CSS

I think this is what is wanted:

body
{
    background-image:url('smiley.gif');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position:center;
} 

How to sleep the thread in node.js without affecting other threads?

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

Is there a good jQuery Drag-and-drop file upload plugin?

If you are still looking for one, I just released mine: http://github.com/weixiyen/jquery-filedrop

Works for Firefox 3.6 right now. I decided not to do the Chrome hack for now and let Webkit catch up with FileReader() in the next versions of Safari and Chrome.

This plugin is future compatible.

FileReader() is the official standard over something like XHR.getAsBinary() which is deprecated according to mozilla.

It's also the only HTML5 desktop drag+drop plugin out there that I know of which allows you to send extra data along with the file, including data that can be calculated at the time of upload with a callback function.

Best way to represent a fraction in Java?

One very minor improvement could potentially be to save the double value that you're computing so that you only compute it on the first access. This won't be a big win unless you're accessing this number a lot, but it's not overly difficult to do, either.

One additional point might be the error checking you do in the denominator...you automatically change 0 to 1. Not sure if this is correct for your particular application, but in general if someone is trying to divide by 0, something is very wrong. I'd let this throw an exception (a specialized exception if you feel it's needed) rather than change the value in a seemingly arbitrary way that isn't known to the user.

In constrast with some other comments, about adding methods to add subtract, etc...since you didn't mention needing them, I'm assuming you don't. And unless you're building a library that is really going to be used in many places or by other people, go with YAGNI (you ain't going to need it, so it shouldn't be there.)

SQL Server query to find all permissions/access for all users in a database

Due to low rep can't reply with this to the people asking to run this on multiple databases/SQL Servers.

Create a registered server group and query across them all us the following and just cursor through the databases:

--Make sure all ' are doubled within the SQL string.

DECLARE @dbname VARCHAR(50)   
DECLARE @statement NVARCHAR(max)

DECLARE db_cursor CURSOR 
LOCAL FAST_FORWARD
FOR  
SELECT name
FROM MASTER.dbo.sysdatabases
where name like '%DBName%'

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @dbname  
WHILE @@FETCH_STATUS = 0  
BEGIN  

SELECT @statement = 'use '+@dbname +';'+ '
/*
Security Audit Report
1) List all access provisioned to a SQL user or Windows user/group directly
2) List all access provisioned to a SQL user or Windows user/group through a database or application role
3) List all access provisioned to the public role

Columns Returned:
UserType        : Value will be either ''SQL User'', ''Windows User'', or ''Windows Group''.
                  This reflects the type of user/group defined for the SQL Server account.
DatabaseUserName: Name of the associated user as defined in the database user account.  The database user may not be the
                  same as the server user.
LoginName       : SQL or Windows/Active Directory user account.  This could also be an Active Directory group.
Role            : The role name.  This will be null if the associated permissions to the object are defined at directly
                  on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType  : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
                  DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ObjectType      : Type of object the user/role is assigned permissions on.  Examples could include USER_TABLE,
                  SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
Schema          : Name of the schema the object is in.
ObjectName      : Name of the object that the user/role is assigned permissions on.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ColumnName      : Name of the column of the object that the user/role is assigned permissions on. This value
                  is only populated if the object is a table, view or a table value function.
*/

    --1) List all access provisioned to a SQL user or Windows user/group directly
    SELECT
        [UserType] = CASE princ.[type]
                         WHEN ''S'' THEN ''SQL User''
                         WHEN ''U'' THEN ''Windows User''
                         WHEN ''G'' THEN ''Windows Group''
                     END,
        [DatabaseUserName] = princ.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = NULL,
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Database user
        sys.database_principals            AS princ
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = princ.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = princ.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        princ.[type] IN (''S'',''U'',''G'')
        -- No need for these system accounts
        AND princ.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')

UNION

    --2) List all access provisioned to a SQL user or Windows user/group through a database or application role
    SELECT
        [UserType] = CASE membprinc.[type]
                         WHEN ''S'' THEN ''SQL User''
                         WHEN ''U'' THEN ''Windows User''
                         WHEN ''G'' THEN ''Windows Group''
                     END,
        [DatabaseUserName] = membprinc.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Role/member associations
        sys.database_role_members          AS members
        --Roles
        JOIN      sys.database_principals  AS roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
        --Role members (database users)
        JOIN      sys.database_principals  AS membprinc ON membprinc.[principal_id] = members.[member_principal_id]
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = membprinc.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        membprinc.[type] IN (''S'',''U'',''G'')
        -- No need for these system accounts
        AND membprinc.[name] NOT IN (''sys'', ''INFORMATION_SCHEMA'')

UNION

    --3) List all access provisioned to the public role, which everyone gets by default
    SELECT
        [UserType]         = ''{All Users}'',
        [DatabaseUserName] = ''{All Users}'',
        [LoginName]        = ''{All Users}'',
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Roles
        sys.database_principals            AS roleprinc
        --Role permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        --All objects
        JOIN      sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        roleprinc.[type] = ''R''
        AND roleprinc.[name] = ''public''
        AND obj.[is_ms_shipped] = 0

ORDER BY
    [UserType],
    [DatabaseUserName],
    [LoginName],
    [Role],
    [Schema],
    [ObjectName],
    [ColumnName],
    [PermissionType],
    [PermissionState],
    [ObjectType]
'
exec sp_executesql @statement

FETCH NEXT FROM db_cursor INTO @dbname  
END  
CLOSE db_cursor  
DEALLOCATE db_cursor 

This thread massively helped me thanks everyone!

How to programmatically send SMS on the iPhone?

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    UIImage *ui =resultimg.image;
    pasteboard.image = ui;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
}

How to install gem from GitHub source?

Bundler allows you to use gems directly from git repositories. In your Gemfile:

# Use the http(s), ssh, or git protocol
gem 'foo', git: 'https://github.com/dideler/foo.git'
gem 'foo', git: '[email protected]:dideler/foo.git'
gem 'foo', git: 'git://github.com/dideler/foo.git'

# Specify a tag, ref, or branch to use
gem 'foo', git: '[email protected]:dideler/foo.git', tag: 'v2.1.0'
gem 'foo', git: '[email protected]:dideler/foo.git', ref: '4aded'
gem 'foo', git: '[email protected]:dideler/foo.git', branch: 'development'

# Shorthand for public repos on GitHub (supports all the :git options)
gem 'foo', github: 'dideler/foo'

For more info, see https://bundler.io/v2.0/guides/git.html

Recursively list all files in a directory including files in symlink directories

I knew tree was an appropriate, but I didn't have tree installed. So, I got a pretty close alternate here

find ./ | sed -e 's/[^-][^\/]*\//--/g;s/--/ |-/'

How to normalize a NumPy array to within a certain range?

You can also rescale using sklearn. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records.

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

The keyword arguments axis, with_mean, with_std are self explanatory, and are shown in their default state. The argument copy performs the operation in-place if it is set to False. Documentation here.

Cocoa Autolayout: content hugging vs content compression resistance priority

Let's say you have a button with the text, "Click Me". What width should that button be?

First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.

Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [          Click Me          ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.