Programs & Examples On #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.

Python: finding lowest integer

You have to start somewhere the correct code should be:

The code to return the minimum value

l = [ '0.0', '1','-1.2'] x = l[0] for i in l: if i < x: x = i print x

But again it's good to use directly integers instead of using quotations ''

This way!

l = [ 0.0, 1,-1.2] x = l[0] for i in l: if i < x: x = i print x

Python String and Integer concatenation

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use :

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+`i` for i in range(11)]

Update as per Python3

You can use :

string = 'string'
for i in range(11):
    string +=str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+str(i) for i in range(11)]

Generate random integers between 0 and 9

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

Python: TypeError: cannot concatenate 'str' and 'int' objects

If you want to concatenate int or floats to a string you must use this:

i = 123
a = "foobar"
s = a + str(i)

How can I check if a value is of type Integer?

Try maybe this way

try{
    double d= Double.valueOf(someString);
    if (d==(int)d){
        System.out.println("integer"+(int)d);
    }else{
        System.out.println("double"+d);
    }
}catch(Exception e){
    System.out.println("not number");
}

But all numbers outside Integers range (like "-1231231231231231238") will be treated as doubles. If you want to get rid of that problem you can try it this way

try {
    double d = Double.valueOf(someString);
    if (someString.matches("\\-?\\d+")){//optional minus and at least one digit
        System.out.println("integer" + d);
    } else {
        System.out.println("double" + d);
    }
} catch (Exception e) {
    System.out.println("not number");
}

Generate unique random numbers between 1 and 100

This is a very generic function I have written to generate random unique/non-unique integers for an array. Assume the last parameter to be true in this scenario for this answer.

/* Creates an array of random integers between the range specified 
     len = length of the array you want to generate
     min = min value you require
     max = max value you require
     unique = whether you want unique or not (assume 'true' for this answer)
*/
    function _arrayRandom(len, min, max, unique) {
        var len = (len) ? len : 10,
                min = (min !== undefined) ? min : 1,
                max = (max !== undefined) ? max : 100,
                unique = (unique) ? unique : false,
                toReturn = [], tempObj = {}, i = 0;

        if(unique === true) {
            for(; i < len; i++) {
                var randomInt = Math.floor(Math.random() * ((max - min) + min));
                if(tempObj['key_'+ randomInt] === undefined) {
                    tempObj['key_'+ randomInt] = randomInt;
                    toReturn.push(randomInt);
                } else {
                    i--;
                }
            }
        } else {
            for(; i < len; i++) {
                toReturn.push(Math.floor(Math.random() * ((max - min) + min)));
            }
        }

        return toReturn;
    }

Here the 'tempObj' is a very useful obj since every random number generated will directly check in this tempObj if that key already exists, if not, then we reduce the i by one since we need 1 extra run since the current random number already exists.

In your case, run the following

_arrayRandom(8, 1, 100, true);

That's all.

Efficient way to determine number of digits in an integer

#include <stdint.h> // uint32_t [available since C99]

/// Determine the number of digits for a 32 bit integer.
/// - Uses at most 4 comparisons.
/// - (cX) 2014 [email protected]
/// - \see http://stackoverflow.com/questions/1489830/#27669966
/**  #d == Number length vs Number of comparisons == #c
     \code
         #d | #c   #d | #c
         ---+---   ---+---
         10 | 4     5 | 4
          9 | 4     4 | 4
          8 | 3     3 | 3
          7 | 3     2 | 3
          6 | 3     1 | 3
     \endcode
*/
unsigned NumDigits32bs(uint32_t x) {
    return // Num-># Digits->[0-9] 32->bits bs->Binary Search
    ( x >= 100000u // [6-10] [1-5]
    ?   // [6-10]
        ( x >= 10000000u // [8-10] [6-7]
        ?   // [8-10]
            ( x >= 100000000u // [9-10] [8]
            ? // [9-10]
                ( x >=  1000000000u // [10] [9]
                ?   10
                :    9
                )
            : 8
            )
        :   // [6-7]
            ( x >=  1000000u // [7] [6]
            ?   7
            :   6
            )
        )
    :   // [1-5]
        ( x >= 100u // [3-5] [1-2]
        ?   // [3-5]
            ( x >= 1000u // [4-5] [3]
            ? // [4-5]
                ( x >=  10000u // [5] [4]
                ?   5
                :   4
                )
            : 3
            )
        :   // [1-2]
            ( x >=  10u // [2] [1]
            ?   2
            :   1
            )
        )
    );
}

Round a floating-point number down to the nearest integer?

It may be very simple, but couldn't you just round it up then minus 1? For example:

number=1.5
round(number)-1
> 1

Way to get number of digits in an int?

no String API, no utils, no type conversion, just pure java iteration ->

public static int getNumberOfDigits(int input) {
    int numOfDigits = 1;
    int base = 1;
    while (input >= base * 10) {
        base = base * 10;
        numOfDigits++;
    }
    return numOfDigits;
 }

You can go long for bigger values if you please.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Checking whether a variable is an integer or not

Rather than over complicate things, why not just a simple

if type(var) is int:

How to convert signed to unsigned integer in python

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376
>>> i & 0xffffffff
4288082920

or if it is 64 bit:

>>> i & 0xffffffffffffffff
18446744073702667240

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.

This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.

Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):

>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:

>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376

Or for the 64 bit version:

>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.

How do I parse a string to a float or int?

This is a corrected version of https://stackoverflow.com/a/33017514/5973334

This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else 
        number_as_float

How to cast an Object to an int

int i = (Integer) object; //Type is Integer.

int i = Integer.parseInt((String)object); //Type is String.

How does Java handle integer underflows and overflows and how would you check for it?

There is one case, that is not mentioned above:

int res = 1;
while (res != 0) {
    res *= 2;

}
System.out.println(res);

will produce:

0

This case was discussed here: Integer overflow produces Zero.

T-sql - determine if value is integer

Here's a blog post describing the creation of an IsInteger UDF.

Basically, it recommends adding '.e0' to the value and using IsNumeric. In this way, anything that already had a decimal point now has two decimal points, causing IsNumeric to be false, and anything already expressed in scientific notation is invalidated by the e0.

Signed versus Unsigned Integers

Unsigned integers are far more likely to catch you in a particular trap than are signed integers. The trap comes from the fact that while 1 & 3 above are correct, both types of integers can be assigned a value outside the bounds of what it can "hold" and it will be silently converted.

unsigned int ui = -1;
signed int si = -1;

if (ui < 0) {
    printf("unsigned < 0\n");
}
if (si < 0) {
    printf("signed < 0\n");
}
if (ui == si) {
    printf("%d == %d\n", ui, si);
    printf("%ud == %ud\n", ui, si);
}

When you run this, you'll get the following output even though both values were assigned to -1 and were declared differently.

signed < 0
-1 == -1
4294967295d == 4294967295d

Convert boolean result into number/integer

I was just dealing with this issue in some code I was writing. My solution was to use a bitwise and.

var j = bool & 1;

A quicker way to deal with a constant problem would be to create a function. It's more readable by other people, better for understanding at the maintenance stage, and gets rid of the potential for writing something wrong.

function toInt( val ) {
    return val & 1;
}

var j = toInt(bool);

Edit - September 10th, 2014

No conversion using a ternary operator with the identical to operator is faster in Chrome for some reason. Makes no sense as to why it's faster, but I suppose it's some sort of low level optimization that makes sense somewhere along the way.

var j = boolValue === true ? 1 : 0;

Test for yourself: http://jsperf.com/boolean-int-conversion/2

In FireFox and Internet Explorer, using the version I posted is faster generally.

Edit - July 14th, 2017

Okay, I'm not going to tell you which one you should or shouldn't use. Every freaking browser has been going up and down in how fast they can do the operation with each method. Chrome at one point actually had the bitwise & version doing better than the others, but then it suddenly was much worse. I don't know what they're doing, so I'm just going to leave it at who cares. There's rarely any reason to care about how fast an operation like this is done. Even on mobile it's a nothing operation.

Also, here's a newer method for adding a 'toInt' prototype that cannot be overwritten.

Object.defineProperty(Boolean.prototype, "toInt", { value: function()
{
    return this & 1;
}});

Split an integer into digits to compute an ISBN checksum

Use the body of this loop to do whatever you want to with the digits

for digit in map(int, str(my_number)):

Convert string with comma to integer

How about this?

 "1,112".delete(',').to_i

Converting Integer to String with comma for thousands

System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646

MySQL Error 1264: out of range value for column

You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.

SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10

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

int[] arr = {111, 111, 110, 101, 101, 102, 115, 112};

/* for ascending order */

System.out.println(Arrays.toString(getSortedArray(arr)));
/*for descending order */
System.out.println(Arrays.toString(getSortedArray(arr)));

private int[] getSortedArray(int[] k){  

        int localIndex =0;
        for(int l=1;l<k.length;l++){
            if(l>1){
                localIndex = l;
                while(true){
                    k = swapelement(k,l);
                    if(l-- == 1)
                        break;
                }
                l = localIndex;
            }else
                k = swapelement(k,l);   
        }
        return k;
    }

    private int[] swapelement(int[] ar,int in){
        int temp =0;
        if(ar[in]<ar[in-1]){
            temp = ar[in];
            ar[in]=ar[in-1];
            ar[in-1] = temp;
        }

        return ar;
    }

private int[] getDescOrder(int[] byt){
        int s =-1;
        for(int i = byt.length-1;i>=0;--i){
              int k = i-1;
              while(k >= 0){
                  if(byt[i]>byt[k]){
                      s = byt[k];
                      byt[k] = byt[i];
                      byt[i] = s;
                  }
                  k--;
              }
           }
        return byt;
    }


output:-
ascending order:- 101, 101, 102, 110, 111, 111, 112, 115


descending order:- 115, 112, 111, 111, 110, 102, 101, 101

Increment a Integer's int value?

Integer objects are immutable, so you cannot modify the value once they have been created. You will need to create a new Integer and replace the existing one.

playerID = new Integer(playerID.intValue() + 1);

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

They are completely equivalent when used with printf(). Personally, I prefer %d, it's used more often (should I say "it's the idiomatic conversion specifier for int"?).

(One difference between %i and %d is that when used with scanf(), then %d always expects a decimal integer, whereas %i recognizes the 0 and 0x prefixes as octal and hexadecimal, but no sane programmer uses scanf() anyway so this should not be a concern.)

C++ - how to find the length of an integer

If you can use C libraries then one method would be to use sprintf, e.g.

#include <cstdio>

char s[32];

int len = sprintf(s, "%d", i);

How to convert a string to an integer in JavaScript?

I posted the wrong answer here, sorry. fixed.

This is an old question, but I love this trick:

~~"2.123"; //2
~~"5"; //5

The double bitwise negative drops off anything after the decimal point AND converts it to a number format. I've been told it's slightly faster than calling functions and whatnot, but I'm not entirely convinced.

EDIT: Another method I just saw here (a question about the javascript >>> operator, which is a zero-fill right shift) which shows that shifting a number by 0 with this operator converts the number to a uint32 which is nice if you also want it unsigned. Again, this converts to an unsigned integer, which can lead to strange behaviors if you use a signed number.

"-2.123" >>> 0; // 4294967294
"2.123" >>> 0; // 2
"-5" >>> 0; // 4294967291
"5" >>> 0; // 5

Converting an integer to a string in PHP

$num = 10;
"'".$num."'"

Try this

how to convert from int to char*?

I would not typecast away the const in the last line since it is there for a reason. If you can't live with a const char* then you better copy the char array like:

char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

max value of integer

Actually the size in bits of the int, short, long depends on the compiler implementation.

E.g. on my Ubuntu 64 bit I have short in 32 bits, when on another one 32bit Ubuntu version it is 16 bit.

Declaring an unsigned int in Java

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

How to print a number with commas as thousands separators in JavaScript

if you are dealing with currency values and formatting a lot then it might be worth to add tiny accounting.js which handles lot of edge cases and localization:

// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

How Do I Convert an Integer to a String in Excel VBA?

The shortest way without declaring the variable is with Type Hints :

s$ =  123   ' s = "123"
i% = "123"  ' i =  123

This will not compile with Option Explicit. The types will not be Variant but String and Integer

What's the most efficient way to test two integer ranges for overlap?

Here's my version:

int xmin = min(x1,x2)
  , xmax = max(x1,x2)
  , ymin = min(y1,y2)
  , ymax = max(y1,y2);

for (int i = xmin; i < xmax; ++i)
    if (ymin <= i && i <= ymax)
        return true;

return false;

Unless you're running some high-performance range-checker on billions of widely-spaced integers, our versions should perform similarly. My point is, this is micro-optimization.

Converting EditText to int? (Android)

I had the same problem myself. I'm not sure if you got it to work though, but what I had to was:

EditText cypherInput;
cypherInput = (EditText)findViewById(R.id.input_cipherValue);
int cypher = Integer.parseInt(cypherInput.getText().toString());

The third line of code caused the app to crash without using the .getText() before the .toString().

Just for reference, here is my XML:

<EditText
    android:id="@+id/input_cipherValue"
    android:inputType="number"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

How to convert an int to string in C?

/*Function return size of string and convert signed  *
 *integer to ascii value and store them in array of  *
 *character with NULL at the end of the array        */

