Programs & Examples On #Int

A data type that represents an integer. An integer is a whole number that can be negative, positive, or zero. (i.e. ...-2, -1, 0, 1, 2...) Use this tag for questions about using, storing, or manipulating integers.

Converting a column within pandas dataframe from int to string

Warning: Both solutions given ( astype() and apply() ) do not preserve NULL values in either the nan or the None form.

import pandas as pd
import numpy as np

df = pd.DataFrame([None,'string',np.nan,42], index=[0,1,2,3], columns=['A'])

df1 = df['A'].astype(str)
df2 =  df['A'].apply(str)

print df.isnull()
print df1.isnull()
print df2.isnull()

I believe this is fixed by the implementation of to_string()

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))

This would work, if your are trying to Sum up a list.

How to check if an integer is within a range of numbers in PHP?

using a switch case

    switch ($num){

        case ($num>= $value1 && $num<= $value2): 
            echo "within range 1";
        case ($num>= $value3 && $num<= $value4): 
            echo "within range 2";

        default: //default
            echo "within no range";

Convert char array to single int?

Ascii string to integer conversion is done by the atoi() function.

Java Round up Any Number

Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .

double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );

Output : 

Function stoi not declared

The answers above are correct, but not well explained.

g++ -std=c++11 my_cpp_code.cpp

Add -std=c++11 to your compiler options since you are most likely using an older version of debian or ubuntu which is not using by default the new c++11 standard of g++/gcc. I had the same problem on Debian Wheezy.

shows in really small writing to the right in green that c++11 is required.

How to take the nth digit of a number in python

I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.

(My use-case was slightly different, I wanted to get all digits in the number.)

The string approach gave:

         10000002 function calls in 1.113 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.113    0.000    1.113    0.000
        1    0.000    0.000    0.000    0.000
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

While the modular arithmetic approach gave:

         10000002 function calls in 1.102 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
 10000000    1.102    0.000    1.102    0.000
        1    0.000    0.000    0.000    0.000
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

There were 10^7 tests run with a max number size less than 10^28.

Code used for reference:

def get_digits_str(num):
    for n_str in str(num):
        yield int(n_str)

def get_digits_mod(num, radix=10):

    remaining = num
    yield remaining % radix

    while remaining := remaining // radix:
        yield remaining % radix

if __name__ == '__main__':

    import cProfile
    import random

    random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]

    with cProfile.Profile() as str_profiler:
        for rand_num in random_inputs:


    with cProfile.Profile() as mod_profiler:
        for rand_num in random_inputs:


Determine if a String is an Integer in Java

You want to use the Integer.parseInt(String) method.

  int num = Integer.parseInt(str);
  // is an integer!
} catch (NumberFormatException e) {
  // not an integer!

Javascript String to int conversion

JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:

var numberAsInt = parseInt(number, 10);  
// Second arg is radix, 10 is decimal.

If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.

How do I convert from int to Long in Java?

Note that there is a difference between a cast to long and a cast to Long. If you cast to long (a primitive value) then it should be automatically boxed to a Long (the reference type that wraps it).

You could alternatively use new to create an instance of Long, initializing it with the int value.

Increment a Integer's int value?

You can use IntHolder as mutable alternative to Integer. But does it worth?

Converting EditText to int? (Android)

You can use like this

 EditText dollar=(EditText) findViewById(;
 int rupees=Integer.parseInt( dollar.getText().toString());

Rounding integer division (instead of truncating)

The following correctly rounds the quotient to the nearest integer for both positive and negative operands WITHOUT floating point or conditional branches (see assembly output below). Assumes N-bit 2's complement integers.

#define ASR(x) ((x) < 0 ? -1 : 0)  // Compiles into a (N-1)-bit arithmetic shift right
#define ROUNDING(x,y) ( (y)/2 - (ASR((x)^(y)) & (y)))

int RoundedQuotient(int x, int y)
   return (x + ROUNDING(x,y)) / y ;

The value of ROUNDING will have the same sign as the dividend (x) and half the magnitude of the divisor (y). Adding ROUNDING to the dividend thus increases its magnitude before the integer division truncates the resulting quotient. Here's the output of the gcc compiler with -O3 optimization for a 32-bit ARM Cortex-M4 processor:

RoundedQuotient:                // Input parameters: r0 = x, r1 = y
    eor     r2, r1, r0          // r2 = x^y
    and     r2, r1, r2, asr #31 // r2 = ASR(x^y) & y
    add     r3, r1, r1, lsr #31 // r3 = (y < 0) ? y + 1 : y
    rsb     r3, r2, r3, asr #1  // r3 = y/2 - (ASR(x^y) & y)
    add     r0, r0, r3          // r0 = x + (y/2 - (ASR(x^y) & y)
    sdiv    r0, r0, r1          // r0 = (x + ROUNDING(x,y)) / y
    bx      lr                  // Returns r0 = rounded quotient

How to check whether input value is integer or float?

Do this to distinguish that.

If for example your number is 3.1214 and stored in num but you don't know kind of num:

num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
  // num is a integer
  // num is float

In this example we see that num is not integer.

How can I divide two integers to get a double?

var result = decimal.ToDouble(decimal.Divide(5, 2));

How can I write these variables into one line of code in C#?

You can do pretty much the same as in JavaScript. Try this:

Console.WriteLine(mon + "." + da + "." + yer);

Or you can use WriteLine as if it were a string.Format statement by doing:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);

which is equivalent to:

string.Format("{0}.{1}.{2}", mon, da, yer);

The number of parameters can be infinite, just make sure you correctly index those numbers (starting at 0).

Splitting String and put it on int array

For input 1,2,3,4,5 the input is of length 9. 9/2 = 4 in integer math, so you're only storing the first four variables, not all 5.

Even if you fixed that, it would break horribly if you passed in an input of 10,11,12,13

It would work (by chance) if you used 1,2,3,4,50 for an input, strangely enough :-)

You would be much better off doing something like this

String[] strArray = input.split(",");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);

For future reference, when you get an error, I highly recommend posting it with the code. You might not have someone with a jdk readily available to compile the code to debug it! :)

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Integer.toString calls the static method in the class Integer. It does not need an instance of Integer.

If you call new Integer(i) you create an instance of type Integer, which is a full Java object encapsulating the value of your int. Then you call the toString method on it to ask it to return a string representation of itself.

If all you want is to print an int, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).

If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int.

%i or %d to print integer in C using printf()?

d and i conversion specifiers behave the same with fprintf but behave differently for fscanf.

As some other wrote in their answer, the idiomatic way to print an int is using d conversion specifier.

Regarding i specifier and fprintf, C99 Rationale says that:

The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.

php string to int

You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

Java: parse int value from a char

String element = "el5";
int x = element.charAt(2) - 48;

Subtracting ascii value of '0' = 48 from char

Converting String to Int with Swift

About int() and Swift 2.x: if you get a nil value after conversion check if you try to convert a string with a big number (for example: 1073741824), in this case try:

let bytesInternet : Int64 = Int64(bytesInternetString)!

Rounding a double to turn it into an int (java)

Rounding double to the "nearest" integer like this:

1.4 -> 1

1.6 -> 2

-2.1 -> -2

-1.3 -> -1

-1.5 -> -2