int itoa(int value,char *ptr)
     {
        int count=0,temp;
        if(ptr==NULL)
            return 0;   
        if(value==0)
        {   
            *ptr='0';
            return 1;
        }

        if(value<0)
        {
            value*=(-1);    
            *ptr++='-';
            count++;
        }
        for(temp=value;temp>0;temp/=10,ptr++);
        *ptr='\0';
        for(temp=value;temp>0;temp/=10)
        {
            *--ptr=temp%10+'0';
            count++;
        }
        return count;
     }

Finding the length of an integer in C

Why don't you cast your integer to String and get length like this :

int data = 123;
int data_len = String(data).length();

How to convert a boolean array to an int array

Most of the time you don't need conversion:

>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])

The right way to do it is:

yourArray.astype(int)

or

yourArray.astype(float)

Why doesn't Java support unsigned ints?

Your question is "Why doesn't Java support unsigned ints"?

And my answer to your question is that Java wants that all of it's primitive types: byte, char, short, int and long should be treated as byte, word, dword and qword respectively, exactly like in assembly, and the Java operators are signed operations on all of it's primitive types except for char, but only on char they are unsigned 16 bit only.

So static methods suppose to be the unsigned operations also for both 32 and 64 bit.

You need final class, whose static methods can be called for the unsigned operations.

You can create this final class, call it whatever name you want and implement it's static methods.

If you have no idea about how to implement the static methods then this link may help you.

In my opinion, Java is not similar to C++ at all, if it neither support unsigned types nor operator overloading, so I think that Java should be treated as completely different language from both C++ and from C.

It is also completely different in the name of the languages by the way.

So I don't recommend in Java to type code similar to C and I don't recommend to type code similar to C++ at all, because then in Java you won't be able to do what you want to do next in C++, i.e. the code won't continue to be C++ like at all and for me this is bad to code like that, to change the style in the middle.

I recommend to write and use static methods also for the signed operations, so you don't see in the code mixture of operators and static methods for both signed and unsigned operations, unless you need only signed operations in the code, and it's okay to use the operators only.

Also I recommend to avoid using short, int and long primitive types, and use word, dword and qword respectively instead, and you are about call the static methods for unsigned operations and/or signed operations instead of using operators.

If you are about to do signed operations only and use the operators only in the code, then this is okay to use these primitive types short, int and long.

Actually word, dword and qword don't exist in the language, but you can create new class for each and the implementation of each should be very easy:

The class word holds the primitive type short only, the class dword holds the primitive type int only and the class qword holds the primitive type long only. Now all the unsigned and the signed methods as static or not as your choice, you can implement in each class, i.e. all the 16 bit operations both unsigned and signed by giving meaning names on the word class, all the 32 bit operations both unsigned and signed by giving meaning names on the dword class and all the 64 bit operations both unsigned and signed by giving meaning names on the qword class.

If you don't like giving too many different names for each method, you can always use overloading in Java, good to read that Java didn't remove that too!

If you want methods rather than operators for 8 bit signed operations and methods for 8 bit unsigned operations that have no operators at all, then you can create the Byte class (note that the first letter 'B' is capital, so this is not the primitive type byte) and implement the methods in this class.

About passing by value and passing by reference:

If I am not wrong, like in C#, primitive objects are passed by value naturally, but class objects are passed by reference naturally, so that means that objects of type Byte, word, dword and qword will be passed by reference and not by value by default. I wish Java had struct objects as C# has, so all Byte, word, dword and qword could be implemented to be struct instead of class, so by default they were passed by value and not by reference by default, like any struct object in C#, like the primitive types, are passed by value and not by reference by default, but because that Java is worse than C# and we have to deal with that, then there is only classes and interfaces, that are passed by reference and not by value by default. So if you want to pass Byte, word, dword and qword objects by value and not by reference, like any other class object in Java and also in C#, you will have to simply use the copy constructor and that's it.

That's the only solution that I can think about. I just wish that I could just typedef the primitive types to word, dword and qword, but Java neither support typedef nor using at all, unlike C# that supports using, which is equivalent to the C's typedef.

About output:

For the same sequence of bits, you can print them in many ways: As binary, as decimal (like the meaning of %u in C printf), as octal (like the meaning of %o in C printf), as hexadecimal (like the meaning of %x in C printf) and as integer (like the meaning of the %d in C printf).

Note that C printf doesn't know the type of the variables being passed as parameters to the function, so printf knows the type of each variable only from the char* object passed to the first parameter of the function.

So in each of the classes: Byte, word, dword and qword, you can implement print method and get the functionality of printf, even though the primitive type of the class is signed, you still can print it as unsigned by following some algorithm involving logical and shift operations to get the digits to print to the output.

Unfortunately the link I gave you doesn't show how to implement these print methods, but I am sure you can google for the algorithms you need to implement these print methods.

That's all I can answer your question and suggest you.

Parse v. TryParse

TryParse and the Exception Tax

Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

What is the difference between an int and an Integer in Java and C#?

One more thing that I don't see in previous answers: In Java the primitive wrappers classes like Integer, Double, Float, Boolean... and String are suposed to be invariant, so that when you pass an instance of those classes the invoked method couldn't alter your data in any way, in opositión with most of other classes, which internal data could be altered by its public methods. So that this classes only has 'getter' methods, no 'setters', besides the constructor.

In a java program String literals are stored in a separate portion of heap memory, only a instance for literal, to save memory reusing those instances

Convert array values from string to int?

Keep it simple...

$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);

Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode (). People have posted how to use that, so I am not including it here.

Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:

$str = '1';
($str == 1) // true but
($str === 1) //false

Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.

How can I tell if a Java integer is null?

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

Add to integers in a list

Yes, it is possible since lists are mutable.

Look at the built-in enumerate() function to get an idea how to iterate over the list and find each entry's index (which you can then use to assign to the specific list item).

Generate a random number in a certain range in MATLAB

Best solution is randint , but this function produce integer numbers.

You can use rand with rounding function

  r = round(a + (b-a).*rand(m,n));

This produces Real random number between a and b , size of output matrix is m*n

Alternative to itoa() for converting integer to string C++?

?++11 finally resolves this providing std::to_string. Also boost::lexical_cast is handy tool for older compilers.

Large Numbers in Java

Use the BigInteger class that is a part of the Java library.

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html

Converting integer to string in Python

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'

Casting an int to a string in Python

Here answer for your code as whole:

key =10

files = ("ME%i.txt" % i for i in range(key))

#opening
files = [ open(filename, 'w') for filename in files]

# processing
for i, file in zip(range(key),files):
    file.write(str(i))
# closing
for openfile in files:
    openfile.close()

How to convert datetime to integer in python

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

import datetime 

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))

Bash integer comparison

Easier solution;

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...

Output

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1

Explanation

  • (( )) - Evaluates the expression using integers.
  • ${1:-2} - Uses parameter expansion to set a value of 2 if undefined.
  • >= 2 - True if the integer is greater than or equal to two 2.

android - how to convert int to string and place it in a EditText?

try Integer.toString(integer value); method as

ed = (EditText)findViewById(R.id.box);
int x = 10;
ed.setText(Integer.toString(x));

Converting a string to an integer on Android

There are five ways to convert The First Way :

String str = " 123" ;
int i = Integer.parse(str); 
output : 123

The second way :

String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123

The Third Way :

String str"123";
int i = new Integer(str);
output "123 

The Fourth Way :

String str"123";
int i = Integer.valueOf(Str);
output "123 

The Fifth Way :

String str"123";
int i = Integer.decode(str);
output "123 

There could be other ways But that's what I remember now

What's the difference between integer class and numeric class in R

First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.

> is.numeric(1)

[1] TRUE

> is.integer(1)

[1] FALSE

> is.numeric(1L)

[1] TRUE

> is.integer(1L)

[1] TRUE

(Putting capital 'L' after an integer forces it to be stored as an integer.)

As you can see "integer" is a subset of "numeric".

> .Machine$integer.max

[1] 2147483647

> .Machine$double.xmax

[1] 1.797693e+308

Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).

Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.

One thing to watch out for is that the colon operator, :, will return integers if the start and end points are whole numbers. For example, 1:5 creates an integer vector of numbers from 1 to 5. You don't need to append the letter L.

> class(1:5)
[1] "integer"

Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R

In C#, how to check whether a string contains an integer?

This work for me.

("your string goes here").All(char.IsDigit)

C++ convert hex string to signed integer

Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.

char hextob(char ch)
{
    if (ch >= '0' && ch <= '9') return ch - '0';
    if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
    if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
    return 0;
}
template<typename T>
T hextot(char* hex)
{
    T value = 0;
    for (size_t i = 0; i < sizeof(T)*2; ++i)
        value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
    return value;
};

Usage:

int main()
{
    char str[4] = {'f','f','f','f'};
    std::cout << hextot<int16_t>(str)  << "\n";
}

Note: the length of the string must be divisible by 2

Integer value comparison

It's better to avoid unnecessary autoboxing for 2 reasons.

For one thing, it's a bit slower than int < int, as you're (sometimes) creating an extra object;

void doSomethingWith(Integer integerObject){ ...
  int i = 1000;
  doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));

The bigger issue is that hidden autoboxing can hide exceptions:

void doSomethingWith (Integer count){
  if (count>0)  // gets compiled into count.intValue()>0

Calling this method with null will throw a NullPointerException.

The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare() or intValue(), and if you've got the primitive just check the value directly.

How to parse a month name (string) to an integer for comparison in C#?

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

How does Python manage int and long?

Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().

>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>

How to convert integer to string in C?

Making your own itoa is also easy, try this :

char* itoa(int i, char b[]){
    char const digit[] = "0123456789";
    char* p = b;
    if(i<0){
        *p++ = '-';
        i *= -1;
    }
    int shifter = i;
    do{ //Move to where representation ends
        ++p;
        shifter = shifter/10;
    }while(shifter);
    *p = '\0';
    do{ //Move back, inserting digits as u go
        *--p = digit[i%10];
        i = i/10;
    }while(i);
    return b;
}

or use the standard sprintf() function.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Will be more portable in case of extending to other alphabets:

char='abcdefghijklmnopqrstuvwxyz'[code]

or, to be more compatible (with our beloved IE):

char='abcdefghijklmnopqrstuvwxyz'.charAt(code);

What is the maximum value for an int32?

That's how I remembered 2147483647:

  • 214 - because 2.14 is approximately pi-1
  • 48 = 6*8
  • 64 = 8*8

Write these horizontally:

214_48_64_
and insert:
   ^  ^  ^
   7  3  7 - which is Boeing's airliner jet (thanks, sgorozco)

Now you've got 2147483647.

Hope this helps at least a bit.

How to convert an IPv4 address into a integer in C#?

With the UInt32 in the proper little-endian format, here are two simple conversion functions:

public uint GetIpAsUInt32(string ipString)
{
    IPAddress address = IPAddress.Parse(ipString);

    byte[] ipBytes = address.GetAddressBytes();

    Array.Reverse(ipBytes);

    return BitConverter.ToUInt32(ipBytes, 0);
}

public string GetIpAsString(uint ipVal)
{
    byte[] ipBytes = BitConverter.GetBytes(ipVal);

    Array.Reverse(ipBytes);

    return new IPAddress(ipBytes).ToString();
}

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

Difference between long and int data types

The guarantees the standard gives you go like this:

1 == sizeof(char) <= sizeof(short) <= sizeof (int) <= sizeof(long) <= sizeof(long long)

So it's perfectly valid for sizeof (int) and sizeof (long) to be equal, and many platforms choose to go with this approach. You will find some platforms where int is 32 bits, long is 64 bits, and long long is 128 bits, but it seems very common for sizeof (long) to be 4.

(Note that long long is recognized in C from C99 onwards, but was normally implemented as an extension in C++ prior to C++11.)

How to catch integer(0)?

You can easily catch integer(0) with function identical(x,y)

x = integer(0)
identical(x, integer(0))
[1] TRUE

foo = function(x){identical(x, integer(0))}
foo(x)
[1] TRUE

foo(0)
[1] FALSE

Java reverse an int value without using array

int convert (int n)
{
        long val = 0;

        if(n==0)
            return 0;

        for(int i = 1; n > exponent(10,  (i-1)); i++)
        {
            int mod = n%( (exponent(10, i))) ;
            int index = mod / (exponent(10, i-1));

            val *= 10;
            val += index;
        }

        if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) 
        {
            throw new IllegalArgumentException
                (val + " cannot be cast to int without changing its value.");
        }
        return (int) val;

    }


static int exponent(int m, int n)
    {
        if(n < 0) 
            return 0;
        if(0 == n) 
            return 1;

        return (m * exponent(m, n-1));

    }

How to pass integer from one Activity to another?

It's simple. On the sender side, use Intent.putExtra:

Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

On the receiver side, use Intent.getIntExtra:

 Intent mIntent = getIntent();
 int intValue = mIntent.getIntExtra("intVariableName", 0);

Python - converting a string of numbers into a list of int

it should work

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]

Call int() function on every list element?

Another way,

for i, v in enumerate(numbers): numbers[i] = int(v)

Get int from String, also containing letters, in Java

Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

How to find length of digits in an integer?

Without conversion to string

import math
digits = int(math.log10(n))+1

To also handle zero and negative numbers

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

How to get the separate digits of an int number?

Java 9 introduced a new Stream.iterate method which can be used to generate a stream and stop at a certain condition. This can be used to get all the digits in the number, using the modulo approach.

int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();

Note that this will get the digits in reverse order, but that can be solved either by looping through the array backwards (sadly reversing an array is not that simple), or by creating another stream:

int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();

or

int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length - i]).toArray();

As an example, this code:

int[] a = IntStream.iterate(123400, i -> i > 0, i -> i / 10).map(i -> i % 10).toArray();
int[] b = IntStream.iterate(a.length - 1, i -> i >= 0, i -> i - 1).map(i -> a[i]).toArray();
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));

Will print:

[0, 0, 4, 3, 2, 1]
[1, 2, 3, 4, 0, 0]

Converting String Array to an Integer Array

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();

Maximum and Minimum values for ints

sys.maxsize is not the actually the maximum integer value which is supported. You can double maxsize and multiply it by itself and it stays a valid and correct value.

However, if you try sys.maxsize ** sys.maxsize, it will hang your machine for a significant amount of time. As many have pointed out, the byte and bit size does not seem to be relevant because it practically doesn't exist. I guess python just happily expands it's integers when it needs more memory space. So in general there is no limit.

Now, if you're talking about packing or storing integers in a safe way where they can later be retrieved with integrity then of course that is relevant. I'm really not sure about packing but I know python's pickle module handles those things well. String representations obviously have no practical limit.

So really, the bottom line is: what is your applications limit? What does it require for numeric data? Use that limit instead of python's fairly nonexistent integer limit.

C++ floating point to integer type conversions

the easiest technique is to just assign float to int, for example:

int i;
float f;
f = 34.0098;
i = f;

this will truncate everything behind floating point or you can round your float number before.

Convert int to ASCII and back in Python

Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

Convert integers to strings to create output filenames at run time

For a shorten version. If all the indices are smaller than 10, then use the following:

do i=0,9
   fid=100+i
   fname='OUTPUT'//NCHAR(i+48) //'.txt'
   open(fid, file=fname)
   !....
end do

For a general version:

character(len=5) :: charI
do i = 0,100
   fid = 100 + i
   write(charI,"(A)"), i
   fname ='OUTPUT' // trim(charI) // '.txt'
   open(fid, file=fname)
end do

That's all.

How do I generate random integers within a specific range in Java?

int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

Or take a look to RandomUtils from Apache Commons.

How to get the Enum Index value in C#

In answering this question I define 'value' as the value of the enum item, and index as is positional location in the Enum definition (which is sorted by value). The OP's question asks for 'index' and various answer have interpreted this as either 'index' or 'value' (by my definitions). Sometimes the index is equal to numerical value.

No answer has specifically addressed the case of finding the index (not value) where the Enum is an Enum flag.

Enum Flag
{
    none = 0       // not a flag, thus index =-1
    A = 1 << 0,   // index should be 0
    B = 1 << 1,   // index should be 1 
    C = 1 << 2,   // index should be 2 
    D = 1 << 3,   // index should be 3,
    AandB = A | B // index is composite, thus index = -1 indicating undefined
    All = -1      //index is composite, thus index = -1 indicating undefined
}

In the case of Flag Enums, the index is simply given by

var index = (int)(Math.Log2((int)flag)); //Shows the maths, but is inefficient

However, the above solution is (a) Inefficient as pointed out by @phuclv (Math.Log2() is floating point and costly) and (b) Does not address the Flag.none case, nor any composite flags - flags that are composed of other flags (eg the 'AandB' flag as in my example).

DotNetCore If using dot net core we can address both a) and b) above as follows:

int setbits = BitOperations.PopCount((uint)flag); //get number of set bits
if (setbits != 1) //Finds ECalFlags.none, and all composite flags
    return -1;   //undefined index
int index = BitOperations.TrailingZeroCount((uint)flag); //Efficient bit operation

Not DotNetCore The BitOperations only work in dot net core. See @phuclv answer here for some efficient suggestions https://stackoverflow.com/a/63582586/6630192

  • @user1027167 answer will not work if composite flags are used, as per my comment on his answer
  • Thankyou to @phuclv for suggestions on improving efficiency

sorting integers in order lowest to highest java

You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list

Convert a string to integer with decimal in Python

What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:

s = '234.67'
i = int(round(float(s)))

Otherwise, just do:

s = '234.67'
i = int(float(s))

Definition of int64_t

An int64_t should be 64 bits wide on any platform (hence the name), whereas a long can have different lengths on different platforms. In particular, sizeof(long) is often 4, ie. 32 bits.

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Converting integer to digit list

By looping it can be done the following way :)

num1= int(input('Enter the number'))
sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
y = [] #making a list 
while True:
    if(sum1==0):#checking if the number is not zero so it can break if it is
        break
    d = sum1%10 #last number of your integer is saved in d
    sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
    y.append(d) # appending the last number in the first place

y.reverse()#as last is in first , reversing the number to orginal form
print(y)

Answer becomes

Enter the number2342
[2, 3, 4, 2]

Convert an integer to an array of digits

I can not add comments to the decision of Vladimir, but you can immediately make an array deployed in the right direction. Here is my solution:

public static int[] splitAnIntegerIntoAnArrayOfNumbers (int a) {
    int temp = a;
    ArrayList<Integer> array = new ArrayList<Integer>();
    do{
        array.add(temp % 10);
        temp /= 10;
    } while  (temp > 0);

    int[] arrayOfNumbers = new int[array.size()];
    for(int i = 0, j = array.size()-1; i < array.size(); i++,j--) 
        arrayOfNumbers [j] = array.get(i);
    return arrayOfNumbers;
}

Important: This solution will not work for negative integers.

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

from list of integers, get number closest to a given value

def closest(list, Number):
    aux = []
    for valor in list:
        aux.append(abs(Number-valor))

    return aux.index(min(aux))

This code will give you the index of the closest number of Number in the list.

The solution given by KennyTM is the best overall, but in the cases you cannot use it (like brython), this function will do the work

c++ integer->std::string conversion. Simple function?

Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);

it also provides some safety:

try{
  std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
 ...
}

Java: Integer equals vs. ==

The JVM is caching Integer values. Hence the comparison with == only works for numbers between -128 and 127.

Refer: #Immutable_Objects_.2F_Wrapper_Class_Caching

Check if int is between two numbers

The inconvenience of typing 10 < x && x < 20 is minimal compared to the increase in language complexity if one would allow 10 < x < 20, so the designers of the Java language decided against supporting it.

"Integer number too large" error message for 600851475143

Apart from all the other answers, what you can do is :

long l = Long.parseLong("600851475143");

for example :

obj.function(Long.parseLong("600851475143"));

How do you express binary literals in Python?

How do you express binary literals in Python?

They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a 0 followed by a B or b followed by a series of zeros and ones, for example:

>>> 0b0010101010
170
>>> 0B010101
21

From the Python 3 docs, these are the ways of providing integer literals in Python:

Integer literals are described by the following lexical definitions:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Some examples of integer literals:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

Other ways of expressing binary:

You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):

>>> int('010101', 2)
21

You can optionally have the 0b or 0B prefix:

>>> int('0b0010101010', 2)
170

If you pass it 0 as the base, it will assume base 10 if the string doesn't specify with a prefix:

>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21

Converting from int back to human readable binary:

You can pass an integer to bin to see the string representation of a binary literal:

>>> bin(21)
'0b10101'

And you can combine bin and int to go back and forth:

>>> bin(int('010101', 2))
'0b10101'

You can use a format specification as well, if you want to have minimum width with preceding zeros:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'

What's the maximum value for an int in PHP?

It subjects to architecture of the server on which PHP runs. For 64-bit,

print PHP_INT_MIN . ", ” . PHP_INT_MAX; yields -9223372036854775808, 9223372036854775807

How can I listen for a click-and-hold in jQuery?

Aircoded (but tested on this fiddle)

(function($) {
    function startTrigger(e) {
        var $elem = $(this);
        $elem.data('mouseheld_timeout', setTimeout(function() {
            $elem.trigger('mouseheld');
        }, e.data));
    }

    function stopTrigger() {
        var $elem = $(this);
        clearTimeout($elem.data('mouseheld_timeout'));
    }


    var mouseheld = $.event.special.mouseheld = {
        setup: function(data) {
            // the first binding of a mouseheld event on an element will trigger this
            // lets bind our event handlers
            var $this = $(this);
            $this.bind('mousedown', +data || mouseheld.time, startTrigger);
            $this.bind('mouseleave mouseup', stopTrigger);
        },
        teardown: function() {
            var $this = $(this);
            $this.unbind('mousedown', startTrigger);
            $this.unbind('mouseleave mouseup', stopTrigger);
        },
        time: 750 // default to 750ms
    };
})(jQuery);

// usage
$("div").bind('mouseheld', function(e) {
    console.log('Held', e);
})

T-SQL split string based on delimiter

These all helped me get to this. I am still on 2012 but now have something quick that will allow me to split a string, even if string has varying numbers of delimiters, and grab the nth substring from that string. It's quick too. I know this post is old, but it took me forever to find something so hopefully this will help someone else.

CREATE FUNCTION [dbo].[SplitsByIndex]
(@separator VARCHAR(20)  = ' ', 
 @string    VARCHAR(MAX), 
 @position  INT
)
RETURNS VARCHAR(MAX)
AS
     BEGIN
     DECLARE @results TABLE
     (id   INT IDENTITY(1, 1), 
      chrs VARCHAR(8000)
     );
     DECLARE @outResult VARCHAR(8000);
     WITH X(N)
          AS (SELECT 'Table1'
              FROM(VALUES(0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) T(C)),
          Y(N)
          AS (SELECT 'Table2'
              FROM X A1, 
                   X A2, 
                   X A3, 
                   X A4, 
                   X A5, 
                   X A6, 
                   X A7, 
                   X A8), -- Up to 16^8 = 4 billion
          T(N)
          AS (SELECT TOP (ISNULL(LEN(@string), 0)) ROW_NUMBER() OVER(
                                                   ORDER BY
              (
                  SELECT NULL
              )) - 1 N
              FROM Y),
          Delim(Pos)
          AS (SELECT t.N
              FROM T
              WHERE(SUBSTRING(@string, t.N, LEN(@separator + 'x') - 1) LIKE @separator
                    OR t.N = 0)),
          Separated(value)
          AS (SELECT SUBSTRING(@string, d.Pos + LEN(@separator + 'x') - 1, LEAD(d.Pos, 1, 2147483647) OVER(
                     ORDER BY
              (
                  SELECT NULL
              ))-d.Pos - LEN(@separator))
              FROM Delim d
              WHERE @string IS NOT NULL)
          INSERT INTO @results(chrs)
                 SELECT s.value
                 FROM Separated s
                 WHERE s.value <> @separator;
     SELECT @outResult =
     (
         SELECT chrs
         FROM @results
         WHERE id = @position
     );
     RETURN @outResult;
 END;

This can be used like this:

SELECT [dbo].[SplitsByIndex](' ',fieldname,2) 
from tablename

Remove element of a regular array

In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.

How to access the value of a promise?

When a promise is resolved/rejected, it will call its success/error handler:

var promiseB = promiseA.then(function(result) {
   // do something with result
});

The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   When rejected, promiseB will be rejected. The value passed to
   the promiseB's then handler will be the result of the promise

Armed with this understanding, you can make sense of the following:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

Bad Request - Invalid Hostname IIS7

Don't forget to bind to the IPv6 address as well! I was trying to add a site on 127.0.0.1 using localhost and got the bad request/invalid hostname error. When I pinged localhost it resolved to ::1 since IPv6 was enabled so I just had to add the additional binding to fix the issue.

IIS Site Bindings

How to fix: Error device not found with ADB.exe

Another issue here is that you likely need to turn off "connect as media device" to be able to connect with adb.

Windows equivalent of the 'tail' command

I don't think there is way out of the box. There is no such command in DOS and batch files are far to limited to simulate it (without major pain).

Java System.out.print formatting

Something likes this

public void testPrintOut() {
    int val1 = 8;
    String val2 = "$951.23";
    String val3 = "$215.92";
    String val4 = "$198,301.22";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));

    val1 = 9;
    val2 = "$950.19";
    val3 = "$216.95";
    val4 = "$198,084.26";
    System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}

View list of all JavaScript variables in Google Chrome Console

Is this the kind of output you're looking for?

for(var b in window) { 
  if(window.hasOwnProperty(b)) console.log(b); 
}

This will list everything available on the window object (all the functions and variables, e.g., $ and jQuery on this page, etc.). Though, this is quite a list; not sure how helpful it is...

Otherwise just do window and start going down its tree:

window

This will give you DOMWindow, an expandable/explorable object.

How to use log4net in Asp.net core 2.0

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

You have to set LANG as well, look for files named 'sp1*.msb', and set for instance export LANG=us if you find a file name sp1us.msb. The error message could sure be better :)

Submit form on pressing Enter with AngularJS

Will be slightly neater using a CSS class instead of repeating inline styles.

CSS

input[type=submit] {
    position: absolute;
    left: -9999px;
}

HTML