private int round(double d){
    double dAbs = Math.abs(d);
    int i = (int) dAbs;
    double result = dAbs - (double) i;
        return d<0 ? -i : i;            
        return d<0 ? -(i+1) : i+1;          

You can change condition (result<0.5) as you prefer.

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.


Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

What is the size of column of int(11) in mysql in bytes?

What is the size of column of int(11) in mysql in bytes?

(11) - this attribute of int data type has nothing to do with size of column. It is just the display width of the integer data type. From Numeric Type Attributes:

MySQL supports an extension for optionally specifying the display width of integer data types in parentheses following the base keyword for the type. For example, INT(4) specifies an INT with a display width of four digits.

How can I convert a std::string to int?

1. std::stoi

std::string str = "10";  
int number = std::stoi(str); 

2. string streams

std::string str = "10";  
int number;  
std::istringstream(str) >> number

3. boost::lexical_cast

#include <boost/lexical_cast.hpp>
std::string str = "10";  
int number;
    number = boost::lexical_cast<int>(str);
    std::cout << number << std::endl;
catch (boost::bad_lexical_cast const &e) // bad input
    std::cout << "error" << std::endl;

4. std::atoi

std::string str = "10";
int number = std::atoi(str.c_str()); 

5. sscanf()

 std::string str = "10";
 int number;
 if (sscanf(str .c_str(), "%d", &number) == 1) 
     std::cout << number << '\n';
     std::cout << "Bad Input";

How to convert NUM to INT in R?

Use as.integer:

x <- runif(5, 0, 100)
[1] 26.55087 37.21239 57.28534 90.82078 20.16819

[1] 26 37 57 90 20

Test for class:

xx <- as.integer(x)
 int [1:5] 26 37 57 90 20

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:


Update: why not - the character array is not null terminated. Doh!

Java Array Sort descending?

public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if (array[i] >= array[j]) {
                double x = array[i];
                array[i] = array[j];
                array[j] = x;
    return array;

just use this method to sort an array of type double in descending order, you can use it to sort arrays of any other types(like int, float, and etc) just by changing the "return type", the "argument type" and the variable "x" type to the corresponding type. you can also change ">=" to "<=" in the if condition to make the order ascending.

How to elegantly check if a number is within a range?

How about something like this?

if (theNumber.isBetween(low, high, IntEx.Bounds.INCLUSIVE_INCLUSIVE))

with the extension method as follows (tested):

public static class IntEx
    public enum Bounds 

    public static bool isBetween(this int theNumber, int low, int high, Bounds boundDef)
        bool result;
        switch (boundDef)
            case Bounds.INCLUSIVE_INCLUSIVE:
                result = ((low <= theNumber) && (theNumber <= high));
            case Bounds.INCLUSIVE_EXCLUSIVE:
                result = ((low <= theNumber) && (theNumber < high));
            case Bounds.EXCLUSIVE_INCLUSIVE:
                result = ((low < theNumber) && (theNumber <= high));
            case Bounds.EXCLUSIVE_EXCLUSIVE:
                result = ((low < theNumber) && (theNumber < high));
                throw new System.ArgumentException("Invalid boundary definition argument");
        return result;

Java - Convert integer to string

Integer class has static method toString() - you can use it:

int i = 1234;
String str = Integer.toString(i);

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

Java : Sort integer array without using Arrays.sort()

Simple way :

int a[]={6,2,5,1};
             int temp;
             for(int i=0;i<a.length-1;i++){
                 for(int j=0;j<a.length-1;j++){
                     if(a[j] > a[j+1]){   // use < for Descending order
                         temp = a[j+1];
                         a[j+1] = a[j];

    [6, 2, 5, 1]
    [1, 2, 5, 6]

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

How to check whether a int is not null or empty?

int variables can't be null

If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE). Try to plug your own converter.

How do I convert a String to an int in Java?

The two main ways to do this are using the method valueOf() and method parseInt() of the Integer class.

Suppose you are given a String like this

String numberInString = "999";

Then you can convert it into integer by using

int numberInInteger = Integer.parseInt(numberInString);

And alternatively, you can use

int numberInInteger = Integer.valueOf(numberInString);

But the thing here is, the method Integer.valueOf() has the following implementation in Integer class:

public static Integer valueOf(String var0, int var1) throws NumberFormatException {
    return parseInt(var0, var1);

As you can see, the Integer.valueOf() internally calls Integer.parseInt() itself. Also, parseInt() returns an int, and valueOf() returns an Integer

How to convert string to integer in C#

int myInt = System.Convert.ToInt32(myString);

As several others have mentioned, you can also use int.Parse() and int.TryParse().

If you're certain that the string will always be an int:

int myInt = int.Parse(myString);

If you'd like to check whether string is really an int first:

int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
    int plusOne = myInt + 1;

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
    print("That is an invalid input. Restarting attribute selection.")

Converting a double to an int in Javascript without rounding

Use parseInt().

var num = 2.9
console.log(parseInt(num, 10)); // 2

You can also use |.

var num = 2.9
console.log(num | 0); // 2

What is size_t in C?

size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.

When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, following program would definitely give the unexpected result:

// C program to demonstrate that size_t or
// any unsigned int type should be used 
// carefully when used in a loop

int main()
const size_t N = 10;
int a[N];

// This is fine
for (size_t n = 0; n < N; ++n)
a[n] = n;

// But reverse cycles are tricky for unsigned 
// types as can lead to infinite loop
for (size_t n = N-1; n >= 0; --n)
printf("%d ", a[n]);

Infinite loop and then segmentation fault

How to concatenate a std::string and an int?

Common Answer: itoa()

This is bad. itoa is non-standard, as pointed out here.

What range of values can integer types store in C++

No, only part of ten digits number can be stored in a unsigned long int whose valid range is 0 to 4,294,967,295 . you can refer to this:

How do I limit the number of decimals printed for a double?

Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.

 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

 public static void main(String[] args)

  public static void computeShippingCost()
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (;
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;

   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

     Formatter fmt = new Formatter();
     fmt.format("%.2f", shippingCost);

   System.out.print("$" + fmt);



How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;

What's the best way to check if a String represents an integer in Java?

This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, as pointed out in danatel's comment):


Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base Exception class rather than NumberFormatException).

Convert all strings in a list to int

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1


>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]


def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

Convert char to int in C#

char c = '1';
int i = (int)(c-'0');

and you can create a static method out of it:

static int ToInt(this char c)
    return (int)(c - '0');

What is the maximum float in Python?

For all practical purposes, and with no import at all, one can use:

x = float("inf")

More detail on this related question: How can I represent an infinite number in Python?

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Python float to int conversion

>>> x = 2.51
>>> x*100

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library :),

Convert bytes to int?

int.from_bytes( bytes, byteorder, *, signed=False )

doesn't work with me I used function from this website, it works well

def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result

def int_to_bytes(value, length):
    result = []
    for i in range(0, length):
        result.append(value >> (i * 8) & 0xff)
    return result

How can I convert a string to an int in Python?


    if option == str(1):
        numberA = int(raw_input("enter first number. "))
        numberB= int(raw_input("enter second number. "))
        print " "
        print addition(numberA, numberB)
     etc etc etc

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
    int useconds = atoi(argv[1]); 

What is the difference between Integer and int in Java?

int is a primitive data type while Integer is a Reference or Wrapper Type (Class) in Java.

after java 1.5 which introduce the concept of autoboxing and unboxing you can initialize both int or Integer like this.

int a= 9
Integer a = 9 // both valid After Java 1.5.

why Integer.parseInt("1"); but not int.parseInt("1"); ??

Integer is a Class defined in jdk library and parseInt() is a static method belongs to Integer Class

So, Integer.parseInt("1"); is possible in java. but int is primitive type (assume like a keyword) in java. So, you can't call parseInt() with int.

How to convert int to float in C?

This should give you the result you want.

double total = 0;
int number = 0;
float percentage = number / total * 100

Note that the first operand is a double

Converting an int to a binary string representation in Java?

This should be quite simple with something like this :

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
        number = number / 2;

    return sb.reverse().toString();


Leading zeros for Int in Swift

Swift 5

@imanuo answers is already great, but if you are working with an application full of number, you can consider an extension like this:

extension String {

    init(withInt int: Int, leadingZeros: Int = 2) {
        self.init(format: "%0\(leadingZeros)d", int)

    func leadingZeros(_ zeros: Int) -> String {
        if let int = Int(self) {
            return String(withInt: int, leadingZeros: zeros)
        print("Warning: \(self) is not an Int")
        return ""

In this way you can call wherever:

String(withInt: 3) 
// prints 03

String(withInt: 23, leadingZeros: 4) 
// prints 0023

// prints 42

// prints 054

How to convert from int to string in objective c: example code

The commented out version is the more correct way to do this.

If you use the == operator on strings, you're comparing the strings' addresses (where they're allocated in memory) rather than the values of the strings. This is very occasional useful (it indicates you have the exact same string object), but 99% of the time you want to compare the values, which you do like so:

if([myT isEqualToString:@"10"] || [myT isEqualToString:@"11"] || [myT isEqualToString:@"12"])

Pandas: Subtracting two date columns and the result being an integer

You can use datetime module to help here. Also, as a side note, a simple date subtraction should work as below:

import datetime as dt
import numpy as np
import pandas as pd

#Assume we have df_test:
In [222]: df_test
   first_date second_date
0  2016-01-31  2015-11-19
1  2016-02-29  2015-11-20
2  2016-03-31  2015-11-21
3  2016-04-30  2015-11-22
4  2016-05-31  2015-11-23
5  2016-06-30  2015-11-24
6         NaT  2015-11-25
7         NaT  2015-11-26
8  2016-01-31  2015-11-27
9         NaT  2015-11-28
10        NaT  2015-11-29
11        NaT  2015-11-30
12 2016-04-30  2015-12-01
13        NaT  2015-12-02
14        NaT  2015-12-03
15 2016-04-30  2015-12-04
16        NaT  2015-12-05
17        NaT  2015-12-06

In [223]: df_test['Difference'] = df_test['first_date'] - df_test['second_date'] 

In [224]: df_test
   first_date second_date  Difference
0  2016-01-31  2015-11-19     73 days
1  2016-02-29  2015-11-20    101 days
2  2016-03-31  2015-11-21    131 days
3  2016-04-30  2015-11-22    160 days
4  2016-05-31  2015-11-23    190 days
5  2016-06-30  2015-11-24    219 days
6         NaT  2015-11-25         NaT
7         NaT  2015-11-26         NaT
8  2016-01-31  2015-11-27     65 days
9         NaT  2015-11-28         NaT
10        NaT  2015-11-29         NaT
11        NaT  2015-11-30         NaT
12 2016-04-30  2015-12-01    151 days
13        NaT  2015-12-02         NaT
14        NaT  2015-12-03         NaT
15 2016-04-30  2015-12-04    148 days
16        NaT  2015-12-05         NaT
17        NaT  2015-12-06         NaT

Now, change type to datetime.timedelta, and then use the .days method on valid timedelta objects.

In [226]: df_test['Diffference'] = df_test['Difference'].astype(dt.timedelta).map(lambda x: np.nan if pd.isnull(x) else x.days)

In [227]: df_test
   first_date second_date  Difference  Diffference
0  2016-01-31  2015-11-19     73 days           73
1  2016-02-29  2015-11-20    101 days          101
2  2016-03-31  2015-11-21    131 days          131
3  2016-04-30  2015-11-22    160 days          160
4  2016-05-31  2015-11-23    190 days          190
5  2016-06-30  2015-11-24    219 days          219
6         NaT  2015-11-25         NaT          NaN
7         NaT  2015-11-26         NaT          NaN
8  2016-01-31  2015-11-27     65 days           65
9         NaT  2015-11-28         NaT          NaN
10        NaT  2015-11-29         NaT          NaN
11        NaT  2015-11-30         NaT          NaN
12 2016-04-30  2015-12-01    151 days          151
13        NaT  2015-12-02         NaT          NaN
14        NaT  2015-12-03         NaT          NaN
15 2016-04-30  2015-12-04    148 days          148
16        NaT  2015-12-05         NaT          NaN
17        NaT  2015-12-06         NaT          NaN

Hope that helps.

How can I convert a char to int in Java?

You can use static methods from Character class to get Numeric value from char.

char x = '9';

if (Character.isDigit(x)) { // Determines if the specified character is a digit.
    int y = Character.getNumericValue(x); //Returns the int value that the 
                                          //specified Unicode character represents.

How do you append an int to a string in C++?

cout << text << " " << i << endl;

Get int value from enum in C#

On a related note, if you want to get the int value from System.Enum, then given e here:

Enum e = Question.Role;

You can use:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

The last two are plain ugly. I prefer the first one.

Convert hex string (char []) to int?

Try below block of code, its working for me.

char *p = "0x820";
uint16_t intVal;
sscanf(p, "%x", &intVal);

printf("value x: %x - %d", intVal, intVal);

Output is:

value x: 820 - 2080

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

How to round a Double to the nearest Int in swift?

To round a double to the nearest integer, just use round().

var x = 3.7
x.round() // x = 4.0

If you don't want to modify the original value, then use rounded():

let x = 3.7
let y = x.rounded() // y = 4.0. x = 3.7

As one might expect (or might not), a number like 3.5 is rounded up and a number like -3.5 is rounded down. If you need different rounding behavior than that, you can use one of the rounding rules. For example:

var x = 3.7
x.round(.towardZero) // 3.0

If you need an actual Int then just cast it to one (but only if you are certain that the Double won't be greater than Int.max):

let myInt = Int(myDouble.rounded())


  • This answer is completely rewritten. My old answer dealt with the C math functions like round, lround, floor, and ceil. However, now that Swift has this functionality built in, I can no longer recommend using those functions. Thanks to @dfri for pointing this out to me. Check out @dfri's excellent answer here. I also did something similar for rounding a CGFloat.

Is the size of C "int" 2 bytes or 4 bytes?

The only guarantees are that char must be at least 8 bits wide, short and int must be at least 16 bits wide, and long must be at least 32 bits wide, and that sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) (same is true for the unsigned versions of those types).

int may be anywhere from 16 to 64 bits wide depending on the platform.

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:


and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

Easiest way to convert int to string in C++

You use a counter type of algorithm to convert to a string. I got this technique from programming Commodore 64 computers. It is also good for game programming.

  • You take the integer and take each digit that is weighted by powers of 10. So assume the integer is 950.

    • If the integer equals or is greater than 100,000 then subtract 100,000 and increase the counter in the string at ["000000"];
      keep doing it until no more numbers in position 100,000. Drop another power of ten.

    • If the integer equals or is greater than 10,000 then subtract 10,000 and increase the counter in the string at ["000000"] + 1 position;
      keep doing it until no more numbers in position 10,000.

  • Drop another power of ten

  • Repeat the pattern

I know 950 is too small to use as an example, but I hope you get the idea.

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

Any of the following will work:

s = "true"

(s == 'true').real

(s == 'false').real

(s == 'true').conjugate()    

(s == '').conjugate()

(s == 'true').__int__()

(s == 'opal').__int__()    

def as_int(s):
    return (s == 'true').__int__()

>>>> as_int('false')
>>>> as_int('true')

Android: converting String to int

You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected). Try change.

int NUM=null;

How to check if an integer is within a range?

There is no builtin function, but you can easily achieve it by calling the functions min() and max() appropriately.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

Convert boolean to int in Java

import org.apache.commons.lang3.BooleanUtils;
boolean x = true;   
int y= BooleanUtils.toInteger(x);

How to Convert Int to Unsigned Byte and Back

in java 7

public class Main {
    public static void main(String[] args) {
        byte b =  -2;
        int i = 0 ;
        i = ( b & 0b1111_1111 ) ;

result : 254

Convert int to char in java

In java a char is an int. Your first snippet prints out the character corresponding to the value of 1 in the default character encoding scheme (which is probably Unicode). The Unicode character U+0001 is a non-printing character, which is why you don't see any output.

If you want to print out the character '1', you can look up the value of '1' in the encoding scheme you are using. In Unicode this is 49 (the same as ASCII). But this will only work for digits 0-9.

You might be better off using a String rather than a char, and using Java's built-in toString() method:

int a = 1;
String b = toString(a);

This will work whatever your system encoding is, and will work for multi-digit numbers.

ObjectiveC Parse Integer from String

You can just convert the string like that [str intValue] or [str integerValue]

integerValue Returns the NSInteger value of the receiver’s text.

  • (NSInteger)integerValue Return Value The NSInteger value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.

for more information refer here

How to set null value to int in c#?

 public static int? Timesaday { get; set; } = null;


 public static Nullable<int> Timesaday { get; set; }


 public static int? Timesaday = null;


 public static int? Timesaday

or just

 public static int? Timesaday { get; set; } 

    static void Main(string[] args)

    Console.WriteLine(Timesaday == null);

     //you also can check using 


The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

casting int to char using C++ style casting

reinterpret_cast cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:

Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.

This conversion is not listed in that section. Even this is invalid:

long l = reinterpret_cast<long>(i)

static_cast is the one which has to be used here. See this and this SO questions.

Convert unsigned int to signed int C

I know it's an old question, but it's a good one, so how about this?

unsigned short int x = 65529U;
short int y = *(short int*)&x;

printf("%d\n", y);

How can I read inputs as numbers?

for i in range(n):

the for loop shall run 'n' number of times . the second 'n' is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.

Convert int to string?

string myString = myInt.ToString();

How do you convert a C++ string to an int?

Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.

Am I just missing the point here?

MySQL integer field is returned as string in PHP

My solution is to pass the query result $rs and get a assoc array of the casted data as the return:

function cast_query_results($rs) {
    $fields = mysqli_fetch_fields($rs);
    $data = array();
    $types = array();
    foreach($fields as $field) {
        switch($field->type) {
            case 3:
                $types[$field->name] = 'int';
            case 4:
                $types[$field->name] = 'float';
                $types[$field->name] = 'string';
    while($row=mysqli_fetch_assoc($rs)) array_push($data,$row);
    for($i=0;$i<count($data);$i++) {
        foreach($types as $name => $type) {
            settype($data[$i][$name], $type);
    return $data;

Example usage:

$dbconn = mysqli_connect('localhost','user','passwd','tablename');
$rs = mysqli_query($dbconn, "SELECT * FROM Matches");
$matches = cast_query_results($rs);
// $matches is now a assoc array of rows properly casted to ints/floats/strings

C char* to int conversion

atoi can do that for you


char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

How can I cast int to enum?

If you're ready for the 4.0 .NET Framework, there's a new Enum.TryParse() function that's very useful and plays well with the [Flags] attribute. See Enum.TryParse Method (String, TEnum%)

c++ parse int from string

You can use istringstream.

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;

How to cast or convert an unsigned int to int in C?

If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.

How to check if an int is a null

In Java there isn't Null values for primitive Data types. If you need to check Null use Integer Class instead of primitive type. You don't need to worry about data type difference. Java converts int primitive type data to Integer. When concerning about the memory Integer takes more memory than int. But the difference of memory allocation, nothing to be considered.

In this case you must use Inter instead of int

Try below snippet and see example for more info,

Integer id;
String name;

//Refer this example
    Integer val = 0;


if (val != null){
System.out.println("value is not null");


Also you can assign Null as below,

val = null;

Unsupported operand type(s) for +: 'int' and 'str'


str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))


change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

How to convert float to int with Java

As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.

Not dependent on Java Math.round() types

Checking if float is an integer

stdlib float modf (float x, float *ipart) splits into two parts, check if return value (fractional part) == 0.

C++ int to byte array

Int to byte and vice versa.

unsigned char bytes[4];
unsigned long n = 1024;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

int num = 0;
for(int i = 0; i < 4; i++)
 num <<= 8;
 num |= bytes[i];

printf("number %d",num);

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

How do I convert a decimal to an int in C#?

int i = (int)d;

will give you the number rounded down.

If you want to round to the nearest even number (i.e. >.5 will round up) you can use

int i = (int)Math.Round(d, MidpointRounding.ToEven);

In general you can cast between all the numerical types in C#. If there is no information that will be lost during the cast you can do it implicitly:

int i = 10;
decimal d = i;

though you can still do it explicitly if you wish:

int i = 10;
decimal d = (decimal)i;

However, if you are going to be losing information through the cast you must do it explicitly (to show you are aware you may be losing information):

decimal d = 10.5M;
int i = (int)d;

Here you are losing the ".5". This may be fine, but you must be explicit about it and make an explicit cast to show you know you may be losing the information.

Quickest way to convert a base 10 number to any base in .NET?

I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

Public Class BaseNumber

    Private _CharacterArray As List(Of Char)

    Private _BaseXNumber As String
    Private _Base10Number As Double?

    Private NumberBaseLow As Integer
    Private NumberBaseHigh As Integer

    Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator

    Public Sub UseCapsLetters()
        TrySetBaseSet(65, 90)
    End Sub

    Public Function GetCharacterArray() As List(Of Char)
        Return _CharacterArray
    End Function

    Public Sub SetCharacterArray(CharacterArray As String)
        _CharacterArray = New List(Of Char)

    End Sub

    Public Sub SetCharacterArray(CharacterArray As List(Of Char))
        _CharacterArray = CharacterArray
    End Sub

    Public Sub SetNumber(Value As String)
        _BaseXNumber = Value
        _Base10Number = Nothing
    End Sub

    Public Sub SetNumber(Value As Double)
        _Base10Number = Value
        _BaseXNumber = Nothing
    End Sub

    Public Function GetBaseXNumber() As String
        If _BaseXNumber IsNot Nothing Then
            Return _BaseXNumber
            Return ToBaseString()
        End If
    End Function

    Public Function GetBase10Number() As Double
        If _Base10Number IsNot Nothing Then
            Return _Base10Number
            Return ToBase10()
        End If
    End Function

    Private Sub TrySetBaseSet(Values As List(Of Char))
        For Each value As Char In _BaseXNumber
            If Not Values.Contains(value) Then
                Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
            End If

        _CharacterArray = Values

    End Sub

    Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)

        Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()

        If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
            Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
        End If

        NumberBaseLow = LowValue
        NumberBaseHigh = HighValue

    End Sub

    Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
        If Values Is Nothing Then
            Values = _BaseXNumber.ToList
        End If

        Dim lowestValue As Integer = Convert.ToInt32(Values(0))
        Dim highestValue As Integer = Convert.ToInt32(Values(0))

        Dim currentValue As Integer

        For Each value As Char In Values

            If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
                If currentValue < lowestValue Then
                    currentValue = lowestValue
                End If
            End If

        Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)

    End Function

    Public Sub New(BaseXNumber As String)
        _BaseXNumber = BaseXNumber
    End Sub

    Public Sub New(BaseXNumber As String, NumberBase As Integer)
        Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
    End Sub

    Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
        _BaseXNumber = BaseXNumber
        Me.NumberBaseLow = NumberBaseLow
        Me.NumberBaseHigh = NumberBaseHigh
    End Sub

    Public Sub New(Base10Number As Double)
        _Base10Number = Base10Number
    End Sub

    Private Sub DetermineNumberBase()
        Dim highestValue As Integer

        Dim currentValue As Integer

        For Each value As Char In _BaseXNumber

            currentValue = Convert.ToInt32(value)
            If currentValue > highestValue Then
                highestValue = currentValue
            End If

        NumberBaseHigh = highestValue
        NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest

    End Sub

    Private Function ToBaseString() As String
        Dim Base10Number As Double = _Base10Number

        Dim intPart As Long = Math.Truncate(Base10Number)
        Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")

        Dim intPartString As String = ConvertIntToString(intPart)
        Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")

        Return intPartString & fracPartString

    End Function

    Private Function ToBase10() As Double
        Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
        Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")

        Dim intPart As Long = ConvertStringToInt(intPartString)
        Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
        Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))

        Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)

    End Function

    Private Function ConvertIntToString(ValueToConvert As Long) As String
        Dim result As String = String.Empty
        Dim targetBase As Long = GetEncodingCharsLength()

            result = GetEncodedChar(ValueToConvert Mod targetBase) & result
            ValueToConvert = ValueToConvert \ targetBase
        Loop While ValueToConvert > 0

        Return result
    End Function

    Private Function ConvertStringToInt(ValueToConvert As String) As Long
        Dim result As Long
        Dim targetBase As Integer = GetEncodingCharsLength()
        Dim startBase As Integer = GetEncodingCharsStartBase()

        Dim value As Char
        For x As Integer = 0 To ValueToConvert.Length - 1
            value = ValueToConvert(x)
            result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))

        Return result

    End Function

    Private Function GetEncodedChar(index As Integer) As Char
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray(index)
            Return Convert.ToChar(index + NumberBaseLow)
        End If
    End Function

    Private Function GetDecodedChar(character As Char) As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.IndexOf(character)
            Return Convert.ToInt32(character) - NumberBaseLow
        End If
    End Function

    Private Function GetEncodingCharsLength() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.Count
            Return NumberBaseHigh - NumberBaseLow + 1
        End If
    End Function

    Private Function GetEncodingCharsStartBase() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return GetHighLow.Key
            Return NumberBaseLow
        End If
    End Function
End Class

And now for the code to loop through Excel columns:

    Public Function GetColumnList(DataSheetID As String) As List(Of String)
        Dim workingColumn As New BaseNumber("A")

        Dim listOfPopulatedColumns As New List(Of String)
        Dim countOfEmptyColumns As Integer

        Dim colHasData As Boolean
        Dim cellHasData As Boolean

            colHasData = True
            cellHasData = False
            For r As Integer = 1 To GetMaxRow(DataSheetID)
                cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
            colHasData = colHasData And cellHasData

            'keep trying until we get 4 empty columns in a row
            If colHasData Then
                countOfEmptyColumns = 0
                countOfEmptyColumns += 1
            End If

            'we are already starting with column A, so increment after we check column A
                workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
            Loop Until Not workingColumn.GetBaseXNumber.Contains("@")

        Loop Until countOfEmptyColumns > 3

        Return listOfPopulatedColumns

    End Function

You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

percentage of two int?

If you don't add .0f it will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed :)

float percent = (n * 100.0f) / v;

If you need an integer out of this you can of course cast the float or the double again in integer.

int percent = (int)((n * 100.0f) / v);

If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.

int percent = (n * 100) / v;

If you get NaN is because wathever you do you cannot divide for zero of course... it doesn't make sense.

IntelliJ: Working on multiple projects

Yes, your intuition was good. You shouldn't use three instances of intellij. You can open one Project and add other 'parts' of application as Modules. Add them via project browser, default hotkey is alt+1

How to convert a JSON string to a Map<String, String> with Jackson JSON

Using Google's Gson

Why not use Google's Gson as mentioned in here?

Very straight forward and did the job for me:

HashMap<String,String> map = new Gson().fromJson( yourJsonString, new TypeToken<HashMap<String, String>>(){}.getType());

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Also something that can go wrong: Make sure you exit Docker for Mac (possibly all other kind of docker installations as well).

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

Can a table row expand and close?

It depends on your mark-up, but it can certainly be made to work, I used the following:


  function() {
  $('td p').slideUp();
    $('td h2').click(


      <th>Which Doctor</th>
      <th>Significant companion</th>
      <td><h2>William Hartnell</h2></td>
      <td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
      <td><h2>Patrick Troughton</h2></td>
      <td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
      <td><h2>Jon Pertwee</h2></td>
      <td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>

The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp() as the paragraphs were hidden, and still leave an element, h2 to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.

Demo at JS Bin

As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p elements this would work:

  function() {
  $('td p').slideUp();
    $('td h2').click(

Demo at JS Bin

Count number of rows within each group

You can use by functions as by(df1$Year, df1$Month, count) that will produce a list of needed aggregation.

The output will look like,

df1$Month: Feb
     x freq
1 2012    1
2 2013    1
3 2014    5
df1$Month: Jan
     x freq
1 2012    5
2 2013    2
df1$Month: Mar
     x freq
1 2012    1
2 2013    3
3 2014    2

Resize to fit image in div, and center horizontally and vertically


More info here: Can I Use?

.container {_x000D_
  overflow: hidden;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
.container img {_x000D_
  object-fit: cover;_x000D_
  width: 100%;_x000D_
  min-height: 100%;_x000D_
<div class='container'>_x000D_
    <img src='' />_x000D_

How do I test if a variable does not equal either of two values?

May I suggest trying to use in else if statement in your if/else statement. And if you don't want to run any code that not under any conditions you want you can just leave the else out at the end of the statement. else if can also be used for any number of diversion paths that need things to be a certain condition for each.

if(condition 1){

} else if (condition 2) {

}else {


Running Python from Atom

Download and Install package here:

To execute the python command in atom use the below shortcuts:

For Windows/Linux, it's SHIFT + Ctrl + B OR Ctrl + SHIFT + B

If you're on Mac, press ? + I

Prevent wrapping of span or div

Try this:

.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

Calling a Javascript Function from Console

I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:

function indirect(js) { return eval(js); }

With that function in each module, you can then execute any code in the context of it.

E.g. if you had this import in your module:

import { imported_fn } from "./import.js";

You could then get the results of calling imported_fn from the console by doing this:


Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

ps command doesn't work in docker container

In case you can't install the procps package (don't have proper permissions) you can use /proc directory.

The first few directories (named as numbers) are PIDs of your processes. Inside directories, you can find additional information useful to decipher which process is connected to each PID. For example, you can use the cat command to view "cmdline" file to check which process is connected to PID.

$ ls /proc
1 10 11 ...

$ ls -1 /proc/22

$ cat /proc/22/cmdline 

Changing nav-bar color after scrolling?

How about the Intersection Observer API? This avoids the potential sluggishness from using the scroll event.


<nav class="navbar-fixed-top">Navbar</nav>
  <div class="content">Some content</div>


.navbar-fixed-top--scrolled changes the nav bar background color. It's added to the nav bar when the content div is no longer 100% visible as we scroll down.

.navbar-fixed-top {
  position: sticky;
  top: 0;
  height: 60px;

.navbar-fixed-top--scrolled {
  /* change background-color to whatever you want */
  background-color: grey;


Create the observer to determine when the content div fully intersects with the browser viewport.

The callback function is called:

  • the first time the observer is initially asked to watch the target element
  • when content div is no longer fully visible (due to threshold: 1)
  • when content div becomes fully visible (due to threshold: 1)

isIntersecting indicates whether the content div (the target element) is fully intersecting with the observer's root (the browser viewport by default).

// callback function to be run whenever threshold is crossed in one direction or the other
const callback = (entries, observer) => {
  const entry = entries[0];
  // toggle class depending on if content div intersects with viewport
  const navBar = document.querySelector('.navbar-fixed-top');
  navBar.classList.toggle('navbar-fixed-top--scrolled', !entry.isIntersecting);

// options controls circumstances under which the observer's callback is invoked
const options = {
  // no root provided - by default browser viewport used to check target visibility
  // only detect if target element is fully visible or not
  threshold: [1]

const io = new IntersectionObserver(callback, options);

// observe content div 
const target = document.querySelector('.content');

IntersectionObserver options

The nav bar currently changes background color when the content div starts moving off the screen.

If we want the background to change as soon as the user scrolls, we can use the rootMargin property (top, right, bottom, left) and set the top margin to negative the height of the nav bar (60px in our case).

const options = {
  rootMargin: "-60px 0px 0px 0px",
  threshold: [1]

You can see all the above in action on CodePen. Kevin Powell also has a good explanation on this (Github & YouTube).

What is a reasonable length limit on person "Name" fields?

In the UK, there are a few government standards which deal successfully with the bulk of the UK population -- the Passport Office, the Driver & Vehicle Licensing Agency, the Deed Poll office, and the NHS. They use different standards, obviously.

Changing your name by Deed Poll allows 300 characters;

There is no legal limit on the length of your name, but we impose a limit of 300 characters (including spaces) for your full name.

The NHS uses 70 characters for patient names

Format/length: max an70

The Passport Office allows 30+30 first/last and Driving Licenses (DVLA) is 30 total.

Note that other organisations will have their own restrictions about what they will show on the documents they produce — for HM Passport Office the limit is 30 characters each for your forename and your surname, and for the DVLA the limit is 30 characters in total for your full name.

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:

var filteredCollection = from item in getMyCollection()
                         orderby item.ReportDate
                         select item;

This code is not NULL SAFE, meaning that if getMyCollection() returns a null, you'll get the Value cannot be null. Parameter name: source error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:

var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);

Which obviously will blow up if the starting method returns a null.

To prevent this, you can use a null coalescing operator in your LINQ query like so:

var filteredCollection = from item in getMyCollection() ?? 
                         orderby item.ReportDate
                         select item;

However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()" then it should NEVER return a null array/enumerable/etc. Always always always use an if check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
    std::cout << "Hello World\n";

Can an Android Toast be longer than Toast.LENGTH_LONG?

This text will disappear in 5 seconds.

    final Toast toast = Toast.makeText(getApplicationContext(), "My Text", Toast.LENGTH_SHORT);;

    Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
           public void run() {
    }, 5000); // Change to what you want

Edit: As Itai Spector in comment said it will be shown about 3.5 seconds, So use this code:

    int toastDuration = 5000; // in MilliSeconds
    Toast mToast = Toast.makeText(this, "My text", Toast.LENGTH_LONG);
    CountDownTimer countDownTimer;
    countDownTimer = new CountDownTimer(toastDuration, 1000) {
        public void onTick(long millisUntilFinished) {

        public void onFinish() {

How to change UIPickerView height

Create a view in IB or code. Add your picker as a subview of this view. Resize the view. This is easiest to do in IB. Create constraints from the view to its superview and from the picker to this new view.

Since the Picker curves around it spills out over the top and bottom of the view. You can see in IB when you add top and bottom constraints from the picker to the view it shows a standard space something like 16 points above and below the superview container. Set the view to clip it if you don't want this behaviour (ugly warning).

Here's what it looks like at 96 points high on an iPhone 5. The picker with the spillover is about 130 points high. Pretty skinny!

I'm using this in my project to prevent the picker from spreading out to an unnecessary height. This technique trims it down and forces a tighter spill over. It actually looks slicker to be a bit more compact.

enter image description here

Here's an image of the view showing the spillover.

enter image description here

Here's the IB constraints I added.

enter image description here

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.


How to plot all the columns of a data frame in R

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

enter image description here enter image description here

How can we redirect a Java program console output to multiple files?

You could use a "variable" inside the output filename, for example:



Returns the current system time formatted as yyyyMMdd_HHmm. An optional argument can be used to provide alternative formatting. The argument must be valid pattern for java.util.SimpleDateFormat.

Or you can also use a system_property or an env_var to specify something dynamic (either one needs to be specified as arguments)

Downloading a large file using curl

//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response

How do I correctly use "Not Equal" in MS Access?

In Access, you will probably find a Join is quicker unless your tables are very small:

FROM Table1 
ON Table1.Column1 = Table2.Column1  
WHERE Table2.Column1 Is Null

This will exclude from the list all records with a match in Table2.

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Since I can not add a comment to the marked answer I will just post this here.

In addition to the correct answer you can indeed have this validated. Since this meta tag is only directed for IE all you need to do is add a IE conditional.

<!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

Doing this is just like adding any other IE conditional statement and only works for IE and no other browsers will be affected.

How can I tell if a VARCHAR variable contains a substring?

Instead of LIKE (which does work as other commenters have suggested), you can alternatively use CHARINDEX:

declare @full varchar(100) = 'abcdefg'
declare @find varchar(100) = 'cde'
if (charindex(@find, @full) > 0)
    print 'exists'

Standard Android Button with a different color

I like the color filter suggestion in previous answers from @conjugatedirection and @Tomasz; However, I found that the code provided so far wasn't as easily applied as I expected.

First, it wasn't mentioned where to apply and clear the color filter. It's possible that there are other good places to do this, but what came to mind for me was an OnTouchListener.

From my reading of the original question, the ideal solution would be one that does not involve any images. The accepted answer using custom_button.xml from @emmby is probably a better fit than color filters if that's your goal. In my case, I'm starting with a png image from a UI designer of what the button is supposed to look like. If I set the button background to this image, the default highlight feedback is lost completely. This code replaces that behavior with a programmatic darkening effect.

button.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 0x6D6D6D sets how much to darken - tweak as desired
                setColorFilter(v, 0x6D6D6D);
            // remove the filter when moving off the button
            // the same way a selector implementation would 
            case MotionEvent.ACTION_MOVE:
                Rect r = new Rect();
                if (!r.contains((int) event.getX(), (int) event.getY())) {
                    setColorFilter(v, null);
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                setColorFilter(v, null);
        return false;

    private void setColorFilter(View v, Integer filter) {
        if (filter == null) v.getBackground().clearColorFilter();
        else {
            // To lighten instead of darken, try this:
            // LightingColorFilter lighten = new LightingColorFilter(0xFFFFFF, filter);
            LightingColorFilter darken = new LightingColorFilter(filter, 0x000000);
        // required on Android 2.3.7 for filter change to take effect (but not on 4.0.4)

I extracted this as a separate class for application to multiple buttons - shown as anonymous inner class just to get the idea.

Change tab bar tint color on iOS 7

There is an much easier way to do this.

Just open the file inspector and select a "global tint".

You can also set an app’s tint color in Interface Builder. The Global Tint menu in the Interface Builder Document section of the File inspector lets you open the Colors window or choose a specific color.

Also see:

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

I've solved this. In my case I just changed my configuration. 'hostname' became 'localhost'

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';

Why I cannot cout a string?

You need to reference the cout's namespace std somehow. For instance, insert

using std::cout;
using std::endl;

on top of your function definition, or the file.

Making a POST call instead of GET using urllib2

Try this instead:

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
req = urllib2.Request(url=url,data=data)
content = urllib2.urlopen(req).read()
print content

What is an application binary interface (ABI)?

ABI - Application Binary Interface is about a machine code communication in runtime between two binary parts like - application, library, OS... ABI describes how objects are saved in memory, how functions are called(calling convention), mangling...

A good example of API and ABI is iOS ecosystem with Swift language.

  • Application layer - When you create an application using different languages. For example you can create application using Swift and Objective-C[Mixing Swift and Objective-C]

  • Application - OS layer - runtime - Swift runtime and standard libraries are parts of OS and they should not be included into each bundle(e.g. app, framework). It is the same as like Objective-C uses

  • Library layer - Module Stability case - compile time - you will be able to import a framework which was built with another version of Swift's compiler. It means that it is safety to create a closed-source(pre-build) binary which will be consumed by a different version of compiler( .swiftinterface is used with .swiftmodule) and you will not get

    Module compiled with _ cannot be imported by the _ compiler
  • Library layer - Library Evolution case

    1. Compile time - if a dependency was changed, a client has not to be recompiled.
    2. Runtime - a system library or a dynamic framework can be hot-swapped by a new one.

[API vs ABI]
[Swift Module and Library stability]

Rendering raw html with reactjs

There are now safer methods to render HTML. I covered this in a previous answer here. You have 4 options, the last uses dangerouslySetInnerHTML.

Methods for rendering HTML

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>


    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

kubectl apply vs kubectl create?

We love Kubernetes is because once we give them what we want it goes on to figure out how to achieve it without our any involvement.

"create" is like playing GOD by taking things into our own hands. It is good for local debugging when you only want to work with the POD and not care abt Deployment/Replication Controller.

"apply" is playing by the rules. "apply" is like a master tool that helps you create and modify and requires nothing from you to manage the pods.

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

What exactly do "u" and "r" string flags do, and what are raw string literals?

Unicode string literals

Unicode string literals (string literals prefixed by u) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.

Raw string literals

If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n to your string literal. So when you print the 'hello\nworld' string, the words will be printed on separate lines. That's very handy!

On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:

'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'

In such situations you can just prefix the string literal with the r character like this: r'hello\nworld' and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.

Raw string literals are not completely "raw"?

Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.

From the lexical definition of a string literal:

string     ::=  "'" stringitem* "'"
stringitem ::=  stringchar | escapeseq
stringchar ::=  <any source character except "\" or newline or the quote>
escapeseq  ::=  "\" <any source character>

It is clear that string literals (raw or not) containing a bare quote character: 'hello'world' or ending with a backslash: 'hello world\' are not valid.

Establish a VPN connection in cmd

I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.

****Note that you probably have to run cmd.exe as an administrator for this to work**

So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run

C:\Windows\System32>cd ras

Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.

So to create our temp file run:

C:\Windows\System32\ras>copy con temp.txt

Now it will let you type the contents of the file, which should look like this:

Device=WAN Miniport (IKEv2)

So replace CONNECTION NAME and with the desired connection name and the vpn server address you want.

Make a new line and press Ctrl+Z to finish and save.

Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:

C:\Windows\System32\ras>del temp.txt

Now we can connect to our newly configured VPN server with the following command:

C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword

When we want to disconnect we can run:

C:\Windows\System32\ras>rasdial /DISCONNECT

That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:

Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Windows\system32>cd ras

C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
Device=WAN Miniport (IKEv2)
        1 file(s) copied.

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

C:\Windows\System32\ras>del temp.txt

C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.

C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.


Hope this helps.

How to check Elasticsearch cluster health?

The _cluster/health API can do far more than the typical output that most see with it:

 $ curl -XGET 'localhost:9200/_cluster/health?pretty'

Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.


all the indices health
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    "filebeat-6.5.1-2019.06.11" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    "filebeat-6.5.1-2019.06.12" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    "filebeat-6.5.1-2019.06.13" : {
      "status" : "green",
      "number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0,
      "shards" : {
        "0" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        "1" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        "2" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0

The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.

In Swift how to call method with parameters on GCD main thread?

Swift 2

Using Trailing Closures this becomes:

dispatch_async(dispatch_get_main_queue()) {

Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.

In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t) since dispatch_block_t is type alias for () -> Void - A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async.

Shell script : How to cut part of a string

A perl-solution:

perl -nE 'say $1 if /id=(\d+)/' filename

SQL Server - find nth occurrence in a string

You can use the following function to split the values by a delimiter. It'll return a table and to find the nth occurrence just make a select on it! Or change it a little for it to return what you need instead of the table.

    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
RETURNS @RtnValue table 
    Id int identity(1,1),
    Data nvarchar(100)
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
        Insert Into @RtnValue (data)
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))


how to save and read array of array in NSUserdefaults in swift?

Swift 4.0


let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]    

 //store in user default
 UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")


if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:


As you require the filename with path, enjoy!

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on = and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and =
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on =
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
  tab3.desc = "XYZ" and =

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

Add IIS 7 AppPool Identities as SQL Server Logons

The "IIS APPPOOL\AppPoolName" will work, but as mentioned previously, it does not appear to be a valid AD name so when you search for it in the "Select User or Group" dialog box, it won't show up (actually, it will find it, but it will think its an actual system account, and it will try to treat it as such...which won't work, and will give you the error message about it not being found).

How I've gotten it to work is:

  1. In SQL Server Management Studio, look for the Security folder (the security folder at the same level as the Databases, Server Objects, etc. folders...not the security folder within each individual database)
  2. Right click logins and select "New Login"
  3. In the Login name field, type IIS APPPOOL\YourAppPoolName - do not click search
  4. Fill whatever other values you like (i.e., authentication type, default database, etc.)
  5. Click OK

As long as the AppPool name actually exists, the login should now be created.

TypeError: 'int' object is not subscriptable

You can't do something like that: (int(sumall[0])+int(sumall[1]))

That's because sumall is an int and not a list or dict.

So, summ + sumd will be you're lucky number

Difference between size and length methods?

size() is a method specified in java.util.Collection, which is then inherited by every data structure in the standard library. length is a field on any array (arrays are objects, you just don't see the class normally), and length() is a method on java.lang.String, which is just a thin wrapper on a char[] anyway.

Perhaps by design, Strings are immutable, and all of the top-level Collection subclasses are mutable. So where you see "length" you know that's constant, and where you see "size" it isn't.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

Also, if you set your build target device, the problem will go away when you testing and debugging. The code signed is only need when you trying to deploy your app to an actually physical device fig

I changed mine from "myIphone" to simulator iPhone 6 Plus, and it solves the problem while I'm developing the app.

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
    return 10;

double a[n()]; // n() is a compile time constant expression

Can I restore a single table from a full mysql mysqldump file?

This can be done more easily? This is how I did it:

Create a temporary database (e.g. restore):

mysqladmin -u root -p create restore

Restore the full dump in the temp database:

mysql -u root -p restore < fulldump.sql

Dump the table you want to recover:

mysqldump restore mytable > mytable.sql

Import the table in another database:

mysql -u root -p database < mytable.sql

Extracting specific columns from a data frame

You can subset using a vector of column names. I strongly prefer this approach over those that treat column names as if they are object names (e.g. subset()), especially when programming in functions, packages, or applications.

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset

Note there's no comma (i.e. it's not df[,c("A","B","C")]). That's because df[,"A"] returns a vector, not a data frame. But df["A"] will always return a data frame.

## 'data.frame':    1 obs. of  1 variable:
## $ A: int 1
str(df[,"A"])  # vector
##  int 1

Thanks to David Dorchies for pointing out that df[,"A"] returns a vector instead of a data.frame, and to Antoine Fabri for suggesting a better alternative (above) to my original solution (below).

# subset (original solution--not recommended)
df[,c("A","B","E")]  # returns a data.frame
df[,"A"]             # returns a vector

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

This will fix it:

/usr/bin/java -Djava.awt.headless=true $Your_program

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) - meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

Set Background cell color in PHPExcel

You can easily apply colours on cell and rows.

$sheet->cell(1, function($row) 

$sheet->row(1, ['Col 1', 'Col 2', 'Col 3']); 
$sheet->row(1, function($row) 

Multiple submit buttons in an HTML form

I think this is a esay solution for this. Make Previous button type to button, and a new add onclick attribute in button with value jQuery(this).attr('type','submit');.

So, when the user clicks on the Previous button then its type will be changed to submit and the form will be submitted with Previous button.

  <!-- Put your cursor in this field and press Enter -->
  <input type="text" name="field1" />

  <!-- This is the button that will submit -->
  <input type="button" onclick="jQuery(this).attr('type','submit');" name="prev" value="Previous Page" />

  <!-- But this is the button that I WANT to submit -->
  <input type="submit" name="next" value="Next Page" />

Bootstrap dropdown menu not working (not dropping down when clicked)

Just add both these files after opening of body tag. Keep in mind 'Only after Body tag' any where after body tag. If you add below mentioned files inside body tag then your problems would still be unresolved.

So paste them after or before close of body tag... This works 100%. I've tested and got it working!

<script src=""></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

ipad safari: disable scrolling, and bounce effect?

Similar to angry kiwi I got it to work using height rather than position:

html,body {
  height: 100%;
  overflow: hidden;

  -webkit-overflow-scrolling: touch;

Regular expression for floating point numbers

what you need is:


I escaped the "+" and "-" sign and also grouped the decimal with its following digits since something like "1." is not a valid number.

The changes will allow you to match integers and floats. for example:


java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

How to fix "unable to open stdio.h in Turbo C" error?

First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C instead of F So from OPTION>DIRECTORY change the folder name

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

In Postgres, you can make almost any single value query return a value or null by wrapping it:

SELECT (SELECT <query>) AS value

and hence avoid complexity in the caller.

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

Keeping ASP.NET Session Open / Alive

If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:

public JsonResult KeepSessionAlive() {
    return new JsonResult {Data = "Success"};

, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):

var keepSessionAlive = false;
var keepSessionAliveUrl = null;

function SetupSessionUpdater(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    var container = $("#body");
    container.mousemove(function () { keepSessionAlive = true; });
    container.keydown(function () { keepSessionAlive = true; });

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 5*60*1000);

function KeepSessionAlive() {
    if (keepSessionAlive && keepSessionAliveUrl != null) {
            type: "POST",
            url: keepSessionAliveUrl,
            success: function () { keepSessionAlive = false; }

, and initialize this functionality by calling a JavaScript function:


Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).

Why do we have to specify FromBody and FromUri?

Just addition to above answers ..

[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring

For Ex..

public class GeoPoint
    public double Latitude { get; set; } 
    public double Longitude { get; set; }

public ValuesController : ApiController
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }

Can be called like:


PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
SET level = users.level + 1;

How does true/false work in PHP?

Since I've visited this page several times, I've decided to post an example (loose) comparison test.


""        -> false
"0"       -> false
"1"       -> true
"01"      -> true
"abc"     -> true
"true"    -> true
"false"   -> true
0         -> false
0.1       -> true
1         -> true
1.1       -> true
-42       -> true
"NAN"     -> true
0         -> false
          -> true
null      -> false
true      -> true
false     -> false
[]        -> false
["a"]     -> true
{}        -> true
{}        -> true
{"s":"f"} -> true


class Vegetable {}

class Fruit {
    public $s = "f";

$cases = [
    (float) "NAN",
    new stdClass(),
    new Vegetable(),
    new Fruit(),

echo "<pre>" . PHP_EOL;

foreach ($cases as $case) {
    printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 9, " ", STR_PAD_RIGHT), json_encode( $case == true ));

When a strict (===) comparison is done, everything except true returns false.

Using NSLog for debugging

NSLog(@"%@", digit);

what is shown in console?

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

When do I need to do "git pull", before or after "git add, git commit"?

You want your change to sit on top of the current state of the remote branch. So probably you want to pull right before you commit yourself. After that, push your changes again.

"Dirty" local files are not an issue as long as there aren't any conflicts with the remote branch. If there are conflicts though, the merge will fail, so there is no risk or danger in pulling before committing local changes.

Getting started with OpenCV 2.4 and MinGW on Windows 7

If you installed opencv 2.4.2 then you need to change the -lopencv_core240 to -lopencv_core242

I made the same mistake.

StringBuilder vs String concatenation in toString() in Java

Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.

So for the sake of code readability, use "+".

2 exceptions :

  • multithreaded environment : StringBuffer
  • concatenation in loops : StringBuilder/StringBuffer

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
        memoryStream = new MemoryStream();
    data = memoryStream.ToArray();

Using "-Filter" with a variable

Add double quote

$nameRegex = "chalmw-dm*"

-like "$nameregex" or -like "'$nameregex'"

How to change line-ending settings

If you want to convert back the file formats which have been changed to UNIX Format from PC format.

(1)You need to reinstall tortoise GIT and in the "Line Ending Conversion" Section make sure that you have selected "Check out as is - Check in as is"option.

(2)and keep the remaining configurations as it is.

(3)once installation is done

(4)write all the file extensions which are converted to UNIX format into a text file (extensions.txt).


(5) copy the file into your clone Run the following command in GITBASH

while read -r a;
find . -type f -name "$a" -exec dos2unix {} \;

How to implement zoom effect for image view in android?

I hope you are doing often happens with all when they want to add new functionality in your app then normally they all search for libraries which are not good tactic because you don`t know what kind of code is in that libabry. so I always prefer to fork the libraries and add the useful classes and methods in my application code.

so when I stuck with the same issue, I make lots of much R&D then I find a class which gives the ability to zoomIn ,zoomOut and pinIn and out. so you can see that class here..

so as I told before, it is a single class. so you can put this class anywhere in your projects like utils folder.and put below lines into your XML files like:

        android:transitionName="@string/transition_name_phone" /> 

and you can find that image view in your respected activity, as you did for all views like -:

TouchImageView tv=(TouchImageView)findViewById(; 

that's it for TouchImageView. enjoy our code :)

How to remove the first character of string in PHP?

Exec time for the 3 answers :

Remove the first letter by replacing the case

$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo

Exec time for 1.000.000 tests : 0.39602184295654 sec

Remove the first letter with substr()

$str = "hello";
$str = substr($str, 1);

Exec time for 1.000.000 tests : 5.153294801712 sec

Remove the first letter with ltrim()

$str = "hello";
$str= ltrim ($str,'h');

Exec time for 1.000.000 tests : 5.2393000125885 sec

Remove the first letter with preg_replace()

$str = "hello";
$str = preg_replace('/^./', '', $str);

Exec time for 1.000.000 tests : 6.8543920516968 sec

Creating a config file in PHP

I normally end up creating a single conn.php file that has my database connections. Then i include that file in all files that require database queries.

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
                     0, 0,

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):

Cycles in an Undirected Graph

Actually, depth first (or indeed breadth first) search isn't quite enough. You need a sightly more complex algorithm.

For instance, suppose there is graph with nodes {a,b,c,d} and edges {(a,b),(b,c),(b,d),(d,c)} where an edge (x,y) is an edge from x to y. (looks something like this, with all edges directed downwards.)

    / \ 
  (d)  |
   |   |
    \ /

Then doing depth first search may visit node (a), then (b), then (c), then backtrack to (b), then visit (d), and finally visit (c) again and conclude there is a cycle -- when there isn't. A similar thing happens with breadth first.

What you need to do is keep track of which nodes your in the middle of visiting. In the example above, when the algorithm reaches (d) it has finished visiting (c) but not (a) or (b). So revisiting a finished node is fine, but visiting an unfinished node means you have a cycle. The usual way to do this is colour each node white(not yet visited), grey(visiting descendants) or black(finished visiting).

here is some pseudo code!

define visit(node n):
  if n.colour == grey: //if we're still visiting this node or its descendants
    throw exception("Cycle found")

  n.colour = grey //to indicate this node is being visited
  for node child in n.children():
    if child.colour == white: //if the child is unexplored

  n.colour = black //to show we're done visiting this node

then running visit(root_node) will throw an exception if and only if there is a cycle (initially all nodes should be white).

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
    static void Main() 
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
        Console.WriteLine("DEBUG and VC_V7 are not defined");

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:

    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined

    using System.Diagnostics;
    class Class1 
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");


I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

How to get the first element of an array?

Use this to split character in javascript.

var str = "boy, girl, dog, cat";
var arr = str.split(",");
var fst = arr.splice(0,1).join("");
var rest = arr.join(",");

Get integer value of the current year in Java

As some people answered above:

If you want to use the variable later, better use:

int year;

year = Calendar.getInstance().get(Calendar.YEAR);

If you need the year for just a condition you better use:


For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):

import java.util.Calendar;
import java.util.Scanner;

public static void main (String[] args){

    Scanner scannernumber = new Scanner(;
    int year;

    /*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/

        System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
        year = scannernumber.nextInt();
    }while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));

python exception message capturing

If you want the error class, error message, and stack trace, use sys.exc_info().

Minimal working code with some formatting:

import sys
import traceback

    ans = 1/0
except BaseException as ex:
    # Get current system exception
    ex_type, ex_value, ex_traceback = sys.exc_info()

    # Extract unformatter stack traces as tuples
    trace_back = traceback.extract_tb(ex_traceback)

    # Format stacktrace
    stack_trace = list()

    for trace in trace_back:
        stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" %ex_value)
    print("Stack trace : %s" %stack_trace)

Which gives the following output:

Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\ , Line : 5, Func.Name : <module>, Message : ans = 1/0']

The function sys.exc_info() gives you details about the most recent exception. It returns a tuple of (type, value, traceback).

traceback is an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation .

How to remove specific elements in a numpy array

You can also use sets:

a = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
the_index_list = [2, 3, 6]

the_big_set = set(numpy.arange(len(a)))
the_small_set = set(the_index_list)
the_delta_row_list = list(the_big_set - the_small_set)

a = a[the_delta_row_list]

How to create a zip file in Java

If you want decompress without software better use this code. Other code with pdf files sends error on manually decompress

byte[] buffer = new byte[1024];     
        FileOutputStream fos = new FileOutputStream("");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze= new ZipEntry("file.pdf");
        FileInputStream in = new FileInputStream("file.pdf");
        int len;
        while ((len = > 0) 
            zos.write(buffer, 0, len);
    catch(IOException ex)

How to export data from Excel spreadsheet to Sql Server 2008 table

From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.

This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.

You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).

Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??

OK, here it comes - step by step:

Step 1: pick your Excel source

enter image description here

Step 2: pick your SQL Server target database

enter image description here

Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!

enter image description here

Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:

enter image description here

Step 5: if you want to use it later on, save your SSIS package to SQL Server:

enter image description here

Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!

Pipenv: Command Not Found

Installing pipenv globally can have an adverse effect by overwriting the global/system-managed pip installation, thus resulting in import errors when trying to run pip.

You can install pipenv at the user level:

pip install --user pipenv

This should install pipenv at a user-level in /home/username/.local so that it does not conflict with the global version of pip. In my case, that still did not work after running the '--user' switch, so I ran the longer 'fix what I screwed up' command once to restore the system managed environment:

sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall

^ found here: Error after upgrading pip: cannot import name 'main'

and then did the following:

mkdir /home/username/.local ... if it doesn't already exist

export PYTHONUSERBASE=/home/username/.local

Make sure the export took effect (bit me once during this process):


Then, I ran the pip install --user pipenv and all was well. I could then run pipenv from the CLI and it did not overwrite the global/system-managed pip module. Of course, this is specific to the user so you want to make sure you install pipenv this way while working as the user you wish to use pipenv.


Python threading.timer - repeat function every 'n' seconds

In the interest of providing a correct answer using Timer as the OP requested, I'll improve upon swapnil jariwala's answer:

from threading import Timer

class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.is_running = False

    def _start_timer(self):
        if self._should_continue: # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            self._should_continue = False # Just in case thread is running and cancel fails.
            print("Timer never started or failed to initialize.")

def tick():
    print('ipsem lorem')

# Example Usage
t = InfiniteTimer(0.5, tick)

WAMP Cannot access on local network 403 Forbidden

For Apache 2.4.9

in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local

Change to:

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted

changing from "Require local" to "Require all granted" solved the error 403 in my local network

Error message "Forbidden You don't have permission to access / on this server"

If you are using a WAMP server then try this:

  • Single click on the WAMP server icon at the taskbar

  • Select the option put online

  • Your server will restart automatically

  • Then try to access your localwebsite

How can I right-align text in a DataGridView column?

DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;

Accessing variables from other functions without using global variables

Consider using namespaces:

(function() {
    var local_var = 'foo';
    global_var = 'bar'; // this.global_var and window.global_var also work

    function local_function() {}
    global_function = function() {};

Both local_function and global_function have access to all local and global variables.

Edit: Another common pattern:

var ns = (function() {
    // local stuff
    function foo() {}
    function bar() {}
    function baz() {} // this one stays invisible

    // stuff visible in namespace object
    return {
        foo : foo,
        bar : bar

The returned properties can now be accessed via the namespace object, e.g., while still retaining access to local definitions.

Best way to get the max value in a Spark dataframe column

Remark: Spark is intended to work on Big Data - distributed computing. The size of the example DataFrame is very small, so the order of real-life examples can be altered with respect to the small ~ example.

Slowest: Method_1, because .describe("A") calculates min, max, mean, stddev, and count (5 calculations over the whole column)

Medium: Method_4, because, .rdd (DF to RDD transformation) slows down the process.

Faster: Method_3 ~ Method_2 ~ method_5, because the logic is very similar, so Spark's catalyst optimizer follows very similar logic with minimal number of operations (get max of a particular column, collect a single-value dataframe); (.asDict() adds a little extra-time comparing 3,2 to 5)

import pandas as pd
import time

time_dict = {}

dfff = self.spark.createDataFrame([(1., 4.), (2., 5.), (3., 6.)], ["A", "B"])
#--  For bigger/realistic dataframe just uncomment the following 3 lines
#lst = list(np.random.normal(0.0, 100.0, 100000))
#pdf = pd.DataFrame({'A': lst, 'B': lst, 'C': lst, 'D': lst})
#dfff = self.sqlContext.createDataFrame(pdf)

tic1 = int(round(time.time() * 1000))
# Method 1: Use describe()
max_val = float(dfff.describe("A").filter("summary = 'max'").select("A").collect()[0].asDict()['A'])
tac1 = int(round(time.time() * 1000))
time_dict['m1']= tac1 - tic1
print (max_val)

tic2 = int(round(time.time() * 1000))
# Method 2: Use SQL
max_val = self.sqlContext.sql("SELECT MAX(A) as maxval FROM df_table").collect()[0].asDict()['maxval']
tac2 = int(round(time.time() * 1000))
time_dict['m2']= tac2 - tic2
print (max_val)

tic3 = int(round(time.time() * 1000))
# Method 3: Use groupby()
max_val = dfff.groupby().max('A').collect()[0].asDict()['max(A)']
tac3 = int(round(time.time() * 1000))
time_dict['m3']= tac3 - tic3
print (max_val)

tic4 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val ="A").rdd.max()[0]
tac4 = int(round(time.time() * 1000))
time_dict['m4']= tac4 - tic4
print (max_val)

tic5 = int(round(time.time() * 1000))
# Method 4: Convert to RDD
max_val = dfff.agg({"A": "max"}).collect()[0][0]
tac5 = int(round(time.time() * 1000))
time_dict['m5']= tac5 - tic5
print (max_val)

print time_dict

Result on an edge-node of a cluster in milliseconds (ms):

small DF (ms) : {'m1': 7096, 'm2': 205, 'm3': 165, 'm4': 211, 'm5': 180}

bigger DF (ms): {'m1': 10260, 'm2': 452, 'm3': 465, 'm4': 916, 'm5': 373}

AES Encrypt and Decrypt

You can use CommonCrypto from iOS or CryptoSwift as external library. There are implementations with both tools below. That said, CommonCrypto output with AES should be tested, as it is not clear in CC documentation, which mode of AES it uses.

CommonCrypto in Swift 4.2

    import CommonCrypto

    func encrypt(data: Data) -> Data {
        return cryptCC(data: data, key: key, operation: kCCEncrypt)

    func decrypt(data: Data) -> Data {
        return cryptCC(data: data, key: key, operation: kCCDecrypt)

    private func cryptCC(data: Data, key: String operation: Int) -> Data {

        guard key.count == kCCKeySizeAES128 else {
            fatalError("Key size failed!")

        var ivBytes: [UInt8]
        var inBytes: [UInt8]
        var outLength: Int

        if operation == kCCEncrypt {
            ivBytes = [UInt8](repeating: 0, count: kCCBlockSizeAES128)
            guard kCCSuccess == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else {
                fatalError("IV creation failed!")

            inBytes = Array(data)
            outLength = data.count + kCCBlockSizeAES128

        } else {
            ivBytes = Array(Array(data).dropLast(data.count - kCCBlockSizeAES128))
            inBytes = Array(Array(data).dropFirst(kCCBlockSizeAES128))
            outLength = inBytes.count


        var outBytes = [UInt8](repeating: 0, count: outLength)
        var bytesMutated = 0

        guard kCCSuccess == CCCrypt(CCOperation(operation), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), Array(key), kCCKeySizeAES128, &ivBytes, &inBytes, inBytes.count, &outBytes, outLength, &bytesMutated) else {
            fatalError("Cryptography operation \(operation) failed")

        var outData = Data(bytes: &outBytes, count: bytesMutated)

        if operation == kCCEncrypt {
            ivBytes.append(contentsOf: Array(outData))
            outData = Data(bytes: ivBytes)
        return outData


CryptoSwift v0.14 in Swift 4.2

    enum Operation {
        case encrypt
        case decrypt

    private let keySizeAES128 = 16
    private let aesBlockSize = 16

    func encrypt(data: Data, key: String) -> Data {
        return crypt(data: data, key: key, operation: .encrypt)

    func decrypt(data: Data, key: String) -> Data {
        return crypt(data: data, key: key, operation: .decrypt)

    private func crypt(data: Data, key: String, operation: Operation) -> Data {

        guard key.count == keySizeAES128 else {
            fatalError("Key size failed!")
        var outData: Data? = nil

        if operation == .encrypt {
            var ivBytes = [UInt8](repeating: 0, count: aesBlockSize)
            guard 0 == SecRandomCopyBytes(kSecRandomDefault, ivBytes.count, &ivBytes) else {
                fatalError("IV creation failed!")

            do {
                let aes = try AES(key: Array( .utf8)!), blockMode: CBC(iv: ivBytes))
                let encrypted = try aes.encrypt(Array(data))
                ivBytes.append(contentsOf: encrypted)
                outData = Data(bytes: ivBytes)

            } catch {
                print("Encryption error: \(error)")

        } else {
            let ivBytes = Array(Array(data).dropLast(data.count - aesBlockSize))
            let inBytes = Array(Array(data).dropFirst(aesBlockSize))

            do {
                let aes = try AES(key: Array( .utf8)!), blockMode: CBC(iv: ivBytes))
                let decrypted = try aes.decrypt(inBytes)
                outData = Data(bytes: decrypted)

            } catch {
                print("Decryption error: \(error)")
        return outData!


Detect all Firefox versions in JS

If you'd like to know what is the numeric version of FireFox you can use the following snippet:

var match = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
var ver = match ? parseInt(match[1]) : 0;

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

mysql update column with value from another table

The second option is feasible also if you're using safe updates mode (and you're getting an error indicating that you've tried to update a table without a WHERE that uses a KEY column), by adding:

SET TableB.value = (  
SELECT TableA.value  
    FROM TableA  
    WHERE =  
**where < X**  

Bootstrap 3 Horizontal Divider (not in a dropdown)

Yes there is, you can simply put <hr> in your code where you want it, I already use it in one of my admin panel side bar.

Reading in from - Java

Well, you may read itself as it is a valid InputStream. Or also you can wrap it in a BufferedReader:

BufferedReader br = new BufferedReader(new InputStreamReader(;

Excel Formula to SUMIF date falls in particular month

Try this instead:


It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.

Here's how the formula works.

  1. MONTH($A$2:$A$6) creates an array of numeric values of the month for the dates in A2:A6, that is,
    {1, 1, 1, 2, 2}.
  2. Then the comparison {1, 1, 1, 2, 2}= 1 produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}, which comprises the condition for the IF statement.
  3. The IF statement then returns an array of values, with {430, 96, 400.. for the values of the sum ranges where the month value equals 1 and ..0,0} where the month value does not equal 1.
  4. That array {430, 96, 400, 0, 0} is then summed to get the answer you are looking for.

This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.

It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)--also works.

Heads up: This does not work in Google Spreadsheets

Use a URL to link to a Google map with a marker on it

If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker


GooglemRute=""&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en"  'route ?hl=en



Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I get the same error in Chrome after pasting code copied from jsfiddle.

If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.

Send multiple checkbox data to PHP via jQuery ajax()

Check this out.

<script type="text/javascript">
    function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {

        var myCheckboxes = new Array();
        $("input:checked").each(function() {

            type: "POST",
            url: "myurl.php",
            dataType: 'html',
            data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
            success: function(data){
        return false;

And on myurl.php you can use print_r($_POST['myCheckboxes']);

Google Colab: how to read data from my google drive?

There are many ways to read the files in your colab notebook(**.ipnb), a few are:

  1. Mounting your Google Drive in the runtime's virtual &, here
  2. Using google.colab.files.upload(). the easiest solution
  3. Using the native REST API;
  4. Using a wrapper around the API such as PyDrive

Method 1 and 2 worked for me, rest I wasn't able to figure out. If anyone could, as others tried in above post please write an elegant answer. thanks in advance.!

First method:

I wasn't able to mount my google drive, so I installed these libraries

# Install a Drive FUSE wrapper.

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

Once the installation & authorization process is finished, you first mount your drive.

!mkdir -p drive
!google-drive-ocamlfuse drive

After installation I was able to mount the google drive, everything in your google drive starts from /content/drive

!ls /content/drive/ML/../../../../path_to_your_folder/

Now you can simply read the file from path_to_your_folder folder into pandas using the above path.

import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')

you are suppose you use absolute path you received & not using /../..

Second method:

Which is convenient, if your file which you want to read it is present in the current working directory.

If you need to upload any files from your local file system, you could use below code, else just avoid it.!

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

suppose you have below the folder hierarchy in your google drive:


Then, you simply need below code to load into pandas.

import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

Ng-model does not update controller value

"If you use ng-model, you have to have a dot in there."
Make your model point to an and you'll be good to go.


$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works


<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

This happens when child scopes are in play - like child routes or ng-repeats. The child-scope creates it's own value and a name conflict is born as illustrated here:

See this video clip for more:

How to redirect output to a file and stdout

Another handy alternative is to use screen command to run the main program and direct the stderr and stdout to a file, then use tail -f to view the file as it is being written to.

You could also open another session if you don't want to use screen.

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

Is there a way to return a list of all the image file names from a folder using only Javascript?

Although you can run FTP commands using WebSockets, the simpler solution is listing your files using opendir in server side (PHP), and "spitting" it into the HTML source-code, so it will be available to client side.

The following code will do just that,

Optionally -

  • use <a> tag to present a link.
  • query for more information using server side (PHP),

    for example a file size,

PHP filesize TIP:   also you can easily overcome the 2GB limit of PHP's filesize using: AJAX + HEAD request + .htaccess rule to allow Content-Length access from client-side.

  /* taken from: */

  $path = 'resources';
  $files = [];
  $handle = @opendir('./' . $path . '/');

  while ($file = @readdir($handle)) 
    ("." !== $file && ".." !== $file) && array_push($files, $file);
  sort($files); //uksort($files, "strnatcasecmp");

  $files = json_encode($files);

<!DOCTYPE html>
<html lang="en-US" dir="ltr">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <div data-container></div>
    /* you will see (for example): 'var files = ["1.bat","1.exe","1.txt"];' if your folder containes those 1.bat 1.exe 1.txt files, it will be sorted too! :) */

    var files = <?php echo $files; ?>;

    files ={
      return '<a data-ext="##EXT##" download="##FILE##" href="">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )

    document.querySelector('[data-container]').innerHTML = files;


DOM result will look like that:

<html lang="en-US" dir="ltr"><head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <div data-container="">
    <a data-ext="bat" download="1.bat" href="">1.bat</a>
    <a data-ext="exe" download="1.exe" href="">1.exe</a>
    <a data-ext="txt" download="1.txt" href="">1.txt</a>
    var files = ["1.bat","1.exe","1.txt"];

    files ={
      return '<a data-ext="##EXT##" download="##FILE##" href="">##FILE##</a>'
        .replace(/##FILE##/g,       file)
        .replace(/##EXT##/g,        file.split('.').slice(-1) )

    document.querySelector('[data-container').innerHTML = files;


SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Probably, you need to insert schema identifier here:

in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    return parser.parse_args()

and this outputs:

usage: [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

Built in Python hash() function

What about sign bit?

For example:

Hex value 0xADFE74A5 represents unsigned 2919134373 and signed -1375832923. Currect value must be signed (sign bit = 1) but python converts it as unsigned and we have an incorrect hash value after translation from 64 to 32 bit.

Be careful using:

def hash32(value):
    return hash(value) & 0xffffffff

Node.js throws "btoa is not defined" error

My team ran into this problem when using Node with React Native and PouchDB. Here is how we solved it...

NPM install buffer:

$ npm install --save buffer

Ensure Buffer, btoa, and atob are loaded as a globals:

global.Buffer = global.Buffer || require('buffer').Buffer;

if (typeof btoa === 'undefined') {
  global.btoa = function (str) {
    return new Buffer(str, 'binary').toString('base64');

if (typeof atob === 'undefined') {
  global.atob = function (b64Encoded) {
    return new Buffer(b64Encoded, 'base64').toString('binary');

/usr/lib/ version `GLIBCXX_3.4.15' not found

Same thing with gcc version 4.8.1 (GCC) and Had to copy it here /usr/lib/x86_64-linux-gnu on my ubuntu box.

Merging 2 branches together in GIT

If you want to merge changes in SubBranch to MainBranch

  1. you should be on MainBranch git checkout MainBranch
  2. then run merge command git merge SubBranch

How to Batch Rename Files in a macOS Terminal?

you can install rename command by using brew. just do brew install rename and use it.

Get the current file name in gulp.src()

For my case gulp-ignore was perfect. As option you may pass a function there:

function condition(file) {
 // do whatever with file.path
 // return boolean true if needed to exclude file 

And the task would look like this:

var gulpIgnore = require('gulp-ignore');

gulp.task('task', function() {

how to check for special characters php


$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
    // one or more of the 'special characters' found in $string

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

public class Parent implements Serializable {

    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);

    public class FileProxy : IFileProxy {
        public void Delete(string path) {

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete


The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();

        public static void Delete(string path) {


Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete


For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The == operator tests value equivalence. The is operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).

>>> a = 'banana'
>>> b = 'banana'
>>> a is b

In this example, Python only created one string object, and both a and b refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:

>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)

When you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED]

I faced same issue but after a lot of RND. I found that whts the problem so run this command on your terminal.

sudo service mongod start

then run mongo on terminal

I can’t find the Android keytool

I never installed Java, but when you install Android Studio it has its own version within the Android directory. Here is where mine is located. Your path may be similar. After that you can either put the keytool into your path, or just run it from that directory.

C:\Program Files\Android\Android Studio\jre\bin

Hide all warnings in ipython

The accepted answer does not work in Jupyter (at least when using some libraries).

The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.

To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.

(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head"); {
    var s='Showing';  
    if(on) {
        cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
    e.text(s+' warnings (click to toggle)');

How to test android apps in a real device with Android Studio?

I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.

How to change a particular element of a C++ STL vector

I prefer -1;

while [4] is your index

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.

How to read an entire file to a string using C#?

string text = File.ReadAllText("Path"); you have all text in one string variable. If you need each line individually you can use this:

string[] lines = File.ReadAllLines("Path");

Ordering issue with date values when creating pivot tables

April 20, 2017

I've read all the previously posted answers, and they require a lot of extra work. The quick and simple solution I have found is as follows:

1) Un-group the date field in the pivot table. 2) Go to the Pivot Field List UI. 3) Re-arrange your fields so that the Date field is listed FIRST in the ROWS section. 4) Under the Design menu, select Report Layout / Show in Tabular Form.

By default, Excel sorts by the first field in a pivot table. You may not want the Date field to be first, but it's a compromise that will save you time and much work.

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => { = 'blurg';
  return previousState;

Unless I'm reading the docs wrong, Facebook recommends the above format.

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { }; // deconstruct into a new object-- effectively making a copy = 'blurg';

How to extract duration time from ffmpeg output?

From my experience many tools offer the desired data in some kind of a table/ordered structure and also offer parameters to gather specific parts of that data. This applies to e.g. smartctl, nvidia-smi and ffmpeg/ffprobe, too. Simply speaking - often there's no need to pipe data around or to open subshells for such a task.

As a consequence I'd use the right tool for the job - in that case ffprobe would return the raw duration value in seconds, afterwards one could create the desired time format on his own:

$ ffmpeg --version
ffmpeg version 2.2.3 ...

The command may vary dependent on the version you are using.

#!/usr/bin/env bash

# Get raw duration value
ffprobe -v quiet -print_format compact=print_section=0:nokey=1:escape=csv -show_entries format=duration "$input_file"

An explanation:

"-v quiet": Don't output anything else but the desired raw data value

"-print_format": Use a certain format to print out the data

"compact=": Use a compact output format

"print_section=0": Do not print the section name

":nokey=1": do not print the key of the key:value pair

":escape=csv": escape the value

"-show_entries format=duration": Get entries of a field named duration inside a section named format

Reference: ffprobe man pages

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:

/usr/bin/mysql_upgrade -u root -p

Login as root:

mysql -u root -p

Run this commands:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:

The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a "String data, right truncation" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.

You can find the full article here.

Format string to a 3 digit number

Does it have to be String.Format?

This looks like a job for String.Padleft

myString=myString.PadLeft(3, '0');

Or, if you are converting direct from an int:


How to call a SOAP web service on Android

Follow these steps by the method SOAP

From the WSDL file,

  • create SOAP Request templates for each Request.

  • Then substitute the values to be passed in code.

  • POST this data to the service end point using DefaultHttpClient instance.

  • Get the response stream and finally

  • Parse the Response Stream using an XML Pull parser.

"Sources directory is already netbeans project" error when opening a project from existing sources

I faced the same issue:

Sources directory is already NetBeans project (maybe only in memory).

The solution is:

Netbeans creates a folder in your project named "nbproject". Once you delete that, restart the IDE and you're good to go.

Changing text color onclick

A rewrite of the answer by Sarfraz would be something like this, I think:


    document.getElementById('change').onclick = changeColor;   

    function changeColor() { = "purple";
        return false;


You'd either have to put this script at the bottom of your page, right before the closing body tag, or put the handler assignment in a function called onload - or if you're using jQuery there's the very elegant $(document).ready(function() { ... } );

Note that when you assign event handlers this way, it takes the functionality out of your HTML. Also note you set it equal to the function name -- no (). If you did onclick = myFunc(); the function would actually execute when the handler is being set.

And I'm curious -- you knew enough to script changing the background color, but not the text color? strange:)

How to find first element of array matching a boolean condition in JavaScript?

As of ECMAScript 6, you can use Array.prototype.find for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.

For example, x below is 106:

const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
    return el > 105;

If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don't want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find and overwrites them (see the comment that begins "Work around bugs in Array#find and Array#findIndex" and the lines immediately following it).

How to embed a PDF?

I recommend using PDFObject for PDF plugin detection.

This will only allow you to display alternate content if the user's browser isn't capable of displaying the PDF directly though. For example, the PDF will display fine in Chrome for most users, but they will need a plugin like Adobe Reader installed if they're using Firefox or Internet Explorer.

At least PDFObject will allow you to display a message with a link to download Adobe Reader and/or the PDF file itself if their browser doesn't already have a PDF plugin installed.

Cut Corners using CSS

CSS Clip-Path

Using a clip-path is a new, up and coming alternative. Its starting to get supported more and more and is now becoming well documented. Since it uses SVG to create the shape, it is responsive straight out of the box.

div {_x000D_
  width: 200px;_x000D_
  min-height: 200px;_x000D_
  -webkit-clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
  clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 25%, 75% 0);_x000D_
  background: lightblue;_x000D_
  <p>Some Text</p>_x000D_

CSS Transform

I have an alternative to web-tiki's transform answer.

body {_x000D_
  background: lightgreen;_x000D_
div {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: transparent;_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
}_x000D_ {_x000D_
  width: 200%;_x000D_
  height: 200%;_x000D_
  background: lightblue;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: -75%;_x000D_
  transform-origin: 50% 50%;_x000D_
  transform: rotate(45deg);_x000D_
  z-index: -1;_x000D_
  <div class="bg"></div>_x000D_
  <p>Some Text</p>_x000D_

res.sendFile absolute path

you can use send instead of sendFile so you wont face with error! this works will help you!

}else {
res.setHeader('Content-Type', 'application/pdf');

for telling browser that your response is type of PDF

res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');

if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.


Pagination using MySQL LIMIT, OFFSET

Use .. LIMIT :pageSize OFFSET :pageStart

Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.

To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.

If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

How get total sum from input box values using Javascript?

  //iterate through each textboxes and add keyup_x000D_
  //handler to trigger sum event_x000D_
  $(".txt").each(function() {_x000D_
 function calculateSum() {_x000D_
  var sum = 0;_x000D_
  //iterate through each textboxes and add the values_x000D_
  $(".txt").each(function() {_x000D_
   //add only if the value is number_x000D_
   if(!isNaN(this.value) && this.value.length!=0) {_x000D_
    sum += parseFloat(this.value);_x000D_
  //.toFixed() method will roundoff the final sum to 2 decimal places_x000D_
body {_x000D_
    font-family: sans-serif;_x000D_
   #summation {_x000D_
    font-size: 18px;_x000D_
    font-weight: bold;_x000D_
   .txt {_x000D_
    background-color: #FEFFB0;_x000D_
    font-weight: bold;_x000D_
    text-align: right;_x000D_
<script src=""></script>_x000D_
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">_x000D_
  <td width="40px">1</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 <tr id="summation">_x000D_
  <td align="right">Sum :</td>_x000D_
  <td align="center"><span id="sum">0</span></td>_x000D_

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

`IF` statement with 3 possible answers each based on 3 different ranges

Your formula should be of the form =IF(X2 >= 85,0.559,IF(X2 >= 80,0.327,IF(X2 >=75,0.255,0))). This simulates the ELSE-IF operand Excel lacks. Your formulas were using two conditions in each, but the second parameter of the IF formula is the value to use if the condition evaluates to true. You can't chain conditions in that manner.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Find a commit on GitHub given the commit hash

A URL of the form<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

You can also shorten the hash to any unique prefix, like so:

I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
        hours  = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
    return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");

I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.

var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);


How to redirect Valgrind's output to a file?

You can also set the options --log-fd if you just want to read your logs with a less. For example :

valgrind --log-fd=1 ls | less

JSLint is suddenly reporting: Use the function form of "use strict"

process.on('warning', function(e) {
    'use strict';
process.on('uncaughtException', function(e) {
    'use strict';

add this lines to at the starting point of your file

Submit form on pressing Enter with AngularJS

Use ng-submit and just wrap both inputs in separate form tags:

<div ng-controller="mycontroller">

  <form ng-submit="myFunc()">
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />

  <br />

  <form ng-submit="myFunc()">
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />


Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.

Float a div above page content

The below code is working,

    .PanelFloat {
        position: fixed;
        overflow: hidden;
        z-index: 2400;
        opacity: 0.70;
        right: 30px;
        top: 0px !important;
        -webkit-transition: all 0.5s ease-in-out;
        -moz-transition: all 0.5s ease-in-out;
        -ms-transition: all 0.5s ease-in-out;
        -o-transition: all 0.5s ease-in-out;
        transition: all 0.5s ease-in-out;

 //The below script will keep the panel float on normal state
 $(function () {
        $(document).on('scroll', function () {
            //Multiplication value shall be changed based on user window
            $('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
 //To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
 $(document).on('click', '.btnSearchView', function () {

  $(document).on('click', '.btnSearchClose', function () {

 <div class="col-lg-12 col-md-12">
   <div class="col-lg-8 col-md-8" >
    //My scrollable content is here
   //This below panel will float while scrolling the above div content
   <div class="col-lg-4 col-md-4" id="MyFloatPanel">
    <div class="row">
     <div class="panel panel-default">
      <div class="panel-heading">Panel Head </div>
     <div class="panel-body ">//Your panel content</div>

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

create table with sequence.nextval in oracle

Oracle 12c

We now finally have IDENTITY columns like many other databases, in case of which a sequence is auto-generated behind the scenes. This solution is much faster than a trigger-based one as can be seen in this blog post.

So, your table creation would look like this:

    qname    VARCHAR2(4000) NOT NULL -- CONSTRAINT qname_uk UNIQUE

Oracle 11g and below

According to the documentation, you cannot do that:

Restriction on Default Column Values A DEFAULT expression cannot contain references to PL/SQL functions or to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, PRIOR, and ROWNUM, or date constants that are not fully specified.

The standard way to have "auto increment" columns in Oracle is to use triggers, e.g.

  ON qname
  -- Optionally restrict this trigger to fire only when really needed
  WHEN (new.qname_id is null)
  v_id qname.qname_id%TYPE;
  -- Select a new value from the sequence into a local variable. As David
  -- commented, this step is optional. You can directly select into :new.qname_id
  SELECT qname_id_seq.nextval INTO v_id FROM DUAL;

  -- :new references the record that you are about to insert into qname. Hence,
  -- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
  -- obtained from your sequence, before inserting
  :new.qname_id := v_id;
END my_trigger;

Read more about Oracle TRIGGERs in the documentation

How to use a FolderBrowserDialog from a WPF application

And here's my final version.

public static class MyWpfExtensions
    public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
        var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
        System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
        return win;

    private class OldWindow : System.Windows.Forms.IWin32Window
        private readonly System.IntPtr _handle;
        public OldWindow(System.IntPtr handle)
            _handle = handle;

        #region IWin32Window Members
        System.IntPtr System.Windows.Forms.IWin32Window.Handle
            get { return _handle; }

And to actually use it:

var dlg = new FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dlg.ShowDialog(this.GetIWin32Window());

What are the main differences between JWT and OAuth authentication?

Firstly, we have to differentiate JWT and OAuth. Basically, JWT is a token format. OAuth is an authorization protocol that can use JWT as a token. OAuth uses server-side and client-side storage. If you want to do real logout you must go with OAuth2. Authentication with JWT token can not logout actually. Because you don't have an Authentication Server that keeps track of tokens. If you want to provide an API to 3rd party clients, you must use OAuth2 also. OAuth2 is very flexible. JWT implementation is very easy and does not take long to implement. If your application needs this sort of flexibility, you should go with OAuth2. But if you don't need this use-case scenario, implementing OAuth2 is a waste of time.

XSRF token is always sent to the client in every response header. It does not matter if a CSRF token is sent in a JWT token or not, because the CSRF token is secured with itself. Therefore sending CSRF token in JWT is unnecessary.

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

The new version has changed.. for the latest version use the code below:

        format:'MMMM DD, YYYY',

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
<td style = "text-align: center;">

How to set a timer in android

I used to use (Timer, TimerTask) as well as Handler to kick off (time-consuming) tasks periodically. Now I've switched the whole to RxJava. RxJava provides Observable.timer which is simpler, less error-prone, hassle-free to use.

public class BetterTimerFragment extends Fragment {
  public static final String TAG = "BetterTimer";
  private TextView timeView;
  private Subscription timerSubscription;

  public View onCreateView(LayoutInflater inflater,
                           @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_timer, container, false);

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    timeView = (TextView) view.findViewById(;

  public void onResume() {

    // Right after the app is visible to users, delay 2 seconds
    // then kick off a (heavy) task every 10 seconds.
    timerSubscription = Observable.timer(2, 10, TimeUnit.SECONDS)
        .map(new Func1<Long, String>() {
          public String call(Long unused) {
            // TODO: Probably do time-consuming work here.
            // This runs on a different thread than the main thread.
            return "Time: " + System.currentTimeMillis();
        .subscribe(new Action1<String>() {
          public void call(String timeText) {
            // The result will then be propagated back to the main thread.
        }, new Action1<Throwable>() {
          public void call(Throwable throwable) {
            Log.e(TAG, throwable.getMessage(), throwable);

  public void onPause() {

    // Don't kick off tasks when the app gets invisible.

Can't connect to MySQL server on 'localhost' (10061) after Installation

if it is showing error 2003 (HY000): Can't connect to MySQL server on localhost (10061) than

  1. Search services.msc in run
  2. goto mysql properties
  3. copy the mysql service name
  4. start cmd as administrator
  5. write: net start mysqlservicename .i.e mysql57 or etc it will show mysql is starting.

How to AUTO_INCREMENT in db2?

hi If you are still not able to make column as AUTO_INCREMENT while creating table. As a work around first create table that is:

create table student( sid integer NOT NULL sname varchar(30), PRIMARY KEY (sid) );

and then explicitly try to alter column bu using the following

alter table student alter column sid set GENERATED BY DEFAULT AS IDENTITY


alter table student alter column sid set GENERATED BY DEFAULT AS IDENTITY (start with 100)

Downloading and unzipping a .zip file without writing to disk

My suggestion would be to use a StringIO object. They emulate files, but reside in memory. So you could do something like this:

# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'

import zipfile
from StringIO import StringIO

zipdata = StringIO()
myzipfile = zipfile.ZipFile(zipdata)
foofile ='foo.txt')

# output: "hey, foo"

Or more simply (apologies to Vishal):

myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
    [ ... ]

In Python 3 use BytesIO instead of StringIO:

import zipfile
from io import BytesIO

filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
    [ ... ]

How to check if a service is running on Android?

An extract from Android docs:

Like sendBroadcast(Intent), but if there are any receivers for the Intent this function will block and immediately dispatch them before returning.

Think of this hack as "pinging" the Service. Since we can broadcast synchronously, we can broadcast and get a result synchronously, on the UI thread.


public void onCreate() {
     .registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping"));
     //do not forget to deregister the receiver when the service is destroyed to avoid
     //any potential memory leaks 

private class ServiceEchoReceiver extends BroadcastReceiver {
    public void onReceive (Context context, Intent intent) {
         .sendBroadcastSync(new Intent("pong"));


    bool serviceRunning = false;

    protected void onCreate (Bundle savedInstanceState){
        LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong"));
        LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping"));
           //run the service

    private BroadcastReceiver pong = new BroadcastReceiver(){
        public void onReceive (Context context, Intent intent) {
          serviceRunning = true;   

The winner in many applications is, of course, a static boolean field on the service that is set to true in Service.onCreate() and to false in Service.onDestroy() because it's a lot simpler.

Angular 2 / 4 / 5 - Set base href dynamically

Here's what we ended up doing.

Add this to index.html. It should be the first thing in the <head> section

<base href="/">
  (function() {
    window['_app_base'] = '/' + window.location.pathname.split('/')[1];

Then in the app.module.ts file, add { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' } to the list of providers, like so:

import { NgModule, enableProdMode, provide } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent, routing, appRoutingProviders, environment } from './';

if (environment.production) {

  declarations: [AppComponent],
  imports: [
  bootstrap: [AppComponent],
  providers: [
    { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' },
export class AppModule { }

How do I get the key at a specific index from a Dictionary in Swift?

You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)

let dict = ["c": 123, "d": 045, "a": 456]

for (index, entry) in enumerate(dict) {
    println(index)   // 0       1        2
    println(entry)   // (d, 45) (c, 123) (a, 456)

If you want to sort first..

var sortedKeysArray = sorted(dict) { $0.0 < $1.0 }
println(sortedKeysArray)   // [(a, 456), (c, 123), (d, 45)]

var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]

then iterate.

for (index, entry) in enumerate(sortedKeysArray) {
    println(index)    // 0   1   2
    println(entry.0)  // a   c   d
    println(entry.1)  // 456 123 45

If you want to create an ordered dictionary, you should look into Generics.

How do I open an .exe from another C++ .exe?

I've had great success with this:

#include <iostream>
#include <windows.h>

int main() {
    ShellExecute(NULL, "open", "path\\to\\file.exe", NULL, NULL, SW_SHOWDEFAULT);

If you're interested, the full documentation is here:

How to set a selected option of a dropdown list control using angular JS

If you assign value 0 to item.selectedVariant it should be selected automatically. Check out sample on which selects red color by default by simply assigning $scope.color='red'.

Static image src in Vue.js template

This solution is for Vue-2 users:

  1. In vue-2 if you don't like to keep your files in static folder (relevant info), or
  2. In vue-2 & vue-cli-3 if you don't like to keep your files in public folder (static folder is renamed to public):

The simple solution is :)

<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}

If you like to keep your static images in static/assets/img or public/assets/img folder, then just do:

<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./

How to select a single column with Entity Framework?

If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;

Above query will be converted to this:

Select Top (1) UserId, Name from MyTable where UserId = 1;

For multiple items you can simply chain Select after Where:

var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);

Use anonymous object inside Select if you need more than one properties.

How can I check for an empty/undefined/null string in JavaScript?

Also, in case you consider a whitespace filled string as "empty".

You can test it with this regular expression:

!/\S/.test(string); // Returns true if blank.

Why is Tkinter Entry's get function returning nothing?


master = Tk()
entryb1 = StringVar

Label(master, text="Input: ").grid(row=0, sticky=W)

Entry(master, textvariable=entryb1).grid(row=1, column=1)

b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)

def print_content():
    global entryb1
    content = entryb1.get()


What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.

How to convert a char array to a string?

Another solution might look like this,

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

which avoids using an extra variable.

Right click to select a row in a Datagridview and show a menu to delete it

You can also make this a little simpler by using the following inside the event code:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) 
    if (e.Button == MouseButtons.Right)     
        rowToDelete = e.RowIndex;

ImportError: No module named six

You probably don't have the six Python module installed. You can find it on pypi.

To install it:

$ easy_install six

(if you have pip installed, use pip install six instead)

File count from a folder

System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]


    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

Android Button click go to another xml page

Write below code in your file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

    protected void onCreate(Bundle savedInstanceState) {

        Button mBtn1 = (Button) findViewById(;

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);

And Declare MainActivity2 into your Androidmanifest.xml file using below code.


How to perform Unwind segue programmatically?

Vishal Chaudhry's answer above worked for me. I would also add that in order to manually trigger the seque using:

[self performSegueWithIdentifier:@"mySegueName" sender:self];

from within the ViewController you must also select the unwind segue under the ViewController's Scene in the storyboard and in the properties view on the RHS ensure that the Indentifier field contains the namer you're referring to in the code ("mySegueName" in the example above).

If you omit this step, the line above will throw an exception that the seque name is not known.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.

In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

change image opacity using javascript

You could use Jquery indeed or plain good old javascript:

var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";

You put this in a function that you call on a setTimeout until the desired opacity is reached

How to find a hash key containing a matching value

You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.

jQuery Determine if a matched class has a given id

Just to say I eventually solved this using index().

NOTHING else seemed to work.

So for sibling elements this is a good work around if you are first selecting by a common class and then want to modify something differently for each specific one.

EDIT: for those who don't know (like me) index() gives an index value for each element that matches the selector, counting from 0, depending on their order in the DOM. As long as you know how many elements there are with class="foo" you don't need an id.

Obviously this won't always help, but someone might find it useful.

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 


P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

How to remove illegal characters from path and filenames?

I absolutely prefer the idea of Jeff Yates. It will work perfectly, if you slightly modify it:

string regex = String.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);

The improvement is just to escape the automaticially generated regex.