<form ng-submit="myFunc()">
    <input type="text" ng-model="name" />
    <br />
    <input type="text" ng-model="email" />
    <input type="submit" />
</form>

Loop in Jade (currently known as "Pug") template engine

An unusual but pretty way of doing it

Without index:

each _ in Array(5)
  = 'a'

Will print: aaaaa

With index:

each _, i in Array(5)
  = i

Will print: 01234

Notes: In the examples above, I have assigned the val parameter of jade's each iteration syntax to _ because it is required, but will always return undefined.

Cassandra cqlsh - connection refused

It is a good idea to check the cassandra log if even the server is running. I was getting exactly the same message and unable to do anything with that and then I found out that there are errors in the log and the system is actually not working.

Silly, I know, but could happen...

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

ORDER BY date and time BEFORE GROUP BY name in mysql

Another method:

SELECT * 
FROM (
    SELECT * FROM table_name
    ORDER BY date ASC, time ASC 
) AS sub
GROUP BY name

GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.

I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.

In Java, how do you determine if a thread is running?

To be precise,

Thread.isAlive() returns true if the thread has been started (may not yet be running) but has not yet completed its run method.

Thread.getState() returns the exact state of the thread.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

for mac : check the compatible version of mysql server in workbench>preference>MySql

if it's the same version with your mysql server in: cd /usr/local/

How to get id from URL in codeigniter?

A bit late but this worked for me

  $data_id = $this->input->get('name_of_field');

How to search a specific value in all tables (PostgreSQL)?

There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml() function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:

To search for the string foo across all tables in a schema, the following can be used:

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
  left join xmltable('//table/row' 
                     passing table_rows
                       columns
                         table_row text path 'table_row') as x on true

Note that the use of xmltable requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().

with found_rows as (
  select format('%I.%I', table_schema, table_name) as table_name,
         query_to_xml(format('select to_jsonb(t) as table_row 
                              from %I.%I as t 
                              where t::text like ''%%foo%%'' ', table_schema, table_name), 
                      true, false, '') as table_rows
  from information_schema.tables 
  where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
   cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)

The common table expression (WITH ...) is only used for convenience. It loops through all tables in the public schema. For each table the following query is run through the query_to_xml() function:

select to_jsonb(t)
from some_table t
where t::text like '%foo%';

The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:

<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
  <table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>

The conversion of the complete row to jsonb is done, so that in the result one could see which value belongs to which column.

The above might return something like this:

table_name   |   table_row
-------------+----------------------------------------
public.foo   |  {"id": 1, "some_column": "foobar"}
public.bar   |  {"id": 42, "another_column": "barfoo"}

Online example for Postgres 10+

Online example for older Postgres versions

Error occurred during initialization of boot layer FindException: Module not found

I had the same issue and I fixed it this way:

  1. Deleted all projects from eclipse, not from the computer.
  2. Created a new project and as soon as you write the name of your project, you get another window, in which is written: "Create module-info.java". I just clicked "don't create".
  3. Created a package. Let us call the package mywork.
  4. Created a Java class inside the package myWork. Let us call the class HelloWorld.
  5. I run the file normally and it was working fine.

Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.

What is the difference between XAMPP or WAMP Server & IIS?

WAMP [ Windows, Apache, Mysql, Php]

XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )

Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.

WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.

XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )

IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

What is the correct way to write HTML using Javascript?

You can change the innerHTML or outerHTML of an element on the page instead.

Check element CSS display with JavaScript

If the style was declared inline or with JavaScript, you can just get at the style object:

return element.style.display === 'block';

Otherwise, you'll have to get the computed style, and there are browser inconsistencies. IE uses a simple currentStyle object, but everyone else uses a method:

return element.currentStyle ? element.currentStyle.display :
                              getComputedStyle(element, null).display;

The null was required in Firefox version 3 and below.

Most common C# bitwise operations on enums

In .NET 4 you can now write:

flags.HasFlag(FlagsEnum.Bit4)

Passing multiple argument through CommandArgument of Button in Asp.net

If you want to pass two values, you can use this approach

<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
 OnClick="RemoveFromRole_Click" />

Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand event in this case, which I think is more clean code.

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

On my 10.6 system:

vhosts folder:
 owner:root
 group:wheel
 permissions:755

vhost.conf files:
 owner:root
 group:wheel
 permissions:644

Automapper missing type map configuration or unsupported mapping - Error

I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.

What is the difference between Cloud Computing and Grid Computing?

There are a lot of good answers to this question already but another way to take a look at it is the cloud (ala Amazon's AWS) is good for interactive use cases and the grid (ala High Performance Computing) is good for batch use cases.

Cloud is interactive in that you can get resources on demand via self service. The code you run on VMs in the cloud, such as the Apache web server, can server clients interactively.

Grid is batch in that you submit jobs to a job queue after obtaining the credentials from some HPC authority to do so. The code you run on the grid waits in that queue until there are sufficient resources to execute it.

There are good use cases for both styles of computing.

What's the common practice for enums in Python?

I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

class enumSeason():
    Spring = 0
    Summer = 1
    Fall = 2
    Winter = 3
    def __init__(self, Type):
        self.value = Type
    def __str__(self):
        if self.value == enumSeason.Spring:
            return 'Spring'
        if self.value == enumSeason.Summer:
            return 'Summer'
        if self.value == enumSeason.Fall:
            return 'Fall'
        if self.value == enumSeason.Winter:
            return 'Winter'
    def __eq__(self,y):
       return self.value==y.value

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring

Format number to always show 2 decimal places

var number = 123456.789;


console.log(new Intl.NumberFormat('en-IN', { maximumFractionDigits: 2 }).format(number));

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Best way to test for a variable's existence in PHP; isset() is clearly broken

Object properties can be checked for existence by property_exists

Example from a unit test:

function testPropertiesExist()
{
    $sl =& $this->system_log;
    $props = array('log_id',
                   'type',
                   'message',
                   'username',
                   'ip_address',
                   'date_added');

    foreach($props as $prop) {
        $this->assertTrue(property_exists($sl, $prop),
                           "Property <{$prop}> exists");
    }
}

JQuery string contains check

If you are worrying about Case sensitive change the case and compare the string.

 if (stringvalue.toLocaleLowerCase().indexOf("mytexttocompare")!=-1)
        {

            alert("found");
        }

How to show particular image as thumbnail while implementing share on Facebook?

Here’s how this works all:

  1. You need the ability to access the HTML on the particular webpage you are sharing. It'll probably work site wide too if you use a common header file. I have not tried this, but it should work. You'll just get the same image for all pages if you do this though.

  2. You need to add these HTML meta tags into page in the . It will not work if you put it in the . Make sure to customize per your a) image, b) description, c) URL, and d) title.

A Real Example.

<meta property="og:image" content="http://www.coachesneedsocial.com/wp-content/uploads/2014/12/BannerWCircleImages-1.jpg" />

<meta property="og:description" content="Coaches share their secrets to success so you can rock 2015." />

<meta property="og:url"content="http://www.coachesneedsocial.com/coacheswisdomtelesummit/" />

<meta property="og:title" content="Coaches Wisdom Telesummit" />
  1. Save
  2. Open a fresh Facebook post, and retry the page you wanted to share.
  3. If you are having trouble… you can debug it with this Facebook tool. It looks more geeky than it is. It tells you what Facebook is seeing when you post in the URL to share.

https://developers.facebook.com/tools/debug/og/object/

Big Tip.. make sure the “quote marks” are the same in your HTML (they should look like 2 straight marks and no curves… sometimes programs change these to different fonts and it goofs up the code.

How to declare a global variable in php?

You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.

Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.

How do I set the figure title and axes labels font size in Matplotlib?

Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.

E.g., to make the x-axis tick label size small:

ax.xaxis.set_tick_params(labelsize='small')

or, to make the y-axis tick label large:

ax.yaxis.set_tick_params(labelsize='large')

You can also enter the labelsize as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.

Java code for getting current time

try this:

final String currentTime    = String.valueOf(System.currentTimeMillis());

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

How Stuff and 'For Xml Path' work in SQL Server?

PATH mode is used in generating XML from a SELECT query

1. SELECT   
       ID,  
       Name  
FROM temp1
FOR XML PATH;  

Ouput:
<row>
<ID>1</ID>
<Name>aaa</Name>
</row>

<row>
<ID>1</ID>
<Name>bbb</Name>
</row>

<row>
<ID>1</ID>
<Name>ccc</Name>
</row>

<row>
<ID>1</ID>
<Name>ddd</Name>
</row>

<row>
<ID>1</ID>
<Name>eee</Name>
</row>

The Output is element-centric XML where each column value in the resulting rowset is wrapped in an row element. Because the SELECT clause does not specify any aliases for the column names, the child element names generated are the same as the corresponding column names in the SELECT clause.

For each row in the rowset a tag is added.

2.
SELECT   
       ID,  
       Name  
FROM temp1
FOR XML PATH('');

Ouput:
<ID>1</ID>
<Name>aaa</Name>
<ID>1</ID>
<Name>bbb</Name>
<ID>1</ID>
<Name>ccc</Name>
<ID>1</ID>
<Name>ddd</Name>
<ID>1</ID>
<Name>eee</Name>

For Step 2: If you specify a zero-length string, the wrapping element is not produced.

3. 

    SELECT   

           Name  
    FROM temp1
    FOR XML PATH('');

    Ouput:
    <Name>aaa</Name>
    <Name>bbb</Name>
    <Name>ccc</Name>
    <Name>ddd</Name>
    <Name>eee</Name>

4. SELECT   
        ',' +Name  
FROM temp1
FOR XML PATH('')

Ouput:
,aaa,bbb,ccc,ddd,eee

In Step 4 we are concatenating the values.

5. SELECT ID,
    abc = (SELECT   
            ',' +Name  
    FROM temp1
    FOR XML PATH('') )
FROM temp1

Ouput:
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee
1   ,aaa,bbb,ccc,ddd,eee


6. SELECT ID,
    abc = (SELECT   
            ',' +Name  
    FROM temp1
    FOR XML PATH('') )
FROM temp1 GROUP by iD

Ouput:
ID  abc
1   ,aaa,bbb,ccc,ddd,eee

In Step 6 we are grouping the date by ID.

STUFF( source_string, start, length, add_string ) Parameters or Arguments source_string The source string to modify. start The position in the source_string to delete length characters and then insert add_string. length The number of characters to delete from source_string. add_string The sequence of characters to insert into the source_string at the start position.

SELECT ID,
    abc = 
    STUFF (
        (SELECT   
                ',' +Name  
        FROM temp1
        FOR XML PATH('')), 1, 1, ''
    )
FROM temp1 GROUP by iD

Output:
-----------------------------------
| Id        | Name                |
|---------------------------------|
| 1         | aaa,bbb,ccc,ddd,eee |
-----------------------------------

Increase heap size in Java

Several people pointed out the specific answers for heap size with the jvm options of -Xms and -Xms. I want to point out that this is not the only type of memory options for the jvm. Specifically if you are get stack over flows, then you'll want to increase the size of the stack by adding an additional option like -Xss8m.

For this problem, the jvm options of something like -Xms2g -Xmx6g -Xss8m would be a solution.

I'm sharing this information as my google searches on how to increase jvm memory took me to this solution, and the solutions didn't work with high amounts of memory allocation. Once I figured out what the specific settings were for, I was able to google how to increase the stack size and found the missing param. :) Hope this saves others time, as it would of saved me a ton of time. :)

Create File If File Does Not Exist

You don't even need to do the check manually, File.Open does it for you. Try:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

jQuery Get Selected Option From Dropdown

Try this for value...

$("select#id_of_select_element option").filter(":selected").val();

or this for text...

$("select#id_of_select_element option").filter(":selected").text();

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.

However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.

for example:

filename = 'cd.pkl'
with open(filename, 'wb') as f:
    classification_dict = pickle.load(f)

This will over-write the pickled file. You might have done this by mistake before using:

...
open(filename, 'rb') as f:

And then got the EOFError because the previous block of code over-wrote the cd.pkl file.

When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails

How to deal with SQL column names that look like SQL keywords?

In Apache Drill, use backquotes:

select `from` from table;

Foreign keys in mongo?

We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: ['bio101', 'bio102']   // <= ids of the courses
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

More: MongoDB Schema Design

The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

Embedded document

  1. Suitable for one-to-few.
  2. Advantage: no need to perform additional queries to another document.
  3. Disadvantage: cannot manage the entity of embedded documents individually.

Example:

student
{
  name: 'Kate Monster',
  addresses : [
     { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
     { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
  ]
}

Child referencing

Like the student/course example above.

Parent referencing

Suitable for one-to-squillions, such as log messages.

host
{
    _id : ObjectID('AAAB'),
    name : 'goofy.example.com',
    ipaddr : '127.66.66.66'
}

logmsg
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : 'cpu is on fire!',
    host: ObjectID('AAAB')       // Reference to the Host document
}

Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

References:

  1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
  2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
  3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
  4. Model One-to-Many Relationships with Document References

Can you require two form fields to match with HTML5?

A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.

Unfortunately, you also need to escape the regex, for which no standard function exists.

<form>
    <input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
    <input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
    function escapeRegExp(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    }
</script>

Jquery function return value

I'm not entirely sure of the general purpose of the function, but you could always do this:

function getMachine(color, qty) {
    var retval;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            retval = thisArray[3];
            return false;
        }
    });
    return retval;
}

var retval = getMachine(color, qty);

Swift_TransportException Connection could not be established with host smtp.gmail.com

In my case, I was using Laravel 5 and I had forgotten to change the mail globals in the .env file that is located in your directory root folder (these variables override your mail configuration)

   MAIL_DRIVER=smtp
   MAIL_HOST=smtp.gmail.com
   MAIL_PORT=465
   [email protected]
   MAIL_PASSWORD=yourpassword

by default, the mailhost is:

   MAIL_HOST=mailtraper.io

I was getting the same error but that worked for me.

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.

How do you use "git --bare init" repository?

It is nice to verify that the code you pushed actually got committed.

You can get a log of changes on a bare repository by explicitly setting the path using the --relative option.

$ cd test_repo
$ git log --relative=/

This will show you the committed changes as if this was a regular git repo.

How do I ignore ampersands in a SQL script running from SQL Plus?

You can set the special character, which is looked for upon execution of a script, to another value by means of using the SET DEFINE <1_CHARACTER>

By default, the DEFINE function itself is on, and it is set to &

It can be turned off - as mentioned already - but it can be avoided as well by means of setting it to a different value. Be very aware of what sign you set it to. In the below example, I've chose the # character, but that choice is just an example.

SQL> select '&var_ampersand #var_hash' from dual;
Enter value for var_ampersand: a value

'AVALUE#VAR_HASH'
-----------------
a value #var_hash

SQL> set define #
SQL> r
  1* select '&var_ampersand #var_hash' from dual
Enter value for var_hash: another value

'&VAR_AMPERSANDANOTHERVALUE'
----------------------------
&var_ampersand another value

SQL>

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

In HTTP the error occurs.

Set permission for localhost in bellow label(Accept requests from these HTTP referrers (web sites)).

It worked for me.

What is the difference between & and && in Java?

I think my answer can be more understandable:

There are two differences between & and &&.

If they use as logical AND

& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.

when & and && as logical AND, there is a difference:

when use && as logical AND, if the left expression result is false, the right expression will not execute.

Take the example :

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute

}

If using &:

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 

}

An other more example:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

& can be used as bit operator

& can be used as Bitwise AND operator, && can not.

The bitwise AND " &" operator produces 1 if and only if both of the bits in its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 

From the wiki page:

http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

How to solve java.lang.OutOfMemoryError trouble in Android

I see only two options:

  1. You have memory leaks in your application.
  2. Devices do not have enough memory when running your application.

Number of lines in a file in Java

This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.

public static int countLinesOld(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the LineNumberReader solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:

public static int countLinesNew(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];

        int readChars = is.read(c);
        if (readChars == -1) {
            // bail out if nothing to read
            return 0;
        }

        // make it easy for the optimizer to tune this loop
        int count = 0;
        while (readChars == 1024) {
            for (int i=0; i<1024;) {
                if (c[i++] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        // count remaining characters
        while (readChars != -1) {
            System.out.println(readChars);
            for (int i=0; i<readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        return count == 0 ? 1 : count;
    } finally {
        is.close();
    }
}

Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with System.nanoTime(). You can see that countLinesOld has a few outliers, and countLinesNew has none and while it's only a bit faster, the difference is statistically significant. LineNumberReader is clearly slower.

Benchmark Plot

Close Window from ViewModel

You can use Messenger from MVVMLight toolkit. in your ViewModel send a message like this:
Messenger.Default.Send(new NotificationMessage("Close"));
then in your windows code behind, after InitializeComponent, register for that message like this:

Messenger.Default.Register<NotificationMessage>(this, m=>{
    if(m.Notification == "Close") 
    {
        this.Close();
    }
   });

you can find more about MVVMLight toolkit here: MVVMLight toolkit on Codeplex

Notice that there is not a "no code-behind at all rule" in MVVM and you can do registering for messages in a view code-behind.

jQuery convert line breaks to br (nl2br equivalent)

Solution

Use this code

jQuery.nl2br = function(varTest){
  return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48+, you can access the print preview via the following steps:

  1. Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.

  2. Hit Esc to open the additional drawer.

  3. If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.

  4. Check the 'Emulate print media' checkbox.

From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.

Image of Chrome 49+ Print Preview option in Dev Tools

Printing with sed or awk a line following a matching pattern

It's the line after that match that you're interesting in, right? In sed, that could be accomplished like so:

sed -n '/ABC/{n;p}' infile

Alternatively, grep's A option might be what you're looking for.

-A NUM, Print NUM lines of trailing context after matching lines.

For example, given the following input file:

foo
bar
baz
bash
bongo

You could use the following:

$ grep -A 1 "bar" file
bar
baz
$ sed -n '/bar/{n;p}' file
baz

Hope that helps.

How do I compile a .c file on my Mac?

Just for the record in modern times,

for 2017 !

1 - Just have updated Xcode on your machine as you normally do

2 - Open terminal and

$ xcode-select --install

it will perform a short install of a minute or two.

3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"

Note - confusingly this is under the "macOS" tab.

choose this one

Select "C" language on the next screen...

enter image description here

4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.

5 - You're golden! You can now enjoy c with Mac and Xcode.

you're golden

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

actually it's an ownership problem

try to:

ls -l /var/run/asterisk/asterisk.ctl

you will see that the file has ownership of 'root'

although you have changed the ownership with:

chown -R asterisk /var/run/asterisk

once you restart the asterisk server the ownership gets back to the 'root' again

they should be for 'asterisk:asterisk' user and group

Basem Hegazy

Does C# support multiple inheritance?

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }

How to clear a data grid view

Firstly, null the data source:

this.dataGridView.DataSource = null;

Then clear the rows:

this.dataGridView.Rows.Clear();

Then set the data source to the new list:

this.dataGridView.DataSource = this.GetNewValues();

SSIS expression: convert date to string

For SSIS you could go with:

RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" +  (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())

Expression builder screen:

Expression builder screen

Simplest/cleanest way to implement a singleton in JavaScript

In ES6 the right way to do this is:

_x000D_
_x000D_
class MyClass {
  constructor() {
    if (MyClass._instance) {
      throw new Error("Singleton classes can't be instantiated more than once.")
    }
    MyClass._instance = this;

    // ... Your rest of the constructor code goes after this
  }
}

var instanceOne = new MyClass() // Executes succesfully
var instanceTwo = new MyClass() // Throws error
_x000D_
_x000D_
_x000D_

Or, if you don't want an error to be thrown on the second instance creation, you can just return the last instance, like so:

_x000D_
_x000D_
class MyClass {
  constructor() {
    if (MyClass._instance) {
      return MyClass._instance
    }
    MyClass._instance = this;

    // ... Your rest of the constructor code goes after this
  }
}

var instanceOne = new MyClass()
var instanceTwo = new MyClass()

console.log(instanceOne === instanceTwo) // Logs "true"
_x000D_
_x000D_
_x000D_

Adding images to an HTML document with javascript

With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).

<head>
    <script type="text/javascript">
        function insert(){
            var src = document.getElementById("gamediv");
            var img = document.createElement("img");
            img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
            src.appendChild(img);
        }
     </script>
 </head>
 <body>
     <div id="gamediv">
         <script type="text/javascript">
             insert();
         </script>
     </div>
 </body>

Convert string to a variable name

assign is what you are looking for.

assign("x", 5)

x
[1] 5

but buyer beware.

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

jQuery: get the file name selected from <input type="file" />

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepath nonsense, you straight up get the file that was uploaded:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

To get the name of the file:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

If I were to upload a PNG, it would return image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

$("#imgUpload")[0].files[0].size

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Count all duplicates of each value

If you want to check repetition more than 1 in descending order then implement below query.

SELECT   duplicate_data,COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
HAVING   COUNT(duplicate_data) > 1
ORDER BY COUNT(duplicate_data) DESC

If want simple count query.

SELECT   COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
ORDER BY COUNT(duplicate_data) DESC

Count distinct value pairs in multiple columns in SQL

To get a count of the number of unique combinations of id, name and address:

SELECT Count(*)
FROM   (
        SELECT DISTINCT
               id
             , name
             , address
        FROM   your_table
       ) As distinctified

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

jQuery preventDefault() not triggered

Update

And there's your problem - you do have to click event handlers for some a elements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.

Here's a working fiddle that shows the behaviour you want.

This should be your code:

$(document).ready(function(){


    $('#tabs div.tab').hide();
    $('#tabs div.tab:first').show();
    $('#tabs ul li:first').addClass('active');

    $("div.subtab_left li.notebook a").click(function(e) {
        e.stopImmediatePropagation();
        alert("asdasdad");
        return false;
    });

    $('#tabs ul li a').click(function(){
        alert("Handling link click");
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div.tab').hide();
        $(currentTab).show();
        return false;
    });

});

Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation() is used to stop the other click handler from firing while return false is used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation).

Play around with this, if you remove the e.stopImmediatePropagation() you'll find that the second click handler's alert will fire after the first alert. Removing the return false will have no effect on this behaviour but will cause links to be followed by the browser.

Note

A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.


  1. I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?

    If you've attached other event handlers to the link, you should look into event.stopPropagation() and event.stopImmediatePropagation() instead. Note that return false is equivalent to calling both event.preventDefault and event.stopPropagation()ref

  2. In your second code snippet, e is not defined. So an error would thrown at e.preventDefault() and the next lines never execute. In other words

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    should be

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

Here's a working example showing that this code indeed does work and that return false is not really required if you only want to stop the following of a link.

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

Tensorflow import error: No module named 'tensorflow'

In Anaconda Prompt (Anaconda 3), Type: conda install tensorflow command

This fix my issue in my Anaconda with Python 3.8.

Reference: https://panjeh.medium.com/modulenotfounderror-no-module-named-tensorflow-in-jupeter-1425afe23bd7

What is a wrapper class?

I currently used a wrapper class for my project and the main benefits I get (just a single benefit to widen the topic explanation):

Exception handling: My main class ,that another class wraps, has methods that are throwing exceptions if occurs any, so I created a wrapper class that handles the exceptions and logs them immediately. So, in my main scope, there is no exception handling. I just call a method and do something.

Easy Usage: I can easily initiate the object. Normally initiating phase is constructed of a lot of steps.

Code Readability: When another programmer opens my code, the code will seem very clear and easy to manipulate.

Hiding the Details: If you are generating a class that another programmer is going to use, then you can wrap the details like "error handling, exception handling, logging messages and etc..." so that the programmer will not be have to handle the chaos, just simply uses the methods.

List vs tuple, when to use each?

But if I am the one who designs the API and gets to choose the data types, then what are the guidelines?

For input parameters it's best to accept the most generic interface that does what you need. It is seldom just a tuple or list - more often it's sequence, sliceable or even iterable. Python's duck typing usually gets it for free, unless you explicitly check input types. Don't do that unless absolutely unavoidable.

For the data that you produce (output parameters) just return what's most convenient for you, e.g. return whatever datatype you keep or whatever your helper function returns.

One thing to keep in mind is to avoid returning a list (or any other mutable) that's part of your state, e.g.

class ThingsKeeper
    def __init__(self):
        self.__things = []

    def things(self):
        return self.__things  #outside objects can now modify your state

    def safer(self):
        return self.__things[:]  #it's copy-on-write, shouldn't hurt performance

Given two directory trees, how can I find out which files differ by content?

To report differences between dirA and dirB, while also updating/syncing.

rsync -auv <dirA> <dirB>

How to sort ArrayList<Long> in decreasing order?

Using List.sort() and Comparator.comparingLong()

numberList.sort(Comparator.comparingLong(x -> -x));

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Okay- here we go:

(In a "silverlight app": please check first that silverlight is checked in "web" in your server project "properties"- If that didnt solve it then try this beneath)

On first time do: run this first: devenv.exe /ResetSettings and 1: In top menu click on debug tag 2: click options and settings 3: In "debugging" and under "general" find "enable .net framework source stepping" 4: Tick the box. 5: And now all the symbols will be downloaded and reconfigured :)

If it happens again after the above just clear the folder where the symbols are:

1: In top menu click on debug tag 2: click options and settings 3: In "debugging" and under "symbols" find the button "empty symbol cache" and click it.

How to Insert Double or Single Quotes

Assuming your data is in column A, add a formula to column B

="'" & A1 & "'" 

and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.

VB.NET Connection string (Web.Config, App.Config)

If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:

    Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)

Hope that helps someone.

How to add a “readonly” attribute to an <input>?

I think "disabled" excludes the input from being sent on the POST

What is (functional) reactive programming?

According to the previous answers, it seems that mathematically, we simply think in a higher order. Instead of thinking a value x having type X, we think of a function x: T ? X, where T is the type of time, be it the natural numbers, the integers or the continuum. Now when we write y := x + 1 in the programming language, we actually mean the equation y(t) = x(t) + 1.

Difference between pre-increment and post-increment in a loop?

There can be a difference for loops. This is the practical application of post/pre-increment.

        int i = 0;
        while(i++ <= 10) {
            Console.Write(i);
        }
        Console.Write(System.Environment.NewLine);

        i = 0;
        while(++i <= 10) {
            Console.Write(i);
        }
        Console.ReadLine();

While the first one counts to 11 and loops 11 times, the second does not.

Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

I'll start with your last question:

Why are these new categories needed?

The C++ standard contains many rules that deal with the value category of an expression. Some rules make a distinction between lvalue and rvalue. For example, when it comes to overload resolution. Other rules make a distinction between glvalue and prvalue. For example, you can have a glvalue with an incomplete or abstract type but there is no prvalue with an incomplete or abstract type. Before we had this terminology the rules that actually need to distinguish between glvalue/prvalue referred to lvalue/rvalue and they were either unintentionally wrong or contained lots of explaining and exceptions to the rule a la "...unless the rvalue is due to unnamed rvalue reference...". So, it seems like a good idea to just give the concepts of glvalues and prvalues their own name.

What are these new categories of expressions? How do these new categories relate to the existing rvalue and lvalue categories?

We still have the terms lvalue and rvalue that are compatible with C++98. We just divided the rvalues into two subgroups, xvalues and prvalues, and we refer to lvalues and xvalues as glvalues. Xvalues are a new kind of value category for unnamed rvalue references. Every expression is one of these three: lvalue, xvalue, prvalue. A Venn diagram would look like this:

    ______ ______
   /      X      \
  /      / \      \
 |   l  | x |  pr  |
  \      \ /      /
   \______X______/
       gl    r

Examples with functions:

int   prvalue();
int&  lvalue();
int&& xvalue();

But also don't forget that named rvalue references are lvalues:

void foo(int&& t) {
  // t is initialized with an rvalue expression
  // but is actually an lvalue expression itself
}

How to parse a JSON file in swift?

Below is a Swift Playground example:

import UIKit

let jsonString = "{\"name\": \"John Doe\", \"phone\":123456}"

let data = jsonString.data(using: .utf8)

var jsonObject: Any
do {
    jsonObject = try JSONSerialization.jsonObject(with: data!) as Any

    if let obj = jsonObject as? NSDictionary {
        print(obj["name"])
    }
} catch {
    print("error")
}

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How to execute 16-bit installer on 64-bit Win7?

You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.

Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.

What would be the best way to get round this problem?

If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.

If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.

It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.

Aren't promises just callbacks?

Yes, Promises are asynchronous callbacks. They can't do anything that callbacks can't do, and you face the same problems with asynchrony as with plain callbacks.

However, Promises are more than just callbacks. They are a very mighty abstraction, allow cleaner and better, functional code with less error-prone boilerplate.

So what's the main idea?

Promises are objects representing the result of a single (asynchronous) computation. They resolve to that result only once. There's a few things what this means:

Promises implement an observer pattern:

  • You don't need to know the callbacks that will use the value before the task completes.
  • Instead of expecting callbacks as arguments to your functions, you can easily return a Promise object
  • The promise will store the value, and you can transparently add a callback whenever you want. It will be called when the result is available. "Transparency" implies that when you have a promise and add a callback to it, it doesn't make a difference to your code whether the result has arrived yet - the API and contracts are the same, simplifying caching/memoisation a lot.
  • You can add multiple callbacks easily

Promises are chainable (monadic, if you want):

  • If you need to transform the value that a promise represents, you map a transform function over the promise and get back a new promise that represents the transformed result. You cannot synchronously get the value to use it somehow, but you can easily lift the transformation in the promise context. No boilerplate callbacks.
  • If you want to chain two asynchronous tasks, you can use the .then() method. It will take a callback to be called with the first result, and returns a promise for the result of the promise that the callback returns.

Sounds complicated? Time for a code example.

var p1 = api1(); // returning a promise
var p3 = p1.then(function(api1Result) {
    var p2 = api2(); // returning a promise
    return p2; // The result of p2 …
}); // … becomes the result of p3

// So it does not make a difference whether you write
api1().then(function(api1Result) {
    return api2().then(console.log)
})
// or the flattened version
api1().then(function(api1Result) {
    return api2();
}).then(console.log)

Flattening does not come magically, but you can easily do it. For your heavily nested example, the (near) equivalent would be

api1().then(api2).then(api3).then(/* do-work-callback */);

If seeing the code of these methods helps understanding, here's a most basic promise lib in a few lines.

What's the big fuss about promises?

The Promise abstraction allows much better composability of functions. For example, next to then for chaining, the all function creates a promise for the combined result of multiple parallel-waiting promises.

Last but not least Promises come with integrated error handling. The result of the computation might be that either the promise is fulfilled with a value, or it is rejected with a reason. All the composition functions handle this automatically and propagate errors in promise chains, so that you don't need to care about it explicitly everywhere - in contrast to a plain-callback implementation. In the end, you can add a dedicated error callback for all occurred exceptions.

Not to mention having to convert things to promises.

That's quite trivial actually with good promise libraries, see How do I convert an existing callback API to promises?

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

Using Font Awesome icon for bullet points, with a single list item element

I'd like to build upon some of the answers above and given elsewhere and suggest using absolute positioning along with the :before pseudo class. A lot of the examples above (and in similar questions) are utilizing custom HTML markup, including Font Awesome's method of handling. This goes against the original question, and isn't strictly necessary.

DEMO HERE

ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  position: relative;
  padding-left: 20px;
  margin-bottom: 10px
}

li:before {
  position: absolute;
  top: 0;
  left: 0;
  font-family: FontAwesome;
  content: "\f058";
  color: green;
}

That's basically it. You can get the ISO value for use in CSS content on the Font Awesome cheatsheet. Simply use the last 4 alphanumerics prefixed with a backslash. So [&#xf058;] becomes \f058

Java executors: how to be notified, without blocking, when a task completes?

Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task.

You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService. Or, see below for a mechanism built into Java 8.

class CallbackTask implements Runnable {

  private final Runnable task;

  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  public void run() {
    task.run();
    callback.complete();
  }

}

With CompletableFuture, Java 8 included a more elaborate means to compose pipelines where processes can be completed asynchronously and conditionally. Here's a contrived but complete example of notification.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class GetTaskNotificationWithoutBlocking {

  public static void main(String... argv) throws Exception {
    ExampleService svc = new ExampleService();
    GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking();
    CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
    f.thenAccept(listener::notify);
    System.out.println("Exiting main()");
  }

  void notify(String msg) {
    System.out.println("Received message: " + msg);
  }

}

class ExampleService {

  String work() {
    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
    char[] str = new char[5];
    ThreadLocalRandom current = ThreadLocalRandom.current();
    for (int idx = 0; idx < str.length; ++idx)
      str[idx] = (char) ('A' + current.nextInt(26));
    String msg = new String(str);
    System.out.println("Generated message: " + msg);
    return msg;
  }

  public static void sleep(long average, TimeUnit unit) {
    String name = Thread.currentThread().getName();
    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
    try {
      unit.sleep(timeout);
      System.out.println(name + " awoke.");
    } catch (InterruptedException abort) {
      Thread.currentThread().interrupt();
      System.out.println(name + " interrupted.");
    }
  }

  public static long exponential(long avg) {
    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
  }

}

Convert a list to a dictionary in Python

I am not sure if this is pythonic, but seems to work

def alternate_list(a):
   return a[::2], a[1::2]

key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

Node.js - Maximum call stack size exceeded

I found a dirty solution:

/bin/bash -c "ulimit -s 65500; exec /usr/local/bin/node --stack-size=65500 /path/to/app.js"

It just increase call stack limit. I think that this is not suitable for production code, but I needed it for script that run only once.

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 5+

extension Date {
    
    func get(_ type: Calendar.Component)-> String {
        let calendar = Calendar.current
        let t = calendar.component(type, from: self)
        return (t < 10 ? "0\(t)" : t.description)
    }
}

Usage:

print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18 

How to get all privileges back to the root user in MySQL?

Log in as root, then run the following MySQL commands:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

can't start MySql in Mac OS 10.6 Snow Leopard

First of all can I just say that I really really love the Internet community for all that it does in providing answers to everybody. I don't post a lot but everybody's posting here and on so many boards helped me so much! None of them gave me the right answer mind you, but here is my unique solution to this nightmare of a spending 2 solid days trying to install MySQL 5.5.9 on Snow Leopard 10.6. Skip to bottom for resolution.

Here's what happened.

I had a server crash recently. The server was rebuilt and of course MySQL 5.5.8 didn't work. What a worthless piece. I had 5.1.54 on my other machine. That had been a pain to install as well but not like this.

I had all sorts of issues installing with the dmg from mysql.org, installing mysql5 using macports, uninstalling trying to revert to 5.1.54 (couldn't because I couldn't find the receipt file with that info even though I followed the directions). After rming everything I could find related to mysql and then reinstalling 5.5.8 everything worked! Until I rebooted... ? I looked in my system preference mysql pane and found mysql server wasn't starting. (skip to end for resolution)

My first error (super common) included: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' and numerous other EXTREMELY common issues related to mysql.sock http://forums.mysql.com/read.php?11,9689,13272

Here were things I tried: 1)Create /etc/my.cnf file with the proper paths to mysql.sock. I even tried modifying mysql.server with vi directly. Modifying the php.ini was worthless. Nothing worked because MySQL wasn't starting, therefore it wasn't creating mysql.sock in the first place. Maybe you can point to the directory it is being created, and not the actual full file path i.e. not /tmp/mysql.sock but /tmp It was suggested but wasn't working because there was no mysql.sock because mysqld wasn't spawning.

2)Basedir and datadir modifications didn't work because there was no mysql.sock to point too.

Why? Because the mysql daemon wasn't starting. Without anything to start mysqld and thereby create mysql.sock I was doomed. They are an important part of the solution but if you try them and still get errors, you will know why.

3)sudo chown -R root:wheel /Library/StartupItems/MySQLCOM/

didn't solve my problem. I ended up having that folder and all items set to root:wheel though in the end, because it was one of the many things recommended and its working. Maybe it could remain _mysql but wheel works.

4)Copy mysql.sock from another machine. Doesn't work. I had searched and searched my new machine and couldn't find mysql.sock. I was using find / | grep mysql.sock because locate mysql wasn't finding anything. Besides I was trying so many different things it wasn't updating enough to find my new installs. I now like find much more than locate, even though you can update the locate db. Anyhow you can't copy mysql.sock, even if you tar it because its a 0 byte file.

THE RESOLUTION: I finally stumbled onto the solution. I finally just typed mysqld from command line while I was in the proper bin directory. It said another process was running. _mysql was spawning a process that I could see in the Activity Monitor. I killed the active mysql process and when I typed mysqld again I found it was creating my mysql.sock file in the /private/tmp/mysql.sock

The mysql pref pane wouldn't start the right process on login, so I just disabled that for being worthless. It wouldn't start mysql because no mysql.sock was being created.

By then I had figured out that mysqld creates mysql.sock. I then found /opt/local/mysql/ and typed "open bin" in the terminal window. This opened the directory with mysqld in it.

I went to login items in the system preferences in my account settings and dragged and dropped the mysqld file onto the startup items there. THAT worked. Finally!

It works flawlessly because mysqld is starting up at login, which means mysql.sock is being created so no more errors about not being able to find mysql.sock.

How to make readonly all inputs in some div in Angular2?

Just set css property of container div 'pointer-events' as none i.e. 'pointer-events:none;'

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

Console app arguments, how arguments are passed to Main method

All answers are awesome and explained everything very well

but I just want to point out different way for passing args to main method

in visual studio

  1. right click on Project then choose Properties
  2. go to Debug tab then on the Start Options section provide the app with your args

like this image

Properties window

and happy knowing secrets

Launching an application (.EXE) from C#?

System.Diagnostics.Process.Start("PathToExe.exe");

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

Sleep Command in T-SQL?

You can also "WAITFOR" a "TIME":

    RAISERROR('Im about to wait for a certain time...', 0, 1) WITH NOWAIT
    WAITFOR TIME '16:43:30.000'
    RAISERROR('I waited!', 0, 1) WITH NOWAIT

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

What happens if you mount to a non-empty mount point with fuse?

Just add -o nonempty in command line, like this:

s3fs -o nonempty  <bucket-name> </mount/point/>

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.

Ex:

byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had the exact same problem, found that I was missing

<mdb>  
  <resource-adapter-ref resource-adapter-name="hornetq-ra"/>  
  <bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>  
</mdb>  

under

<subsystem xmlns="urn:jboss:domain:ejb3:1.2">  

in standalone/configuration/standalone.xml

How do I convert uint to int in C#?

I would say using tryParse, it'll return 'false' if the uint is to big for an int.
Don't forget that a uint can go much bigger than a int, as long as you going > 0

A simple explanation of Naive Bayes Classification

Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.

In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.

During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.

So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.

The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.

In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.

Now I come to your other question about Naive Bayes.

To demonstrate the concept of Naïve Bayes Classification, consider the example given below:

enter image description here

As indicated, the objects can be classified as either GREEN or RED. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.

Since there are twice as many GREEN objects as RED, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership GREEN rather than RED. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of GREEN and RED objects, and often used to predict outcomes before they actually happen.

Thus, we can write:

Prior Probability of GREEN: number of GREEN objects / total number of objects

Prior Probability of RED: number of RED objects / total number of objects

Since there is a total of 60 objects, 40 of which are GREEN and 20 RED, our prior probabilities for class membership are:

Prior Probability for GREEN: 40 / 60

Prior Probability for RED: 20 / 60

Having formulated our prior probability, we are now ready to classify a new object (WHITE circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN (or RED) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

enter image description here

enter image description here

From the illustration above, it is clear that Likelihood of X given GREEN is smaller than Likelihood of X given RED, since the circle encompasses 1 GREEN object and 3 RED ones. Thus:

enter image description here

enter image description here

Although the prior probabilities indicate that X may belong to GREEN (given that there are twice as many GREEN compared to RED) the likelihood indicates otherwise; that the class membership of X is RED (given that there are more RED objects in the vicinity of X than GREEN). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

enter image description here

Finally, we classify X as RED since its class membership achieves the largest posterior probability.

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

"Cannot start compilation: the output path is not specified for module..."

I'm answering this so that I can find the solution when I have to google this error again.

Set project compile output path to path_of_the_project_folder/out. That's what is working today. The intellj documentation makes it seem like we can select any folder but that's not the case.

How to get the selected row values of DevExpress XtraGrid?

Here is the way that I've followed,

int[] selRows = ((GridView)gridControl1.MainView).GetSelectedRows();
DataRowView selRow = (DataRowView)(((GridView)gridControl1.MainView).GetRow(selRows[0]));
txtName.Text = selRow["name"].ToString();

Also you can iterate through selected rows using the selRows array. Here the code describes how to get data only from first selected row. You can insert these code lines to click event of the grid.

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Try putting opacity:0; your select element will be invisible but the options will be visible when you click on it.

ASP.NET Web Api: The requested resource does not support http method 'GET'

I don't know if this can be related to the OP's post but I was missing the [HttpGet] annotation and that was what was causing the error, as stated by @dinesh_ravva methods are assumed to be HttpPost by default.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

set the width of select2 input (through Angular-ui directive)

Wanted to add my solution here as well. This is similar to Ravindu's answer above.

I added width: 'resolve', as a property within the select2:

    $('#searchFilter').select2({
        width: 'resolve',
    });

Then I added a min-width property to select2-container with !important:

.select2-container {
    min-width: 100% !important;
}

On the select element, the style='100px !important;' attribute needed !important to work:

<select class="form-control" style="width: 160px;" id="searchFilter" name="searchfilter[]">

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

How can I conditionally require form inputs with AngularJS?

In AngularJS (version 1.x), there is a build-in directive ngRequired

<input type='email'
       name='email'
       ng-model='user.email' 
       placeholder='[email protected]'
       ng-required='!user.phone' />

<input type='text'
       ng-model='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!user.email' /> 

In Angular2 or above

<input type='email'
       name='email'
       [(ngModel)]='user.email' 
       placeholder='[email protected]'
       [required]='!user.phone' />

<input type='text'
       [(ngModel)]='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       [required]='!user.email' /> 

Android Studio - mergeDebugResources exception

Had to change build tools version from some old one in build.gradle for project module:

android {
    ...
    buildToolsVersion "24.0.2"
    ...
}

How to calculate combination and permutation in R?

The Combinations package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use

install.packages("Combinations", repos = "http://www.omegahat.org/R")

See the documentation at http://www.omegahat.org/Combinations/

How to get all values from python enum class?

class enum.Enum is a class that solves all your enumeration needs, so you just need to inherit from it, and add your own fields. Then from then on, all you need to do is to just call it's attributes: name & value:

from enum import Enum

class Letter(Enum):
   A = 1
   B = 2
   C = 3

print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}

Active Directory LDAP Query by sAMAccountName and Domain

First, modify your search filter to only look for users and not contacts:

(&(objectCategory=person)(objectClass=user)(sAMAccountName=BTYNDALL))

You can enumerate all of the domains of a forest by connecting to the configuration partition and enumerating all the entries in the partitions container. Sorry I don't have any C# code right now but here is some vbscript code I've used in the past:

Set objRootDSE = GetObject("LDAP://RootDSE")
AdComm.Properties("Sort on") = "name"
AdComm.CommandText = "<LDAP://cn=Partitions," & _
    objRootDSE.Get("ConfigurationNamingContext") & ">;" & _
        "(&(objectcategory=crossRef)(systemFlags=3));" & _
            "name,nCName,dnsRoot;onelevel"
set AdRs = AdComm.Execute

From that you can retrieve the name and dnsRoot of each partition:

AdRs.MoveFirst
With AdRs
  While Not .EOF
    dnsRoot = .Fields("dnsRoot")

    Set objOption = Document.createElement("OPTION")
    objOption.Text = dnsRoot(0)
    objOption.Value = "LDAP://" & dnsRoot(0) & "/" & .Fields("nCName").Value
    Domain.Add(objOption)
    .MoveNext 
  Wend 
End With

What charset does Microsoft Excel use when saving files?

From memory, Excel uses the machine-specific ANSI encoding. So this would be Windows-1252 for a EN-US installation, 1251 for Russian, etc.

Add querystring parameters to link_to

If you want the quick and dirty way and don't worry about XSS attack, use params.merge to keep previous parameters. e.g.

<%= link_to 'Link', params.merge({:per_page => 20}) %>

see: https://stackoverflow.com/a/4174493/445908

Otherwise , check this answer: params.merge and cross site scripting

Django: TemplateSyntaxError: Could not parse the remainder

For me it was using {{ }} instead of {% %}:

href="{{ static 'bootstrap.min.css' }}"  # wrong
href="{% static 'bootstrap.min.css' %}"  # right

Adjust list style image position?

like "a darren" answer but minor modification

li 
{
background: url("images/bullet.gif") left center no-repeat;
padding-left: 14px;
margin-left: 24px;
}

it works cross browser, just adjust the padding and margin

Edit for nested: add this style to add margin-left to the sub-nested list

ul ul{ margin-left:15px; }

How do you set the EditText keyboard to only consist of numbers on Android?

After several tries, I got it! I'm setting the keyboard values programmatically like this:

myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Or if you want you can edit the XML like so:

android: inputType = "numberPassword"

Both configs will display password bullets, so we need to create a custom ClickableSpan class:

private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return source;
    }
}

Finally we need to implement it on the EditText in order to display the characters typed.

myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());

This is how my keyboard looks like now:

How to check if array element exists or not in javascript?

Consider the array a:

var a ={'name1':1, 'name2':2}

If you want to check if 'name1' exists in a, simply test it with in:

if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')

For loop in multidimensional javascript array

var cubes = [["string", "string"], ["string", "string"]];

for(var i = 0; i < cubes.length; i++) {
    for(var j = 0; j < cubes[i].length; j++) {
        console.log(cubes[i][j]);
    }
}

JavaScript chop/slice/trim off last character in string

Use substring to get everything to the left of _bar. But first you have to get the instr of _bar in the string:

str.substring(3, 7);

3 is that start and 7 is the length.

Extracting just Month and Year separately from Pandas Datetime column

If you want new columns showing year and month separately you can do this:

df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month

or...

df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month

Then you can combine them or work with them just as they are.

Get current directory name (without full path) in a Bash script

I strongly prefer using gbasename, which is part of GNU coreutils.

Get a DataTable Columns DataType

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

Setting width to wrap_content for TextView through code

A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

If you want to update e.g. only the width you can do that with the following line in Kotlin.

tv.updateLayoutParams { width = WRAP_CONTENT }

Relative imports in Python 3

To obviate this problem, I devised a solution with the repackage package, which has worked for me for some time. It adds the upper directory to the lib path:

import repackage
repackage.up()
from mypackage.mymodule import myfunction

Repackage can make relative imports that work in a wide range of cases, using an intelligent strategy (inspecting the call stack).

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

How to destroy JWT Tokens on logout?

You cannot manually expire a token after it has been created. Thus, you cannot log out with JWT on the server-side as you do with sessions.

JWT is stateless, meaning that you should store everything you need in the payload and skip performing a DB query on every request. But if you plan to have a strict log out functionality, that cannot wait for the token auto-expiration, even though you have cleaned the token from the client-side, then you might need to neglect the stateless logic and do some queries. so what's a solution?

  • Set a reasonable expiration time on tokens

  • Delete the stored token from client-side upon log out

  • Query provided token against The Blacklist on every authorized request

Blacklist

“Blacklist” of all the tokens that are valid no more and have not expired yet. You can use a DB that has a TTL option on documents which would be set to the amount of time left until the token is expired.

Redis

Redis is a good option for blacklist, which will allow fast in-memory access to the list. Then, in the middleware of some kind that runs on every authorized request, you should check if the provided token is in The Blacklist. If it is you should throw an unauthorized error. And if it is not, let it go and the JWT verification will handle it and identify if it is expired or still active.

For more information, see How to log out when using JWT. by Arpy Vanyan

Create an empty object in JavaScript with {} or new Object()?

These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

try:

%matplotlib notebook

see jakevdp reply here

EDIT for JupyterLab users:

Follow the instructions to install jupyter-matplotlib

Then the magic command above is no longer needed, as in the example:

# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 2])
plt.show()

Finally, note Maarten Breddels' reply; IMHO ipyvolume is indeed very impressive (and useful!).

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

How to use an array list in Java?

If you use Java 1.5 or beyond you could use:

List<String> S = new ArrayList<String>();
s.add("My text");

for (String item : S) {
  System.out.println(item);
}

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

td widths, not working?

Width and/or height in tables are not standard anymore; as Ianzz says, they are deprecated. Instead the best way to do this is to have a block element inside your table cell that will hold the cell open to your desired size:

<table>
    <tr>
        <td valign="top">
            <div class="left_menu">
                <div class="menu_item">
                    <a href="#">Home</a>
                </div>
            </div>
        </td>
        <td valign="top" class="content">Content</td>
    </tr>
</table>

CSS

.content {
    width: 1000px;
}

.left_menu {
    background: none repeat scroll 0 0 #333333;
    border-radius: 5px 5px 5px 5px;
    font-family: Arial,Helvetica,sans-serif;
    font-size: 12px;
    font-weight: bold;
    padding: 5px;
    width: 200px;
}

.menu_item {
    background: none repeat scroll 0 0 #CCCCCC;
    border-bottom: 1px solid #999999;
    border-radius: 5px 5px 5px 5px;
    border-top: 1px solid #FFFFCC;
    cursor: pointer;
    padding: 5px;
}

How can I read large text files in Python, line by line, without loading it into memory?

You are better off using an iterator instead. Relevant: http://docs.python.org/library/fileinput.html

From the docs:

import fileinput
for line in fileinput.input("filename"):
    process(line)

This will avoid copying the whole file into memory at once.

ByRef argument type mismatch in Excel VBA

I changed a few things to work with Option Explicit, and the code ran fine against a cell containing "abc.123", which returned "abc.12,". There were no compile errors.

Option Explicit ' This is new

Public Function ProcessString(input_string As String) As String
    ' The temp string used throughout the function
    Dim temp_string As String
    Dim i As Integer ' This is new
    Dim return_string As String ' This is new
    For i = 1 To Len(input_string)
        temp_string = Mid(input_string, i, 1)
        If temp_string Like "[A-Z, a-z, 0-9, :, -]" Then
            return_string = return_string & temp_string
        End If
    Next i
    return_string = Mid(return_string, 1, (Len(return_string) - 1))
    ProcessString = return_string & ", "
End Function

I'll suggest you post more of your relevant code (that calls this function). You've stated that last_name is a String, but it appears that may not be the case. Step through your code line by line and ensure that this is actually the case.

Running Google Maps v2 on the Android emulator

For those who have updated to the latest version of google-play-services_lib and/or have this error Google Play services out of date. Requires 3136100 but found 2012110 this newer version of com.google.android.gms.apk (Google Play Services 3.1.36) and com.android.vending.apk (Google Play Store 4.1.6) should work.

Test with this configuration on Android SDK Tools 22.0.1. Another configuration that targets pure Android, not the Google one, should work too.

  • Device: Galaxy Nexus
  • Target: Android 4.2.2 - API Level 17
  • CPU/ABI: ARM (armeabi-v7a)
  • Checked: Use Host GPU

...

  1. Open the AVD
  2. Execute this in the terminal / cmd

    adb -e install com.google.android.gms.apk
    adb -e install com.android.vending.apk
    
  3. Restart the AVD

  4. Have fun coding!!!

I found this way to be the easiest, cleanest and it works with the newest version of the software, which allow you to get all the bug fixes.

How to get the current location in Google Maps Android API v2?

I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.

First declare these 3 variables:

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

Define methods:

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
  • initGoogleApiClient() is used to initialize GoogleApiClient object
  • setLocationListener() is used to setup location change listener
  • removeLocationListener() is used to remove the listener

Call initGoogleApiClient method to start the code working :) Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.

Parsing JSON with Unix tools

I've done this, "parsing" a json response for a particular value, as follows:

curl $url | grep $var | awk '{print $2}' | sed s/\"//g 

Clearly, $url here would be the twitter url, and $var would be "text" to get the response for that var.

Really, I think the only thing I'm doing the OP has left out is grep for the line with the specific variable he seeks. Awk grabs the second item on the line, and with sed I strip the quotes.

Someone smarter than I am could probably do the whole think with awk or grep.

Now, you could do it all with just sed:

curl $url | sed '/text/!d' | sed s/\"text\"://g | sed s/\"//g | sed s/\ //g

thus, no awk, no grep...I don't know why I didn't think of that before. Hmmm...

How can I remove text within parentheses with a regex?

For those who want to use Python, here's a simple routine that removes parenthesized substrings, including those with nested parentheses. Okay, it's not a regex, but it'll do the job!

def remove_nested_parens(input_str):
    """Returns a copy of 'input_str' with any parenthesized text removed. Nested parentheses are handled."""
    result = ''
    paren_level = 0
    for ch in input_str:
        if ch == '(':
            paren_level += 1
        elif (ch == ')') and paren_level:
            paren_level -= 1
        elif not paren_level:
            result += ch
    return result

remove_nested_parens('example_(extra(qualifier)_text)_test(more_parens).ext')

Non-recursive depth first search algorithm

Non-recursive DFS using ES6 generators

class Node {
  constructor(name, childNodes) {
    this.name = name;
    this.childNodes = childNodes;
    this.visited = false;
  }
}

function *dfs(s) {
  let stack = [];
  stack.push(s);
  stackLoop: while (stack.length) {
    let u = stack[stack.length - 1]; // peek
    if (!u.visited) {
      u.visited = true; // grey - visited
      yield u;
    }

    for (let v of u.childNodes) {
      if (!v.visited) {
        stack.push(v);
        continue stackLoop;
      }
    }

    stack.pop(); // black - all reachable descendants were processed 
  }    
}

It deviates from typical non-recursive DFS to easily detect when all reachable descendants of given node were processed and to maintain the current path in the list/stack.

How to take backup of a single table in a MySQL database?

You can use this code:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql

# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:

--

-- Table structure for table accounts_contacts

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--

How to search for an element in an stl list?

You use std::find from <algorithm>, which works equally well for std::list and std::vector. std::vector does not have its own search/find function.

#include <list>
#include <algorithm>

int main()
{
    std::list<int> ilist;
    ilist.push_back(1);
    ilist.push_back(2);
    ilist.push_back(3);

    std::list<int>::iterator findIter = std::find(ilist.begin(), ilist.end(), 1);
}

Note that this works for built-in types like int as well as standard library types like std::string by default because they have operator== provided for them. If you are using using std::find on a container of a user-defined type, you should overload operator== to allow std::find to work properly: EqualityComparable concept

element with the max height from a set of elements

_x000D_
_x000D_
ul, li {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  width: calc(100% / 3);_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
    <br> Line 3_x000D_
    <br> Line 4_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

herein lies the answer... IIS Settings

IIS-->Default SMTP Virtual Server-->Properties-->Access-->Relay restrictions just add or exclude the IPs you care about, should resolve the issue.

RunAs A different user when debugging in Visual Studio

As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:

  • Hold Shift + right-click to open a new instance of Visual Studio.
  • Click "Run as different user"

    Run as Different user

  • Enter credentials of the other user in the next pop-up window

  • Open the same solution you are working with

Now when you debug the solution it will be with the other user's permissions.

Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).

Resolve Git merge conflicts in favor of their changes during a pull

After git merge, if you get conflicts and you want either your or their

git checkout --theirs .
git checkout --ours .

Example to use shared_ptr?

Through Boost you can do it >

std::vector<boost::any> vecobj;
    boost::shared_ptr<string> sharedString1(new string("abcdxyz!"));    
    boost::shared_ptr<int> sharedint1(new int(10));
    vecobj.push_back(sharedString1);
    vecobj.push_back(sharedint1);

> for inserting different object type in your vector container. while for accessing you have to use any_cast, which works like dynamic_cast, hopes it will work for your need.

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

The system cannot find the file specified in java

How are you running the program?

It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

Need to list all triggers in SQL Server database with table name and table's schema

C# Cribs: I ended up with this super generic one liner. Hope this is useful to both the original poster and/or people who just typed the same question I did into Google:

SELECT TriggerRecord.name as TriggerName,ParentRecord.name as ForTableName 
FROM sysobjects TriggerRecord 
INNER JOIN sysobjects ParentRecord ON TriggerRecord.parent_obj=ParentRecord.id 
WHERE TriggerRecord.xtype='TR'

Query Characteristics:

  • Usable with any SQL database (i.e. Initial Catalog)
  • Self explanatory
  • One single statement
  • Pasteable directly into most IDE's for most languages

Can Twitter Bootstrap alerts fade in as well as out?

I strongly disagree with most answers previously mentioned.

Short answer:

Omit the "in" class and add it using jQuery to fade it in.

See this jsfiddle for an example that fades in alert after 3 seconds http://jsfiddle.net/QAz2U/3/

Long answer:

Although it is true bootstrap doesn't natively support fading in alerts, most answers here use the jQuery fade function, which uses JavaScript to animate (fade) the element. The big advantage of this is cross browser compatibility. The downside is performance (see also: jQuery to call CSS3 fade animation?).

Bootstrap uses CSS3 transitions, which have way better performance. Which is important for mobile devices:

Bootstraps CSS to fade the alert:

.fade {
  opacity: 0;
  -webkit-transition: opacity 0.15s linear;
  -moz-transition: opacity 0.15s linear;
  -o-transition: opacity 0.15s linear;
  transition: opacity 0.15s linear;
}
.fade.in {
  opacity: 1;
}

Why do I think this performance is so important? People using old browsers and hardware will potentially get a choppy transitions with jQuery.fade(). The same goes for old hardware with modern browsers. Using CSS3 transitions people using modern browsers will get a smooth animation even with older hardware, and people using older browsers that don't support CSS transitions will just instantly see the element pop in, which I think is a better user experience than choppy animations.

I came here looking for the same answer as the above: to fade in a bootstrap alert. After some digging in the code and CSS of Bootstrap the answer is rather straightforward. Don't add the "in" class to your alert. And add this using jQuery when you want to fade in your alert.

HTML (notice there is NO in class!)

<div id="myAlert" class="alert success fade" data-alert="alert">
  <!-- rest of alert code goes here -->
</div>

Javascript:

function showAlert(){
  $("#myAlert").addClass("in")
}

Calling the function above function adds the "in" class and fades in the alert using CSS3 transitions :-)

Also see this jsfiddle for an example using a timeout (thanks John Lehmann!): http://jsfiddle.net/QAz2U/3/

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
    e.printStackTrace();
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column
}

If you have any problem regarding this you can write me..

scroll up and down a div on button click using jquery

Scrolling div on click of button.

Html Code:-

 <div id="textBody" style="height:200px; width:600px; overflow:auto;">
    <!------Your content---->
 </div>

JQuery code for scrolling div:-

$(function() {
   $( "#upBtn" ).click(function(){
      $('#textBody').scrollTop($('#textBody').scrollTop()-20);
 }); 

 $( "#downBtn" ).click(function(){
     $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
 }); 

});

the getSource() and getActionCommand()

Assuming you are talking about the ActionEvent class, then there is a big difference between the two methods.

getActionCommand() gives you a String representing the action command. The value is component specific; for a JButton you have the option to set the value with setActionCommand(String command) but for a JTextField if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField.

getSource() is specified by the EventObject class that ActionEvent is a child of (via java.awt.AWTEvent). This gives you a reference to the object that the event came from.

Edit:

Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.

public class Events implements ActionListener {

  private static JFrame frame; 

  public static void main(String[] args) {

    frame = new JFrame("JTextField events");
    frame.getContentPane().setLayout(new FlowLayout());

    JTextField field1 = new JTextField(10);
    field1.addActionListener(new Events());
    frame.getContentPane().add(new JLabel("Field with no action command set"));
    frame.getContentPane().add(field1);

    JTextField field2 = new JTextField(10);
    field2.addActionListener(new Events());
    field2.setActionCommand("my action command");
    frame.getContentPane().add(new JLabel("Field with an action command set"));
    frame.getContentPane().add(field2);


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(220, 150);
    frame.setResizable(false);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    JOptionPane.showMessageDialog(frame, "Command: " + cmd);
  }

}

Error: Uncaught SyntaxError: Unexpected token <

After trying several solutions, this worked for me:

  1. Go to IIS Manager
  2. Open the Site
  3. Click on Authentication
  4. Edit Anonymous Authentication.
  5. Select "Application pool identity"

example

Limit length of characters in a regular expression?

(^(\d{2})|^(\d{4})|^(\d{5}))$

This expression takes the number of length 2,4 and 5. Valid Inputs are 12 1234 12345

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

What is the meaning of {...this.props} in Reactjs

It's ES6 Spread_operator and Destructuring_assignment.

<div {...this.props}>
  Content Here
</div>

It's equal to Class Component

const person = {
    name: "xgqfrms",
    age: 23,
    country: "China"
};

class TestDemo extends React.Component {
    render() {
        const {name, age, country} = {...this.props};
        // const {name, age, country} = this.props;
        return (
          <div>
              <h3> Person Information: </h3>
              <ul>
                <li>name={name}</li>
                <li>age={age}</li>
                <li>country={country}</li>
              </ul>
          </div>
        );
    }
}

ReactDOM.render(
    <TestDemo {...person}/>
    , mountNode
);

enter image description here


or Function component

const props = {
    name: "xgqfrms",
    age: 23,
    country: "China"
};

const Test = (props) => {
  return(
    <div
        name={props.name}
        age={props.age}
        country={props.country}>
        Content Here
        <ul>
          <li>name={props.name}</li>
          <li>age={props.age}</li>
          <li>country={props.country}</li>
        </ul>
    </div>
  );
};

ReactDOM.render(
    <div>
        <Test {...props}/>
        <hr/>
        <Test 
            name={props.name}
            age={props.age}
            country={props.country}
        />
    </div>
    , mountNode
);

enter image description here

refs

Passing vector by reference

void do_something(int el, std::vector<int> **arr)

should be

void do_something(int el, std::vector<int>& arr)
{
    arr.push_back(el);
}

Pass by reference has been simplified to use the & in C++.

Convert Month Number to Month Name Function in SQL

In some locales like Hebrew, there are leap months dependant upon the year so to avoid errors in such locales you might consider the following solution:

SELECT DATENAME(month, STR(YEAR(GETDATE()), 4) + REPLACE(STR(@month, 2), ' ', '0') + '01')     

Tomcat is not deploying my web project from Eclipse

I fixed this issue, this way:

  1. Stop the Server
  2. Remove the previous Deploy that You did
  3. Clean it
  4. Deploy it again

What is the difference between visibility:hidden and display:none?

In addition to all other answers, there's an important difference for IE8: If you use display:none and try to get the element's width or height, IE8 returns 0 (while other browsers will return the actual sizes). IE8 returns correct width or height only for visibility:hidden.

How can I remove the gloss on a select element in Safari on Mac?

i have used this and solved my

-webkit-appearance:none;

How to add custom html attributes in JSX

uniqueId is custom attribute.

<a {...{ "uniqueId": `${item.File.UniqueId}` }}  href={item.File.ServerRelativeUrl} target='_blank'>{item.File.Name}</a>

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

Hiding a form and showing another when a button is clicked in a Windows Forms application

i believe the following code will only run after form1 is closed

 while (true)
    {
        if (form1.Visible == false)
            form2.Show();
    }

Why not start your form2 from form1 instead?

Form2 form2 = new Form2();
 private void button1_Click_1(object sender, EventArgs e)
    {
        if (richTextBox1.Text != null)
        {
            form1.Visible=false;
            form2.Show();

        }
        else MessageBox.Show("Insert Attributes First !");

    }

Why is it that "No HTTP resource was found that matches the request URI" here?

I had that problem, if you are calling your REST Methods from another Assembly you must be sure that all your references have the same version as your main project references, otherwise will never find your controllers.

Regards.

How can I access Oracle from Python?

import cx_Oracle
   dsn_tns = cx_Oracle.makedsn('host', 'port', service_name='give service name') 
   conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns) 
   c = conn.cursor()
   c.execute('select count(*) from schema.table_name')
for row in c:
   print row
conn.close()

Note :

  1. In (dsn_tns) if needed, place an 'r' before any parameter in order to address any special character such as '\'.

  2. In (conn) if needed, place an 'r' before any parameter in order to address any special character such as '\'. For example, if your user name contains '\', you'll need to place 'r' before the user name: user=r'User Name' or password=r'password'

  3. use triple quotes if you want to spread your query across multiple lines.

Get connection string from App.config

This worked for me:

string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

Outputs:

Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"

jQuery UI Sortable, then write order into a database

I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.

Sorting arraylist in alphabetical order (case insensitive)

Starting from Java 8 you can use Stream:

List<String> sorted = Arrays.asList(
                          names.stream().sorted(
                              (s1, s2) -> s1.compareToIgnoreCase(s2)
                          ).toArray(String[]::new)
                      );

It gets a stream from that ArrayList, then it sorts it (ignoring the case). After that, the stream is converted to an array which is converted to an ArrayList.

If you print the result using:

System.out.println(sorted);

you get the following output:

[ananya, Athira, bala, jeena, Karthika, Neethu, Nithin, seetha, sudhin, Swetha, Tony, Vinod]

In Java, how to append a string more efficiently?

java.lang.StringBuilder. Use int constructor to create an initial size.