Programs & Examples On #Tuples

In programming, tuples are simple *product types*, representing ordered collections of types.

Sort tuples based on second parameter

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1])

or, slightly faster,

my_list.sort(key=operator.itemgetter(1))

(As with any module, you'll need to import operator to be able to use it.)

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

2D arrays in Python

Please consider the follwing codes:

from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)

How to easily initialize a list of Tuples?

Why do like tuples? It's like anonymous types: no names. Can not understand structure of data.

I like classic classes

class FoodItem
{
     public int Position { get; set; }
     public string Name { get; set; }
}

List<FoodItem> list = new List<FoodItem>
{
     new FoodItem { Position = 1, Name = "apple" },
     new FoodItem { Position = 2, Name = "kiwi" }
};

List of tuples to dictionary

The dict constructor accepts input exactly as you have it (key/value tuples).

>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}

From the documentation:

For example, these all return a dictionary equal to {"one": 1, "two": 2}:

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

Sort a list of tuples by 2nd item (integer value)

As a python neophyte, I just wanted to mention that if the data did actually look like this:

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical.

Better naming in Tuple classes than "Item1", "Item2"

You Can write a class that contains the Tuple.

You need to override the Equals and GetHashCode functions

and the == and != operators.

class Program
{
    public class MyTuple
    {
        private Tuple<int, int> t;

        public MyTuple(int a, int b)
        {
            t = new Tuple<int, int>(a, b);
        }

        public int A
        {
            get
            {
                return t.Item1;
            }
        }

        public int B
        {
            get
            {
                return t.Item2;
            }
        }

        public override bool Equals(object obj)
        {
            return t.Equals(((MyTuple)obj).t);
        }

        public override int GetHashCode()
        {
            return t.GetHashCode();
        }

        public static bool operator ==(MyTuple m1, MyTuple m2)
        {
            return m1.Equals(m2);
        }

        public static bool operator !=(MyTuple m1, MyTuple m2)
        {
            return !m1.Equals(m2);
        }
    }

    static void Main(string[] args)
    {
        var v1 = new MyTuple(1, 2);
        var v2 = new MyTuple(1, 2);

        Console.WriteLine(v1 == v2);

        Dictionary<MyTuple, int> d = new Dictionary<MyTuple, int>();
        d.Add(v1, 1);

        Console.WriteLine(d.ContainsKey(v2));
    }
}

will return:

True

True

python tuple to dict

Here are couple ways of doing it:

>>> t = ((1, 'a'), (2, 'b'))

>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}

>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}

Python convert tuple to string

This works:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

It will produce:

'abcdgxre'

You can also use a delimiter like a comma to produce:

'a,b,c,d,g,x,r,e'

By using:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

Find an element in a list of tuples

There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary.

For example,

test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1

Python : List of dict, if exists increment a dict value, if not append a new dict

Use defaultdict:

from collections import defaultdict

urls = defaultdict(int)

for url in list_of_urls:
    urls[url] += 1

How to convert comma-delimited string to list in Python?

In the case of integers that are included at the string, if you want to avoid casting them to int individually you can do:

mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]

It is called list comprehension, and it is based on set builder notation.

ex:

>>> mStr = "1,A,B,3,4"
>>> mList = [int(e) if e.isdigit() else e for e in mStr.split(',')]
>>> mList
>>> [1,'A','B',3,4]

Python element-wise tuple operations like sum

simple solution without class definition that returns tuple

import operator
tuple(map(operator.add,a,b))

Ignore python multiple return value

This seems like the best choice to me:

val1, val2, ignored1, ignored2 = some_function()

It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.

Reference an Element in a List of Tuples

Rather than:

first_element = myList[i[0]]

You probably want:

first_element = myList[i][0]

Converting string to tuple without splitting characters

You can just do (a,). No need to use a function. (Note that the comma is necessary.)

Essentially, tuple(a) means to make a tuple of the contents of a, not a tuple consisting of just a itself. The "contents" of a string (what you get when you iterate over it) are its characters, which is why it is split into characters.

Subtracting 2 lists in Python

Here's an alternative to list comprehensions. Map iterates through the list(s) (the latter arguments), doing so simulataneously, and passes their elements as arguments to the function (the first arg). It returns the resulting list.

import operator
map(operator.sub, a, b)

This code because has less syntax (which is more aesthetic for me), and apparently it's 40% faster for lists of length 5 (see bobince's comment). Still, either solution will work.

Select value from list of tuples where condition

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Inserting an item in a Tuple

t = (1,2,3,4,5)

t= t + (6,7)

output :

(1,2,3,4,5,6,7)

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

Getting one value from a tuple

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'

What and When to use Tuple?

The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.

Accessing a value in a tuple that is in a list

A list comprehension is absolutely the way to do this. Another way that should be faster is map and itemgetter.

import operator

new_list = map(operator.itemgetter(1), old_list)

In response to the comment that the OP couldn't find an answer on google, I'll point out a super naive way to do it.

new_list = []
for item in old_list:
    new_list.append(item[1])

This uses:

  1. Declaring a variable to reference an empty list.
  2. A for loop.
  3. Calling the append method on a list.

If somebody is trying to learn a language and can't put together these basic pieces for themselves, then they need to view it as an exercise and do it themselves even if it takes twenty hours.

One needs to learn how to think about what one wants and compare that to the available tools. Every element in my second answer should be covered in a basic tutorial. You cannot learn to program without reading one.

How to merge lists into a list of tuples?

You can use map lambda

a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)

This will also work if there lengths of original lists do not match

What's the difference between lists and tuples?

Difference between list and tuple

Tuples and lists are both seemingly similar sequence types in Python.

  1. Literal syntax

    We use parenthesis () to construct tuples and square brackets [ ] to get a new list. Also, we can use call of the appropriate type to get required structure — tuple or list.

    someTuple = (4,6)
    someList  = [2,6] 
    
  2. Mutability

    Tuples are immutable, while lists are mutable. This point is the base the for the following ones.

  3. Memory usage

    Due to mutability, you need more memory for lists and less memory for tuples.

  4. Extending

    You can add a new element to both tuples and lists with the only difference that the id of the tuple will be changed (i.e., we’ll have a new object).

  5. Hashing

    Tuples are hashable and lists are not. It means that you can use a tuple as a key in a dictionary. The list can't be used as a key in a dictionary, whereas a tuple can be used

    tup      = (1,2)
    list_    = [1,2] 
    
    c = {tup   : 1}     # ok
    c = {list_ : 1}     # error
    
  6. Semantics

    This point is more about best practice. You should use tuples as heterogeneous data structures, while lists are homogenous sequences.

Python: Tuples/dictionaries as keys, select, sort

This type of data is efficiently pulled from a Trie-like data structure. It also allows for fast sorting. The memory efficiency might not be that great though.

A traditional trie stores each letter of a word as a node in the tree. But in your case your "alphabet" is different. You are storing strings instead of characters.

it might look something like this:

root:                Root
                     /|\
                    / | \
                   /  |  \     
fruit:       Banana Apple Strawberry
              / |      |     \
             /  |      |      \
color:     Blue Yellow Green  Blue
            /   |       |       \
           /    |       |        \
end:      24   100      12        0

see this link: trie in python

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

How to sort a list/tuple of lists/tuples by the element at a given index?

from operator import itemgetter
data.sort(key=itemgetter(1))

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

Using Pairs or 2-tuples in Java

As an extension to @maerics nice answer, I've added a few useful methods:

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
    }

    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }

        if (!(other instanceof Tuple)){
            return false;
        }

        Tuple<X,Y> other_ = (Tuple<X,Y>) other;

        // this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
        return other_.x.equals(this.x) && other_.y.equals(this.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + ((y == null) ? 0 : y.hashCode());
        return result;
    }
}

What is the equivalent of the C++ Pair<L,R> in Java?

In a thread on comp.lang.java.help, Hunter Gratzner gives some arguments against the presence of a Pair construct in Java. The main argument is that a class Pair doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?).

A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair class. Map.Entry is an example of a pair that carry its meaning in its name.

To sum up, in my opinion it is better to have a class Position(x,y), a class Range(begin,end) and a class Entry(key,value) rather than a generic Pair(first,second) that doesn't tell me anything about what it's supposed to do.

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

Why is there no tuple comprehension in Python?

We can generate tuples from a list comprehension. The following one adds two numbers sequentially into a tuple and gives a list from numbers 0-9.

>>> print k
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> r= [tuple(k[i:i+2]) for i in xrange(10) if not i%2]
>>> print r
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

Convert tuple to list and back

You have a tuple of tuples.
To convert every tuple to a list:

[list(i) for i in level] # list of lists

--- OR ---

map(list, level)

And after you are done editing, just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

--- OR --- (Thanks @jamylak)

tuple(itertools.imap(tuple, edited))

You can also use a numpy array:

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

For manipulating:

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

Python add item to the tuple

>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')

Using Python's list index() method on a list of tuples or objects?

Inspired by this question, I found this quite elegant:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)
1
>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")
2

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

pop/remove items out of a python tuple

Maybe you want dictionaries?

d = dict( (i,value) for i,value in enumerate(tple))
while d:
    bla bla bla
    del b[x]

How can I access each element of a pair in a pair list?

I don't think that you'll like it but I made a pair port for python :) using it is some how similar to c++

pair = Pair
pair.make_pair(value1, value2)

or

pair = Pair(value1, value2)

here's the source code pair_stl_for_python

How to change values in a tuple?

EDIT: This doesn't work on tuples with duplicate entries yet!!

Based on Pooya's idea:

If you are planning on doing this often (which you shouldn't since tuples are inmutable for a reason) you should do something like this:

def modTupByIndex(tup, index, ins):
    return tuple(tup[0:index]) + (ins,) + tuple(tup[index+1:])

print modTupByIndex((1,2,3),2,"a")

Or based on Jon's idea:

def modTupByIndex(tup, index, ins):
    lst = list(tup)
    lst[index] = ins
    return tuple(lst)

print modTupByIndex((1,2,3),1,"a")

Convert list to tuple in Python

You might have done something like this:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

Here's the problem... Since you have used a tuple variable to hold a tuple (45, 34) earlier... So, now tuple is an object of type tuple now...

It is no more a type and hence, it is no more Callable.

Never use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...

JavaScript variable assignments from tuples

I made a tuple implementation that works quite well. This solution allows for array destructuring, as well as basic type-cheking.

const Tuple = (function() {
    function Tuple() {
        // Tuple needs at least one element
        if (arguments.length < 1) {
            throw new Error('Tuple needs at least one element');
        }

        const args = { ...arguments };

        // Define a length property (equal to the number of arguments provided)
        Object.defineProperty(this, 'length', {
            value: arguments.length,
            writable: false
        });

        // Assign values to enumerable properties
        for (let i in args) {
            Object.defineProperty(this, i, {
                enumerable: true,
                get() {
                    return args[+i];
                },
                // Checking if the type of the provided value matches that of the existing value
                set(value) {
                    if (typeof value !== typeof args[+i]) {
                        throw new Error('Cannot assign ' + typeof value + ' on ' + typeof args[+i]);
                    }

                    args[+i] = value;
                }
            });
        }

        // Implementing iteration with Symbol.iterator (allows for array destructuring as well for...of loops)
        this[Symbol.iterator] = function() {
            const tuple = this;

            return {
                current: 0,
                last: tuple.length - 1,
                next() {
                    if (this.current <= this.last) {
                        let val = { done: false, value: tuple[this.current] };
                        this.current++;
                        return val;
                    } else {
                        return { done: true };
                    }
                }
            };
        };

        // Sealing the object to make sure no more values can be added to tuple
        Object.seal(this);
    }

    // check if provided object is a tuple
    Tuple.isTuple = function(obj) {
        return obj instanceof Tuple;
    };

    // Misc. for making the tuple more readable when printing to the console
    Tuple.prototype.toString = function() {
        const copyThis = { ...this };
        const values = Object.values(copyThis);
        return `(${values.join(', ')})`;
    };

    // conctat two instances of Tuple
    Tuple.concat = function(obj1, obj2) {
        if (!Tuple.isTuple(obj1) || !Tuple.isTuple(obj2)) {
            throw new Error('Cannot concat Tuple with ' + typeof (obj1 || obj2));
        }

        const obj1Copy = { ...obj1 };
        const obj2Copy = { ...obj2 };

        const obj1Items = Object.values(obj1Copy);
        const obj2Items = Object.values(obj2Copy);

        return new Tuple(...obj1Items, ...obj2Items);
    };

    return Tuple;
})();

const SNAKE_COLOR = new Tuple(0, 220, 10);

const [red, green, blue] = SNAKE_COLOR;
console.log(green); // => 220


What's the difference between lists enclosed by square brackets and parentheses in Python?

Another way brackets and parentheses differ is that square brackets can describe a list comprehension, e.g. [x for x in y]

Whereas the corresponding parenthetic syntax specifies a tuple generator: (x for x in y)

You can get a tuple comprehension using: tuple(x for x in y)

See: Why is there no tuple comprehension in Python?

How to search a list of tuples in Python

[k for k,v in l if v =='delicia']

here l is the list of tuples-[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

And instead of converting it to a dict, we are using llist comprehension.

*Key* in Key,Value in list, where value = **delicia**

Add Variables to Tuple

You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma.

>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')

How to extract the n-th elements from a list of tuples?

n = 1 # N. . .
[x[n] for x in elements]

python: create list of tuples from lists

You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

Pair/tuple data type in Go

You can do this. It looks more wordy than a tuple, but it's a big improvement because you get type checking.

Edit: Replaced snippet with complete working example, following Nick's suggestion. Playground link: http://play.golang.org/p/RNx_otTFpk

package main

import "fmt"

func main() {
    queue := make(chan struct {string; int})
    go sendPair(queue)
    pair := <-queue
    fmt.Println(pair.string, pair.int)
}

func sendPair(queue chan struct {string; int}) {
    queue <- struct {string; int}{"http:...", 3}
}

Anonymous structs and fields are fine for quick and dirty solutions like this. For all but the simplest cases though, you'd do better to define a named struct just like you did.

how to add value to a tuple?

OUTPUTS = []
for number in range(len(list_of_tuples))):
    tup_ = list_of_tuples[number]
    list_ = list(tup_)  
    item_ = list_[0] + list_[1] + list_[2] + list_[3]
    list_.append(item_)
    OUTPUTS.append(tuple(list_))

OUTPUTS is what you desire

Why can't I use a list as a dict key in python?

A Dictionary is a HashMap it stores map of your keys, value converted to a hashed new key and value mapping.

something like (psuedo code):

{key : val}  
hash(key) = val

If you are wondering which are available options that can be used as key for your dictionary. Then

anything which is hashable(can be converted to hash, and hold static value i.e immutable so as to make a hashed key as stated above) is eligible but as list or set objects can be vary on the go so hash(key) should also needs to vary just to be in sync with your list or set.

You can try :

hash(<your key here>)

If it works fine it can be used as key for your dictionary or else convert it to something hashable.


Inshort :

  1. Convert that list to tuple(<your list>).
  2. Convert that list to str(<your list>).

How to form tuple column from two columns in Pandas

In [10]: df
Out[10]:
          A         B       lat      long
0  1.428987  0.614405  0.484370 -0.628298
1 -0.485747  0.275096  0.497116  1.047605
2  0.822527  0.340689  2.120676 -2.436831
3  0.384719 -0.042070  1.426703 -0.634355
4 -0.937442  2.520756 -1.662615 -1.377490
5 -0.154816  0.617671 -0.090484 -0.191906
6 -0.705177 -1.086138 -0.629708  1.332853
7  0.637496 -0.643773 -0.492668 -0.777344
8  1.109497 -0.610165  0.260325  2.533383
9 -1.224584  0.117668  1.304369 -0.152561

In [11]: df['lat_long'] = df[['lat', 'long']].apply(tuple, axis=1)

In [12]: df
Out[12]:
          A         B       lat      long                             lat_long
0  1.428987  0.614405  0.484370 -0.628298      (0.484370195967, -0.6282975278)
1 -0.485747  0.275096  0.497116  1.047605      (0.497115615839, 1.04760475074)
2  0.822527  0.340689  2.120676 -2.436831      (2.12067574274, -2.43683074367)
3  0.384719 -0.042070  1.426703 -0.634355      (1.42670326172, -0.63435462504)
4 -0.937442  2.520756 -1.662615 -1.377490     (-1.66261469102, -1.37749004179)
5 -0.154816  0.617671 -0.090484 -0.191906  (-0.0904840623396, -0.191905582481)
6 -0.705177 -1.086138 -0.629708  1.332853     (-0.629707821728, 1.33285348929)
7  0.637496 -0.643773 -0.492668 -0.777344   (-0.492667604075, -0.777344111021)
8  1.109497 -0.610165  0.260325  2.533383        (0.26032456699, 2.5333825651)
9 -1.224584  0.117668  1.304369 -0.152561     (1.30436900612, -0.152560909725)

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

Tuples( or arrays ) as Dictionary keys in C#

If for some reason you really want to avoid creating your own Tuple class, or using on built into .NET 4.0, there is one other approach possible; you can combine the three key values together into a single value.

For example, if the three values are integer types together not taking more than 64 bits, you could combine them into a ulong.

Worst-case you can always use a string, as long as you make sure the three components in it are delimited with some character or sequence that does not occur inside the components of the key, for example, with three numbers you could try:

string.Format("{0}#{1}#{2}", key1, key2, key3)

There is obviously some composition overhead in this approach, but depending on what you are using it for this may be trivial enough not to care about it.

What are "named tuples" in Python?

In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.

Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Delete all data in SQL Server database

As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.

How to check if a symlink exists

How about using readlink?

# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
  test "$(readlink "${1}")";
}

FILE=/usr/mda

if simlink? "${FILE}"; then
  echo $FILE is a symlink
else
  echo $FILE is not a symlink
fi

how to create a logfile in php?

Please check this code, it works fine for me.

$data = array('shopid'=>3,'version'=> 1,'value=>1');  //here $data is dummy varaible

error_log(print_r($data,true), 3, $_SERVER['DOCUMENT_ROOT']."/your-file-name.log");

//In $data we can mention the error messege and create the log

Passing bash variable to jq

Another way to accomplish this is with the jq "--arg" flag. Using the original example:

#!/bin/sh

#this works ***
projectID=$(cat file.json | jq -r '.resource[] | 
select(.username=="[email protected]") | .id')
echo "$projectID"

[email protected]

# Use --arg to pass the variable to jq. This should work:
projectID=$(cat file.json | jq --arg EMAILID $EMAILID -r '.resource[] 
| select(.username=="$EMAILID") | .id')
echo "$projectID"

See here, which is where I found this solution: https://github.com/stedolan/jq/issues/626

Android 6.0 Marshmallow. Cannot write to SD Card

Android changed how permissions work with Android 6.0 that's the reason for your errors. You have to actually request and check if the permission was granted by user to use. So permissions in manifest file will only work for api below 21. Check this link for a snippet of how permissions are requested in api23 http://android-developers.blogspot.nl/2015/09/google-play-services-81-and-android-60.html?m=1

Code:-

If (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_RC);
            return;
        }`


` @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_RC) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted  start reading
            } else {
                Toast.makeText(this, "No permission to read external storage.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

What is the T-SQL syntax to connect to another SQL Server?

If possible, check out SSIS (SQL Server Integration Services). I am just getting my feet wet with this toolkit, but already am looping over 40+ servers and preparing to wreak all kinds of havoc ;)

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

how to remove json object key and value.?

Follow this, it can be like what you are looking:

_x000D_
_x000D_
var obj = {_x000D_
    Objone: 'one',_x000D_
    Objtwo: 'two'_x000D_
};_x000D_
_x000D_
var key = "Objone";_x000D_
delete obj[key];_x000D_
console.log(obj); // prints { "objtwo": two}
_x000D_
_x000D_
_x000D_

.NET 4.0 has a new GAC, why?

It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.

My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.

Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.

How can I determine the current CPU utilization from the shell?

You can use top or ps commands to check the CPU usage.

using top : This will show you the cpu stats

top -b -n 1 |grep ^Cpu

using ps: This will show you the % cpu usage for each process.

ps -eo pcpu,pid,user,args | sort -r -k1 | less

Also, you can write a small script in bash or perl to read /proc/stat and calculate the CPU usage.

Java for loop syntax: "for (T obj : objects)"

That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries().

Auto-redirect to another HTML page

I'm Maybe kind of late but here is a way to have a redirect for your website and another link if it does not do in auto redirect for them,

<meta charset="UTF-8" />
<meta http-equiv="refresh" content="5; url=YOUR_URL_HERE" />
<script type="text/javascript">
  window.location.href = "site";
</script>
<title>Page Redirection</title>

<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
If you are not redirected automatically, follow this <a href="/site">Link</a>

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

How do I monitor all incoming http requests?

Microsoft Message Analyzer is the successor of the Microsoft Network Monitor 3.4

If your http incoming traffic is going to your web server at 58000 port, start the Analyzer in Administrator mode and click new session:

use filter: tcp.Port = 58000 and HTTP

trace scenario: "Local Network Interfaces (Win 8 and earlier)" or "Local Network Interfaces (Win 8.1 and later)" depends on your OS

Parsing Level: Full

Going to a specific line number using Less in Unix

For editing this is possible in nano via +n from command line, e.g.,

nano +16 file.txt

To open file.txt to line 16.

How to display databases in Oracle 11g using SQL*Plus

I am not clearly about it but typically one server has one database (with many users), if you create many databases mean that you create many instances, listeners, ... as well. So you can check your LISTENER to identify it.

In my testing I created 2 databases (dbtest and dbtest_1) so when I check my LISTENER status it appeared like this:

lsnrctl status

....

STATUS of the LISTENER

.....

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.20.20)(PORT=1521)))

Services Summary...

Service "dbtest" has 1 instance(s).

Instance "dbtest", status READY, has 1 handler(s) for this service...

Service "dbtest1XDB" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service...

Service "dbtest_1" has 1 instance(s).

Instance "dbtest1", status READY, has 1 handler(s) for this service... The command completed successfully

Convert xlsx file to csv using batch

You need an external tool, in example: SoftInterface.com - Convert XLSX to CSV.

After installing it, you can use following command in your batch:

"c:\Program Files\Softinterface, Inc\Convert XLS\ConvertXLS.EXE" /S"C:\MyExcelFile.xlsx" /F51 /N"Sheet1" /T"C:\MyExcelFile.CSV" /C6 /M1 /V

How can you find out which process is listening on a TCP or UDP port on Windows?

A single-line solution that helps me is this one. Just substitute 3000 with your port:

$P = Get-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess; Stop-Process $P.Id

Edit: Changed kill to Stop-Process for more PowerShell-like language

Inserting a Python datetime.datetime object into MySQL

If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
    "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
    "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"

sql_data = ( title, link, str(publish_date), \
             author, posted_by, \
             str(coco_id), str(link_id) )

try:
    dbc.execute(sql_stmt, sql_data )
except Exception, e:
    ...

Simple division in Java - is this a bug or a feature?

Please do not take this as an answer to the question. It is not, but an advice related to exploiting the difference of int and float. I would have put this under a comment except that the answer box allows me to format this comment.

This feature has been used in every respectable programming language since the days of fortran (or earlier) - I must confess I was once a Fortran and Cobol punch card programmer.

As an example, integer division of 10/3 yields integer value 3 since an integer has no facility to hold fractional residual .3333.. .

One of the ways we (old time ancient programmers) had been using this feature is loop control.

Let's say we wish to print an array of 1000 strings, but we wish to insert a line break after every 15th string, to insert some prettyfying chars at the end of the line and at the beginning of the next line. We exploit this, given that integer k is the position of a string in that array.

int(k/15)*15 == k

is true only when k is divisible by 15, an occurrence at a frequency of every 15th cell. Which is akin to what my friend said about his grandfather's dead watch being accurate twice a day.

int(1/15) = 0 -> int(1/15)*15 = 0
int(2/15) = 0 -> int(2/15)*15 = 0
...
int(14/15) = 0 -> int(14/15)*15 = 0
int(15/15) = 1 -> int(15/15)*15 = 15

int(16/15) = 1 -> int(16/15)*15 = 15
int(17/15) = 1 -> int(17/15)*15 = 15
...
int(29/15) = 1 -> int(29/15)*15 = 15
int(30/15) = 2 -> int(30/15)*15 = 30

Therefore, the loop,

leftPrettyfy();
for(int k=0; k<sa.length; k++){
  print(sa[k]);
  int z = k + 1;
  if ((z/15)*15 == z){
    rightPrettyfy();
    leftPrettyfy();
  }
}

By varying k in a fanciful way in the loop, we could print a triangular printout

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15

That is to demonstrate that, if you consider this a bug, this "bug" is a useful feature that we would not want to be removed from any of the various languages that we have used thus far.

How do I set the eclipse.ini -vm option?

I am not sure if something has changed, but I just tried the other answers regarding entries in "eclipse.ini" for Eclipse Galileo SR2 (Windows XP SR3) and none worked. Java is jdk1.6.0_18 and is the default Windows install. Things improved when I dropped "\javaw.exe" from the path.

Also, I can't thank enough the mention that -vm needs to be first line in the ini file. I believe that really helped me out.

Thus my eclipse.ini file starts with:

-vm
C:\Program Files\Java\jdk1.6.0_18\bin

FYI, my particular need to specify launching Eclipse with a JDK arose from my wanting to work with the m2eclipse plugin.

How to scanf only integer and repeat reading if the user enters non-numeric characters?

You will need to repeat your call to strtol inside your loops where you are asking the user to try again. In fact, if you make the loop a do { ... } while(...); instead of while, you don't get a the same sort of repeat things twice behaviour.

You should also format your code so that it's possible to see where the code is inside a loop and not.

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

How do I clear/delete the current line in terminal?

or if your using vi mode, hit Esc followed by cc

to get back what you just erased, Esc and then p :)

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How to Add Stacktrace or debug Option when Building Android Studio Project

You can use GUI to add these gradle command line flags from

File > Settings > Build, Execution, Deployment > Compiler

For MacOS user, it's here

Android Studio > Preferences > Build, Execution, Deployment > Compiler

like this (add --stacktrace or --debug)

enter image description here

Note that the screenshot is from before 0.8.10, the option is no longer in the Compiler > Gradle section, it's now in a separate section named Compiler (Gradle-based Android Project)

What is the difference between `throw new Error` and `throw someObject`?

throw something works with both object and strings.But it is less supported than the other method.throw new Error("") Will only work with strings and turns objects into useless [Object obj] in the catch block.

What is the proper way to check if a string is empty in Perl?

You probably want to use "eq" instead of "==". If you worry about some edge cases you may also want to check for undefined:

if (not defined $str) {

# this variable is undefined

}

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

Are static class variables possible in Python?

When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed.

  • CLASSNAME.var is static variable
  • INSTANCENAME.var is not static variable.
  • self.var inside class is not static variable.
  • var inside the class member function is not defined.

For example:

#!/usr/bin/python

class A:
    var=1

    def printvar(self):
        print "self.var is %d" % self.var
        print "A.var is %d" % A.var


    a = A()
    a.var = 2
    a.printvar()

    A.var = 3
    a.printvar()

The results are

self.var is 2
A.var is 1
self.var is 2
A.var is 3

REST API - why use PUT DELETE POST GET?

Am I missing something?

Yes. ;-)

This phenomenon exists because of the uniform interface constraint. REST likes using already existing standards instead of reinventing the wheel. The HTTP standard has already proven to be highly scalable (the web is working for a while). Why should we fix something which is not broken?!

note: The uniform interface constraint is important if you want to decouple the clients from the service. It is similar to defining interfaces for classes in order to decouple them from each other. Ofc. in here the uniform interface consists of standards like HTTP, MIME types, URI, RDF, linked data vocabs, hydra vocab, etc...

Cannot connect to the Docker daemon on macOS

I was facing similar issue on my mac, and I found that docker wasn't running in my machine, I just went to applications and invoked whale and then it worked .

Bootstrap 3 - set height of modal window according to screen size

Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS

$('#myModal').on('show.bs.modal', function () {
    $('.modal .modal-body').css('overflow-y', 'auto'); 
    $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

@class vs. #import

Three simple rules:

  • Only #import the super class, and adopted protocols, in header files (.h files).
  • #import all classes, and protocols, you send messages to in implementation (.m files).
  • Forward declarations for everything else.

If you do forward declaration in the implementation files, then you probably do something wrong.

Maximum call stack size exceeded on npm install

I deleted

node_modules

and then reinstalled by

npm install

It worked for me

Difference between "this" and"super" keywords in Java

When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

Even though you don't see it, the default no argument constructor always calls super() first. Example:

MyClass()
{
}

is equivalent to

MyClass()
{
   super();
}

I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.

How can I get a JavaScript stack trace when I throw an exception?

If you have firebug, there's a break on all errors option in the script tab. Once the script has hit your breakpoint, you can look at firebug's stack window:

screenshot

How to make a script wait for a pressed key?

If you are ok with depending on system commands you can use the following:

Linux and Mac OS X:

import os
os.system('read -s -n 1 -p "Press any key to continue..."')
print()

Windows:

import os
os.system("pause")

Setting background images in JFrame

There is no built-in method, but there are several ways to do it. The most straightforward way that I can think of at the moment is:

  1. Create a subclass of JComponent.
  2. Override the paintComponent(Graphics g) method to paint the image that you want to display.
  3. Set the content pane of the JFrame to be this subclass.

Some sample code:

class ImagePanel extends JComponent {
    private Image image;
    public ImagePanel(Image image) {
        this.image = image;
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this);
    }
}

// elsewhere
BufferedImage myImage = ImageIO.read(...);
JFrame myJFrame = new JFrame("Image pane");
myJFrame.setContentPane(new ImagePanel(myImage));

Note that this code does not handle resizing the image to fit the JFrame, if that's what you wanted.

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.

But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

int k = 100; Integer it1 = new Integer(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();

System.out.println(m*m); // prints 10000

//intValue() is a method of Integer class that returns an int data type.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Put the select statement in a dynamic PL/SQL block.

CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2) 
RETURN NUMBER
IS
  v_query_str VARCHAR2(1000);
  v_num_of_employees NUMBER;
BEGIN
  v_query_str := 'begin SELECT COUNT(*) INTO :into_bind FROM emp_' 
                 || p_loc
                 || ' WHERE job = :bind_job; end;';
  EXECUTE IMMEDIATE v_query_str
    USING out v_num_of_employees, p_job;
  RETURN v_num_of_employees;
END;
/

Sort a List of Object in VB.NET

you must implement IComparer interface.

In this sample I've my custom object JSONReturn, I implement my class like this :

Friend Class JSONReturnComparer
    Implements IComparer(of JSONReturn)

    Public Function Compare(x As JSONReturn, y As JSONReturn) As Integer Implements    IComparer(Of JSONReturn).Compare
        Return String.Compare(x.Name, y.Name)
    End Function

End Class

I call my sort List method like this : alResult.Sort(new JSONReturnComparer())

Maybe it could help you

Get User's Current Location / Coordinates

@wonderwhy I have added my code screenshot. pls check it. You will have to add <code>NSLocationWhenInUseUsageDescription in the plist for authorisation.</code>

NSLocationWhenInUseUsageDescription = Request permission to use location service when the apps is in background. in your plist file.

If this works then please vote the answer.

In Chart.js set chart title, name of x axis and y axis?

In Chart.js version 2.0, it is possible to set labels for axes:

options = {
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: 'probability'
      }
    }]
  }     
}

See Labelling documentation for more details.

Module AppRegistry is not registered callable module (calling runApplication)

If you are using windows and running yarn open cmd on admin mode' terminate and Restart the node process by typing this command.

Find the node: killall -9 node force to kill : taskkill /f /im node.exe Reset the cache : yarn start --reset-cache

Navigate to your project directory: cd myapp Re-Run your App : yarn android

How to add jQuery in JS file

I find that the best way is to use this...

**<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>**

This is from the Codecademy 'Make an Interactive Website' project.

error: expected primary-expression before ')' token (C)

You should create a variable of the type SelectionneNonSelectionne.

struct SelectionneNonSelectionne var;

After that pass that variable to the function like

characterSelection(screen, var);

The error is caused since you are passing the type name SelectionneNonSelectionne

How to round the minute of a datetime object

i'm using this. it has the advantage of working with tz aware datetimes.

def round_minutes(some_datetime: datetime, step: int):
    """ round up to nearest step-minutes """
    if step > 60:
        raise AttrbuteError("step must be less than 60")

    change = timedelta(
        minutes= some_datetime.minute % step,
        seconds=some_datetime.second,
        microseconds=some_datetime.microsecond
    )

    if change > timedelta():
        change -= timedelta(minutes=step)

    return some_datetime - change

it has the disadvantage of only working for timeslices less than an hour.

force browsers to get latest js and css files in asp.net application

There are a built-in way in asp.net for this: bundling. Just use it. Each new version will have unique suffix "?v=XXXXXXX". In debug mode bundling is off, for switching on make setting in web.config:

<system.web>
    <compilation debug="false" />
</system.web>

Or add to the method RegisterBundles(BundleCollection bundles) :

BundleTable.EnableOptimizations = true;

For example:

BundleConfig.cs :

bundles.Add(new ScriptBundle("~/Scripts/myjavascript.js")
                .Include("~/Scripts/myjavascript.js"));

bundles.Add(new StyleBundle("~/Content/mystyle.css")
                .Include("~/Content/mystyle.css"));

_Layout.cshtml :

@Scripts.Render("~/Scripts/myjavascript.js")
@Styles.Render("~/Content/mystyle.css")

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

I was able to get around this loading the headers before the HTML with php, and it worked very well.

<?php 
header( 'X-UA-Compatible: IE=edge,chrome=1' );
header( 'content: width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' );
include('ix.html');
?> 

ix.html is the content I wanted to load after sending the headers.

MySQL Select all columns from one table and some from another table

I need more information really but it will be along the lines of..

SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)

Timing Delays in VBA

Another variant of Steve Mallorys answer, I specifically needed excel to run off and do stuff while waiting and 1 second was too long.

'Wait for the specified number of milliseconds while processing the message pump
'This allows excel to catch up on background operations
Sub WaitFor(milliseconds As Single)

    Dim finish As Single
    Dim days As Integer

    'Timer is the number of seconds since midnight (as a single)
    finish = Timer + (milliseconds / 1000)
    'If we are near midnight (or specify a very long time!) then finish could be
    'greater than the maximum possible value of timer. Bring it down to sensible
    'levels and count the number of midnights
    While finish >= 86400
        finish = finish - 86400
        days = days + 1
    Wend

    Dim lastTime As Single
    lastTime = Timer

    'When we are on the correct day and the time is after the finish we can leave
    While days >= 0 And Timer < finish
        DoEvents
        'Timer should be always increasing except when it rolls over midnight
        'if it shrunk we've gone back in time or we're on a new day
        If Timer < lastTime Then
            days = days - 1
        End If
        lastTime = Timer
    Wend

End Sub

How to get the size of a string in Python?

You also may use str.len() to count length of element in the column

data['name of column'].str.len() 

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

Xcode "Device Locked" When iPhone is unlocked

My phone was set to "trust" the Mac, and I still ran into this error with Xcode 6.1.1.

This worked for me:

  • unplug device
  • quit xcode
  • open xcode
  • plug in device
  • build/run

How do I count columns of a table

SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'tbl_ifo'

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

In my case the file .git/HEAD was corrupted (contained only dots). So I edited it and replaced its content with:

ref: refs/heads/master

and it started working again.

Illegal mix of collations error in MySql

HAvING TheCount > 4 AND username IN (SELECT username FROM users WHERE gender=1)

but why i am answering, you dont voted me as right answer :)

How to mention C:\Program Files in batchfile

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

How do I get the list of keys in a Dictionary?

To get list of all keys

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();

System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

Visual Studio Does not recognize System.Linq

System.Linq Namespace

How do I pipe a subprocess call to a text file?

The options for popen can be used in call

args, 
bufsize=0, 
executable=None, 
stdin=None, 
stdout=None, 
stderr=None, 
preexec_fn=None, 
close_fds=False, 
shell=False, 
cwd=None, 
env=None, 
universal_newlines=False, 
startupinfo=None, 
creationflags=0

So...

subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=myoutput)

Then you can do what you want with myoutput (which would need to be a file btw).

Also, you can do something closer to a piped output like this.

dmesg | grep hda

would be:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

There's plenty of lovely, useful info on the python manual page.

Custom Date/Time formatting in SQL Server

Use DATENAME and wrap the logic in a Function, not a Stored Proc

declare @myTime as DateTime

set @myTime = GETDATE()

select @myTime

select DATENAME(day, @myTime) + SUBSTRING(UPPER(DATENAME(month, @myTime)), 0,4)

Returns "14OCT"

Try not to use any Character / String based operations if possible when working with dates. They are numerical (a float) and performance will suffer from those data type conversions.

Dig these handy conversions I have compiled over the years...

/* Common date functions */
--//This contains common date functions for MSSQL server

/*Getting Parts of a DateTime*/
    --//gets the date only, 20x faster than using Convert/Cast to varchar
    --//this has been especially useful for JOINS
    SELECT (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime))

    --//gets the time only (date portion is '1900-01-01' and is considered the "0 time" of dates in MSSQL, even with the datatype min value of 01/01/1753. 
    SELECT (GETDATE() - (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)))


/*Relative Dates*/
--//These are all functions that will calculate a date relative to the current date and time
    /*Current Day*/
    --//now
    SELECT (GETDATE())

    --//midnight of today
    SELECT (DATEADD(ms,-4,(DATEADD(dd,DATEDIFF(dd,0,GETDATE()) + 1,0))))

    --//Current Hour
    SELECT DATEADD(hh,DATEPART(hh,GETDATE()),CAST(FLOOR(CAST(GETDATE() AS FLOAT)) as DateTime))

    --//Current Half-Hour - if its 9:36, this will show 9:30
    SELECT DATEADD(mi,((DATEDIFF(mi,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)), GETDATE())) / 30) * 30,(CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)))

    /*Yearly*/
    --//first datetime of the current year
    SELECT (DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))

    --//last datetime of the current year
    SELECT (DATEADD(ms,-4,(DATEADD(yy,DATEDIFF(yy,0,GETDATE()) + 1,0))))

    /*Monthly*/
    --//first datetime of current month
    SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))

    --//last datetime of the current month
    SELECT (DATEADD(ms,-4,DATEADD(mm,1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))))

    --//first datetime of the previous month
    SELECT (DATEADD(mm,DATEDIFF(mm,0,GETDATE()) -1,0))

    --//last datetime of the previous month
    SELECT (DATEADD(ms, -4,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))

    /*Weekly*/
    --//previous monday at 12AM
    SELECT (DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))

    --//previous friday at 11:59:59 PM
    SELECT (DATEADD(ms,-4,DATEADD(dd,5,DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))))

    /*Quarterly*/
    --//first datetime of current quarter
    SELECT (DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0))

    --//last datetime of current quarter
    SELECT (DATEADD(ms,-4,DATEADD(qq,DATEDIFF(qq,0,GETDATE()) + 1,0)))

Using PHP variables inside HTML tags?

You can do it a number of ways, depending on the type of quotes you use:

  • echo "<a href='http://www.whatever.com/$param'>Click here</a>";
  • echo "<a href='http://www.whatever.com/{$param}'>Click here</a>";
  • echo '<a href="http://www.whatever.com/' . $param . '">Click here</a>';
  • echo "<a href=\"http://www.whatever.com/$param\">Click here</a>";

Double quotes allow for variables in the middle of the string, where as single quotes are string literals and, as such, interpret everything as a string of characters -- nothing more -- not even \n will be expanded to mean the new line character, it will just be the characters \ and n in sequence.

You need to be careful about your use of whichever type of quoting you decide. You can't use double quotes inside a double quoted string (as in your example) as you'll be ending the string early, which isn't what you want. You can escape the inner double quotes, however, by adding a backslash.

On a separate note, you might need to be careful about XSS attacks when printing unsafe variables (populated by the user) out to the browser.

Extract substring in Bash

Without any sub-processes you can:

shopt -s extglob
front=${input%%_+([a-zA-Z]).*}
digits=${front##+([a-zA-Z])_}

A very small variant of this will also work in ksh93.

How to make a Java Generic method static?

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

Important details:

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

How to compare two tables column by column in oracle

It won't be fast, and there will be a lot for you to type (unless you generate the SQL from user_tab_columns), but here is what I use when I need to compare two tables row-by-row and column-by-column.

The query will return all rows that

  • Exists in table1 but not in table2
  • Exists in table2 but not in table1
  • Exists in both tables, but have at least one column with a different value

(common identical rows will be excluded).

"PK" is the column(s) that make up your primary key. "a" will contain A if the present row exists in table1. "b" will contain B if the present row exists in table2.

select pk
      ,decode(a.rowid, null, null, 'A') as a
      ,decode(b.rowid, null, null, 'B') as b
      ,a.col1, b.col1
      ,a.col2, b.col2
      ,a.col3, b.col3
      ,...
  from table1 a 
  full outer 
  join table2 b using(pk)
 where decode(a.col1, b.col1, 1, 0) = 0
    or decode(a.col2, b.col2, 1, 0) = 0
    or decode(a.col3, b.col3, 1, 0) = 0
    or ...;

Edit Added example code to show the difference described in comment. Whenever one of the values contains NULL, the result will be different.

with a as(
   select 0    as col1 from dual union all
   select 1    as col1 from dual union all
   select null as col1 from dual
)
,b as(
   select 1    as col1 from dual union all
   select 2    as col1 from dual union all
   select null as col1 from dual
)   
select a.col1
      ,b.col1
      ,decode(a.col1, b.col1, 'Same', 'Different') as approach_1
      ,case when a.col1 <> b.col1 then 'Different' else 'Same' end as approach_2       
  from a,b
 order 
    by a.col1
      ,b.col1;    




col1   col1_1   approach_1  approach_2
====   ======   ==========  ==========
  0        1    Different   Different  
  0        2    Different   Different  
  0      null   Different   Same         <--- 
  1        1    Same        Same       
  1        2    Different   Different  
  1      null   Different   Same         <---
null       1    Different   Same         <---
null       2    Different   Same         <---
null     null   Same        Same       

"You have mail" message in terminal, os X

Probably it is some message from your system.

Type in terminal:

man mail

, and see how can you get this message from your system.

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

How to check if element in groovy array/hash/collection/list?

def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}

I did it like this so it works if someone is looking for it.

Storyboard - refer to ViewController in AppDelegate

For iOS 13+

in SceneDelegate:

var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options 
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
    let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}

How to get the instance id from within an ec2 instance?

In Go you can use the goamz package.

import (
    "github.com/mitchellh/goamz/aws"
    "log"
)

func getId() (id string) {
    idBytes, err := aws.GetMetaData("instance-id")
    if err != nil {
        log.Fatalf("Error getting instance-id: %v.", err)
    }

    id = string(idBytes)

    return id
}

Here's the GetMetaData source.

MongoDB/Mongoose querying at a specific date?

That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find({ //query today up to tonight
    created_on: {
        $gte: new Date(2012, 7, 14), 
        $lt: new Date(2012, 7, 15)
    }
})

Use jQuery to get the file input's selected filename without the path

We can also remove it using match

var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Python time measure function

After playing with the timeit module, I don't like its interface, which is not so elegant compared to the following two method.

The following code is in Python 3.

The decorator method

This is almost the same with @Mike's method. Here I add kwargs and functools wrap to make it better.

def timeit(func):
    @functools.wraps(func)
    def newfunc(*args, **kwargs):
        startTime = time.time()
        func(*args, **kwargs)
        elapsedTime = time.time() - startTime
        print('function [{}] finished in {} ms'.format(
            func.__name__, int(elapsedTime * 1000)))
    return newfunc

@timeit
def foobar():
    mike = Person()
    mike.think(30)

The context manager method

from contextlib import contextmanager

@contextmanager
def timeit_context(name):
    startTime = time.time()
    yield
    elapsedTime = time.time() - startTime
    print('[{}] finished in {} ms'.format(name, int(elapsedTime * 1000)))

For example, you can use it like:

with timeit_context('My profiling code'):
    mike = Person()
    mike.think()

And the code within the with block will be timed.

Conclusion

Using the first method, you can eaily comment out the decorator to get the normal code. However, it can only time a function. If you have some part of code that you don't what to make it a function, then you can choose the second method.

For example, now you have

images = get_images()
bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)

Now you want to time the bigImage = ... line. If you change it to a function, it will be:

images = get_images()
bitImage = None
@timeit
def foobar():
    nonlocal bigImage
    bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)

Looks not so great...What if you are in Python 2, which has no nonlocal keyword.

Instead, using the second method fits here very well:

images = get_images()
with timeit_context('foobar'):
    bigImage = ImagePacker.pack(images, width=4096)
drawer.draw(bigImage)

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

The BadImageFormatException on an application running on IIS (not running from VS, since visual studio fixes the problem by using the build for "Any CPU") can be caused by the following:

The site is one a server that is x64 and the Application Pool's default setting for Enable 32-Bit Applications was False. and you have 32-bit assemblies

On the level of Visual Studio, the fix is:

  1. Change the project setting "Target CPU" to "ANYCPU"

Rails: How do I create a default value for attributes in Rails activerecord's model?

The solution depends on a few things.

Is the default value dependent on other information available at creation time? Can you wipe the database with minimal consequences?

If you answered the first question yes, then you want to use Jim's solution

If you answered the second question yes, then you want to use Daniel's solution

If you answered no to both questions, you're probably better off adding and running a new migration.

class AddDefaultMigration < ActiveRecord::Migration
  def self.up
     change_column :tasks, :status, :string, :default => default_value, :null => false
  end
end

:string can be replaced with any type that ActiveRecord::Migration recognizes.

CPU is cheap so the redefinition of Task in Jim's solution isn't going to cause many problems. Especially in a production environment. This migration is proper way of doing it as it is loaded it and called much less often.

How do I alter the precision of a decimal column in Sql Server?

There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.

to wit:

ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);
GO

UPDATE  MyTable
SET     NewColumnName = OldColumnName;
GO

ALTER TABLE CONTRACTS DROP COLUMN OldColumnName;
GO


EXEC sp_rename
    @objname = 'MyTable.NewColumnName',
    @newname = 'OldColumnName',
    @objtype = 'COLUMN'
GO

This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.

Create a OpenSSL certificate on Windows

You can download a native OpenSSL for Windows, or you can always use Cygwin.

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.

How to create a jQuery function (a new jQuery method or plugin)?

Simplest example to making any function in jQuery is

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something here*/}

How to do a https request with bad certificate?

Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.

In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.

Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.

RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

INNER JOIN same table

You can also use UNION like

SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_id = $_GET[id]
UNION
SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_parent_id = $_GET[id]

ImportError: No module named dateutil.parser

For Python 3 above, use:

sudo apt-get install python3-dateutil

Eclipse: Frustration with Java 1.7 (unbound library)

1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .

Then project compile and done ..

Intercept a form submit in JavaScript and prevent normal submission

<form onSubmit="return captureForm()"> that should do. Make sure that your captureForm() method returns false.

Ruby Array find_first object?

use array detect method if you wanted to return first value where block returns true

[1,2,3,11,34].detect(&:even?) #=> 2

OR

[1,2,3,11,34].detect{|i| i.even?} #=> 2

If you wanted to return all values where block returns true then use select

[1,2,3,11,34].select(&:even?)  #=> [2, 34]

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

Does JavaScript guarantee object property order?

YES (for non-integer keys).

Most Browsers iterate object properties as:

  1. Integer keys in ascending order (and strings like "1" that parse as ints)
  2. String keys, in insertion order (ES2015 guarantees this and all browsers comply)
  3. Symbol names, in insertion order (ES2015 guarantees this and all browsers comply)

Some older browsers combine categories #1 and #2, iterating all keys in insertion order. If your keys might parse as integers, it's best not to rely on any specific iteration order.

Current Language Spec (since ES2015) insertion order is preserved, except in the case of keys that parse as integers (eg "7" or "99"), where behavior varies between browsers. For example, Chrome/V8 does not respect insertion order when the keys are parse as numeric.

Old Language Spec (before ES2015): Iteration order was technically undefined, but all major browsers complied with the ES2015 behavior.

Note that the ES2015 behavior was a good example of the language spec being driven by existing behavior, and not the other way round. To get a deeper sense of that backwards-compatibility mindset, see http://code.google.com/p/v8/issues/detail?id=164, a Chrome bug that covers in detail the design decisions behind Chrome's iteration order behavior. Per one of the (rather opinionated) comments on that bug report:

Standards always follow implementations, that's where XHR came from, and Google does the same thing by implementing Gears and then embracing equivalent HTML5 functionality. The right fix is to have ECMA formally incorporate the de-facto standard behavior into the next rev of the spec.

How to register ASP.NET 2.0 to web server(IIS7)?

If you installed IIS after the .Net framework you can solve the porblem by re-installing the .Net framework. Part of its install detects whether IIS is present and updates IIS accordingly.

sqlite3.OperationalError: unable to open database file

You haven't specified the absolute path - you've used a shortcut , ~, which might not work in this context. Use /home/yourusername/Harold-Server/OmniCloud.db instead.

adding noise to a signal in python

Awesome answers above. I recently had a need to generate simulated data and this is what I landed up using. Sharing in-case helpful to others as well,

import logging
__name__ = "DataSimulator"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

import numpy as np
import pandas as pd

def generate_simulated_data(add_anomalies:bool=True, random_state:int=42):
    rnd_state = np.random.RandomState(random_state)
    time = np.linspace(0, 200, num=2000)
    pure = 20*np.sin(time/(2*np.pi))

    # concatenate on the second axis; this will allow us to mix different data 
    # distribution
    data = np.c_[pure]
    mu = np.mean(data)
    sd = np.std(data)
    logger.info(f"Data shape : {data.shape}. mu: {mu} with sd: {sd}")
    data_df = pd.DataFrame(data, columns=['Value'])
    data_df['Index'] = data_df.index.values

    # Adding gaussian jitter
    jitter = 0.3*rnd_state.normal(mu, sd, size=data_df.shape[0])
    data_df['with_jitter'] = data_df['Value'] + jitter

    index_further_away = None
    if add_anomalies:
        # As per the 68-95-99.7 rule(also known as the empirical rule) mu+-2*sd 
        # covers 95.4% of the dataset.
        # Since, anomalies are considered to be rare and typically within the 
        # 5-10% of the data; this filtering
        # technique might work 
        #for us(https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule)
        indexes_furhter_away = np.where(np.abs(data_df['with_jitter']) > (mu + 
         2*sd))[0]
        logger.info(f"Number of points further away : 
        {len(indexes_furhter_away)}. Indexes: {indexes_furhter_away}")
        # Generate a point uniformly and embed it into the dataset
        random = rnd_state.uniform(0, 5, 1)
        data_df.loc[indexes_furhter_away, 'with_jitter'] +=  
        random*data_df.loc[indexes_furhter_away, 'with_jitter']
    return data_df, indexes_furhter_away

How to do date/time comparison

For comparison between two times use time.Sub()

// utc life
loc, _ := time.LoadLocation("UTC")

// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)

// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)

The program outputs:

Lifespan is 3h0m0s

http://play.golang.org/p/bbxeTtd4L6

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How do I write a for loop in bash

Try the bash built-in help:


$ help for

for: for NAME [in WORDS ... ;] do COMMANDS; done
    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
    Equivalent to
        (( EXP1 ))
        while (( EXP2 )); do
            COMMANDS
            (( EXP3 ))
        done
    EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
    omitted, it behaves as if it evaluates to 1.


Efficient way to add spaces between characters in a string

s = "BINGO"
print(" ".join(s))

Should do it.

What is “2's Complement”?

In simple term 2's Complement is a way to store negative number in Computer Memory. Whereas Positive Numbers are stored as Normal Binary Number.

Let's consider this example,

Computer uses Binary Number System to represent any number.

x = 5;

This is represented as 0101.

x = -5;

When the computer encouters - sign, it computes it's 2's complement and stores it. i.e 5 = 0101 and it's 2's complement is 1011.

Important rules computer uses to process numbers are,

  1. If the first bit is 1 then it must be negative number.
  2. If all the bits except first bit are 0 then it is a positive number because there is no -0 in number system.(1000 is not -0 instead it is positive 8)
  3. If all the bits are 0 then it is 0.
  4. Else it is a positive number.

What are C++ functors and their uses?

Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

Then you could pass a MultiplyBy object to an algorithm like std::transform:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is Linux specific and is an environment variable pointing to directories where the dynamic loader should look for shared libraries.

Try to add the directory where your .dll is in the PATH variable. Windows will automatically look in the directories listet in this environment variable. LD_LIBRARY_PATH probably won't solve the problem (unless the JVM uses it - I do not know about that).

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

How do I connect to this localhost from another computer on the same network?

If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:

Listen: 10.20.30.40:80

Restart your Apache server and test it from other computer on the network.

How do I download a tarball from GitHub using cURL?

All the other solutions require specifying a release/version number which obviously breaks automation.

This solution- currently tested and known to work with Github API v3- however can be used programmatically to grab the LATEST release without specifying any tag or release number and un-TARs the binary to an arbitrary name you specify in switch --one-top-level="pi-ap". Just swap-out user f1linux and repo pi-ap in below example with your own details and Bob's your uncle:

curl -L https://api.github.com/repos/f1linux/pi-ap/tarball | tar xzvf - --one-top-level="pi-ap" --strip-components 1

convert from Color to brush

SolidColorBrush brush = new SolidColorBrush( Color.FromArgb(255,255,139,0) )

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

Unrecognized escape sequence for path string containing backslashes

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion



    public new void Clear()
    {
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;


        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);


    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

MySQL config file location - redhat linux server

On RH systems, MySQL configuration file is located under /etc/my.cnf by default.

Find indices of elements equal to zero in a NumPy array

You can use numpy.nonzero to find zero.

>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0)  # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

Here is a bare bones version:

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

Then this formula will give you the date you want:

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

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

Access Database opens as read only

Create an empty folder and move the .mdb file to that folder. And try opening it from there. I tried it this way and it worked for me.

Artificially create a connection timeout error

How about a software solution:

Install SSH server on the application server. Then, use socket tunnel to create a link between your local port and the remote port on the application server. You can use ssh client tools to do so. Have your client application connect to your mapped local port instead. Then, you can break the socket tunnel at will to simulate the connection timeout.

Why doesn't Python have multiline comments?

Multi-line comments are easily breakable. What if you have the following in a simple calculator program?

operation = ''
print("Pick an operation:  +-*/")
# Get user input here

Try to comment that with a multi-line comment:

/*
operation = ''
print("Pick an operation:  +-*/")
# Get user input here
*/

Oops, your string contains the end comment delimiter.

Calculating difference between two timestamps in Oracle in milliseconds

I know that many people finding this solution simple and clear:

create table diff_timestamp (
f1 timestamp
, f2 timestamp);

insert into diff_timestamp values(systimestamp-1, systimestamp+2);
commit;

select cast(f2 as date) - cast(f1 as date) from diff_timestamp;

bingo!

How can I display the users profile pic using the facebook graph api?

to get different sizes, you can use the type parameter:

You can specify the picture size you want with the type argument, which should be one of square (50x50), small (50 pixels wide, variable height), and large (about 200 pixels wide, variable height): http://graph.facebook.com/squall3d/picture?type=large.

How to develop a soft keyboard for Android?

Create Custom Key Board for Own EditText

Download Entire Code

In this post i Created Simple Keyboard which contains Some special keys like ( France keys ) and it's supported Capital letters and small letters and Number keys and some Symbols .

package sra.keyboard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class Main extends Activity implements OnTouchListener, OnClickListener,
  OnFocusChangeListener {
 private EditText mEt, mEt1; // Edit Text boxes
 private Button mBSpace, mBdone, mBack, mBChange, mNum;
 private RelativeLayout mLayout, mKLayout;
 private boolean isEdit = false, isEdit1 = false;
 private String mUpper = "upper", mLower = "lower";
 private int w, mWindowWidth;
 private String sL[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
   "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
   "x", "y", "z", "ç", "à", "é", "è", "û", "î" };
 private String cL[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z", "ç", "à", "é", "è", "û", "î" };
 private String nS[] = { "!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
   "?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
   "\"", "6", "_", "=", "]", "[", "<", ">", "|" };
 private Button mB[] = new Button[32];

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   setContentView(R.layout.main);
   // adjusting key regarding window sizes
   setKeys();
   setFrow();
   setSrow();
   setTrow();
   setForow();
   mEt = (EditText) findViewById(R.id.xEt);
   mEt.setOnTouchListener(this);
   mEt.setOnFocusChangeListener(this);
   mEt1 = (EditText) findViewById(R.id.et1);

   mEt1.setOnTouchListener(this);
   mEt1.setOnFocusChangeListener(this);
   mEt.setOnClickListener(this);
   mEt1.setOnClickListener(this);
   mLayout = (RelativeLayout) findViewById(R.id.xK1);
   mKLayout = (RelativeLayout) findViewById(R.id.xKeyBoard);

  } catch (Exception e) {
   Log.w(getClass().getName(), e.toString());
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  if (v == mEt) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  if (v == mEt1) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  return true;
 }

 @Override
 public void onClick(View v) {

  if (v == mBChange) {

   if (mBChange.getTag().equals(mUpper)) {
    changeSmallLetters();
    changeSmallTags();
   } else if (mBChange.getTag().equals(mLower)) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  } else if (v != mBdone && v != mBack && v != mBChange && v != mNum) {
   addText(v);

  } else if (v == mBdone) {

   disableKeyboard();

  } else if (v == mBack) {
   isBack(v);
  } else if (v == mNum) {
   String nTag = (String) mNum.getTag();
   if (nTag.equals("num")) {
    changeSyNuLetters();
    changeSyNuTags();
    mBChange.setVisibility(Button.INVISIBLE);

   }
   if (nTag.equals("ABC")) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  }

 }

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
  if (v == mEt && hasFocus == true) {
   isEdit = true;
   isEdit1 = false;

  } else if (v == mEt1 && hasFocus == true) {
   isEdit = false;
   isEdit1 = true;

  }

 }

 private void addText(View v) {
  if (isEdit == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt.append(b);

   }
  }

  if (isEdit1 == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt1.append(b);

   }

  }

 }

 private void isBack(View v) {
  if (isEdit == true) {
   CharSequence cc = mEt.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt.setText("");
     mEt.append(cc.subSequence(0, cc.length() - 1));
    }

   }
  }

  if (isEdit1 == true) {
   CharSequence cc = mEt1.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt1.setText("");
     mEt1.append(cc.subSequence(0, cc.length() - 1));
    }
   }
  }
 }
 private void changeSmallLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < sL.length; i++)
   mB[i].setText(sL[i]);
  mNum.setTag("12#");
 }
 private void changeSmallTags() {
  for (int i = 0; i < sL.length; i++)
   mB[i].setTag(sL[i]);
  mBChange.setTag("lower");
  mNum.setTag("num");
 }
 private void changeCapitalLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < cL.length; i++)
   mB[i].setText(cL[i]);
  mBChange.setTag("upper");
  mNum.setText("12#");

 }

 private void changeCapitalTags() {
  for (int i = 0; i < cL.length; i++)
   mB[i].setTag(cL[i]);
  mNum.setTag("num");

 }

 private void changeSyNuLetters() {

  for (int i = 0; i < nS.length; i++)
   mB[i].setText(nS[i]);
  mNum.setText("ABC");
 }

 private void changeSyNuTags() {
  for (int i = 0; i < nS.length; i++)
   mB[i].setTag(nS[i]);
  mNum.setTag("ABC");
 }

 // enabling customized keyboard
 private void enableKeyboard() {

  mLayout.setVisibility(RelativeLayout.VISIBLE);
  mKLayout.setVisibility(RelativeLayout.VISIBLE);

 }

 // Disable customized keyboard
 private void disableKeyboard() {
  mLayout.setVisibility(RelativeLayout.INVISIBLE);
  mKLayout.setVisibility(RelativeLayout.INVISIBLE);

 }

 private void hideDefaultKeyboard() {
  getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

 }

 private void setFrow() {
  w = (mWindowWidth / 13);
  w = w - 15;
  mB[16].setWidth(w);
  mB[22].setWidth(w + 3);
  mB[4].setWidth(w);
  mB[17].setWidth(w);
  mB[19].setWidth(w);
  mB[24].setWidth(w);
  mB[20].setWidth(w);
  mB[8].setWidth(w);
  mB[14].setWidth(w);
  mB[15].setWidth(w);
  mB[16].setHeight(50);
  mB[22].setHeight(50);
  mB[4].setHeight(50);
  mB[17].setHeight(50);
  mB[19].setHeight(50);
  mB[24].setHeight(50);
  mB[20].setHeight(50);
  mB[8].setHeight(50);
  mB[14].setHeight(50);
  mB[15].setHeight(50);

 }

 private void setSrow() {
  w = (mWindowWidth / 10);
  mB[0].setWidth(w);
  mB[18].setWidth(w);
  mB[3].setWidth(w);
  mB[5].setWidth(w);
  mB[6].setWidth(w);
  mB[7].setWidth(w);
  mB[26].setWidth(w);
  mB[9].setWidth(w);
  mB[10].setWidth(w);
  mB[11].setWidth(w);
  mB[26].setWidth(w);

  mB[0].setHeight(50);
  mB[18].setHeight(50);
  mB[3].setHeight(50);
  mB[5].setHeight(50);
  mB[6].setHeight(50);
  mB[7].setHeight(50);
  mB[9].setHeight(50);
  mB[10].setHeight(50);
  mB[11].setHeight(50);
  mB[26].setHeight(50);
 }

 private void setTrow() {
  w = (mWindowWidth / 12);
  mB[25].setWidth(w);
  mB[23].setWidth(w);
  mB[2].setWidth(w);
  mB[21].setWidth(w);
  mB[1].setWidth(w);
  mB[13].setWidth(w);
  mB[12].setWidth(w);
  mB[27].setWidth(w);
  mB[28].setWidth(w);
  mBack.setWidth(w);

  mB[25].setHeight(50);
  mB[23].setHeight(50);
  mB[2].setHeight(50);
  mB[21].setHeight(50);
  mB[1].setHeight(50);
  mB[13].setHeight(50);
  mB[12].setHeight(50);
  mB[27].setHeight(50);
  mB[28].setHeight(50);
  mBack.setHeight(50);

 }

 private void setForow() {
  w = (mWindowWidth / 10);
  mBSpace.setWidth(w * 4);
  mBSpace.setHeight(50);
  mB[29].setWidth(w);
  mB[29].setHeight(50);

  mB[30].setWidth(w);
  mB[30].setHeight(50);

  mB[31].setHeight(50);
  mB[31].setWidth(w);
  mBdone.setWidth(w + (w / 1));
  mBdone.setHeight(50);

 }

 private void setKeys() {
  mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); // getting
  // window
  // height
  // getting ids from xml files
  mB[0] = (Button) findViewById(R.id.xA);
  mB[1] = (Button) findViewById(R.id.xB);
  mB[2] = (Button) findViewById(R.id.xC);
  mB[3] = (Button) findViewById(R.id.xD);
  mB[4] = (Button) findViewById(R.id.xE);
  mB[5] = (Button) findViewById(R.id.xF);
  mB[6] = (Button) findViewById(R.id.xG);
  mB[7] = (Button) findViewById(R.id.xH);
  mB[8] = (Button) findViewById(R.id.xI);
  mB[9] = (Button) findViewById(R.id.xJ);
  mB[10] = (Button) findViewById(R.id.xK);
  mB[11] = (Button) findViewById(R.id.xL);
  mB[12] = (Button) findViewById(R.id.xM);
  mB[13] = (Button) findViewById(R.id.xN);
  mB[14] = (Button) findViewById(R.id.xO);
  mB[15] = (Button) findViewById(R.id.xP);
  mB[16] = (Button) findViewById(R.id.xQ);
  mB[17] = (Button) findViewById(R.id.xR);
  mB[18] = (Button) findViewById(R.id.xS);
  mB[19] = (Button) findViewById(R.id.xT);
  mB[20] = (Button) findViewById(R.id.xU);
  mB[21] = (Button) findViewById(R.id.xV);
  mB[22] = (Button) findViewById(R.id.xW);
  mB[23] = (Button) findViewById(R.id.xX);
  mB[24] = (Button) findViewById(R.id.xY);
  mB[25] = (Button) findViewById(R.id.xZ);
  mB[26] = (Button) findViewById(R.id.xS1);
  mB[27] = (Button) findViewById(R.id.xS2);
  mB[28] = (Button) findViewById(R.id.xS3);
  mB[29] = (Button) findViewById(R.id.xS4);
  mB[30] = (Button) findViewById(R.id.xS5);
  mB[31] = (Button) findViewById(R.id.xS6);
  mBSpace = (Button) findViewById(R.id.xSpace);
  mBdone = (Button) findViewById(R.id.xDone);
  mBChange = (Button) findViewById(R.id.xChange);
  mBack = (Button) findViewById(R.id.xBack);
  mNum = (Button) findViewById(R.id.xNum);
  for (int i = 0; i < mB.length; i++)
   mB[i].setOnClickListener(this);
  mBSpace.setOnClickListener(this);
  mBdone.setOnClickListener(this);
  mBack.setOnClickListener(this);
  mBChange.setOnClickListener(this);
  mNum.setOnClickListener(this);

 }

}

Eloquent - where not equal to

Use where with a != operator in combination with whereNull

Code::where('to_be_used_by_user_id', '!=' , 2)->orWhereNull('to_be_used_by_user_id')->get()

BitBucket - download source as ZIP

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well. Even though the question/answer is about downloading the code of an earlier commit, I thought I'd just add an answer for browsing the code also.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

JNI and Gradle in Android Studio

Gradle Build Tools 2.2.0+ - The closest the NDK has ever come to being called 'magic'

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Android Studio Clean and Build Integration - DEPRECATED

The other answers do point out the correct way to prevent the automatic creation of Android.mk files, but they fail to go the extra step of integrating better with Android Studio. I have added the ability to actually clean and build from source without needing to go to the command-line. Your local.properties file will need to have ndk.dir=/path/to/ndk

apply plugin: 'com.android.application'

android {
    compileSdkVersion 14
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 14
        targetSdkVersion 14

        ndk {
            moduleName "YourModuleName"
        }
    }

    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }

    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }
}

dependencies {
    compile 'com.android.support:support-v4:20.0.0'
}

The src/main/jni directory assumes a standard layout of the project. It should be the relative from this build.gradle file location to the jni directory.

Gradle - for those having issues

Also check this Stack Overflow answer.

It is really important that your gradle version and general setup are correct. If you have an older project I highly recommend creating a new one with the latest Android Studio and see what Google considers the standard project. Also, use gradlew. This protects the developer from a gradle version mismatch. Finally, the gradle plugin must be configured correctly.

And you ask what is the latest version of the gradle plugin? Check the tools page and edit the version accordingly.

Final product - /build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
    gradleVersion = '2.2'
}

// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Make sure gradle wrapper generates the gradlew file and gradle/wrapper subdirectory. This is a big gotcha.

ndkDirectory

This has come up a number of times, but android.ndkDirectory is the correct way to get the folder after 1.1. Migrating Gradle Projects to version 1.0.0. If you're using an experimental or ancient version of the plugin your mileage may vary.

How do I include inline JavaScript in Haml?

:javascript
    $(document).ready( function() {
      $('body').addClass( 'test' );
    } );

Docs: http://haml.info/docs/yardoc/file.REFERENCE.html#javascript-filter

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

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

Count all occurrences of a string in lots of files with grep

If you want number of occurrences per file (example for string "tcp"):

grep -RIci "tcp" . | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr

Example output:

53  ./HTTPClient/src/HTTPClient.cpp
21  ./WiFi/src/WiFiSTA.cpp
19  ./WiFi/src/ETH.cpp
13  ./WiFi/src/WiFiAP.cpp
4   ./WiFi/src/WiFiClient.cpp
4   ./HTTPClient/src/HTTPClient.h
3   ./WiFi/src/WiFiGeneric.cpp
2   ./WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino
2   ./WiFiClientSecure/src/ssl_client.cpp
1   ./WiFi/src/WiFiServer.cpp

Explanation:

  • grep -RIci NEEDLE . - looks for string NEEDLE recursively from current directory (following symlinks), ignoring binaries, counting number of occurrences, ignoring case
  • awk ... - this command ignores files with zero occurrences and formats lines
  • sort -hr - sorts lines in reverse order by numbers in first column

Of course, it works with other grep commands with option -c (count) as well. For example:

grep -c "tcp" *.txt | awk -v FS=":" -v OFS="\t" '$2>0 { print $2, $1 }' | sort -hr

ViewPager and fragments — what's the right way to store fragment's state?

My solution is very rude but works: being my fragments dynamically created from retained data, I simply remove all fragment from the PageAdapter before calling super.onSaveInstanceState() and then recreate them on activity creation:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("viewpagerpos", mViewPager.getCurrentItem() );
    mSectionsPagerAdapter.removeAllfragments();
    super.onSaveInstanceState(outState);
}

You can't remove them in onDestroy(), otherwise you get this exception:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Here the code in the page adapter:

public void removeAllfragments()
{
    if ( mFragmentList != null ) {
        for ( Fragment fragment : mFragmentList ) {
            mFm.beginTransaction().remove(fragment).commit();
        }
        mFragmentList.clear();
        notifyDataSetChanged();
    }
}

I only save the current page and restore it in onCreate(), after the fragments have been created.

if (savedInstanceState != null)
    mViewPager.setCurrentItem( savedInstanceState.getInt("viewpagerpos", 0 ) );  

How can I stop redis-server?

Try killall redis-server. You may also use ps aux to find the name and pid of your server, and then kill it with kill -9 here_pid_number.

Decode HTML entities in Python string?

I had a similar encoding issue. I used the normalize() method. I was getting a Unicode error using the pandas .to_html() method when exporting my data frame to an .html file in another directory. I ended up doing this and it worked...

    import unicodedata 

The dataframe object can be whatever you like, let's call it table...

    table = pd.DataFrame(data,columns=['Name','Team','OVR / POT'])
    table.index+= 1

encode table data so that we can export it to out .html file in templates folder(this can be whatever location you wish :))

     #this is where the magic happens
     html_data=unicodedata.normalize('NFKD',table.to_html()).encode('ascii','ignore')

export normalized string to html file

    file = open("templates/home.html","w") 

    file.write(html_data) 

    file.close() 

Reference: unicodedata documentation

How to make URL/Phone-clickable UILabel?

Swift 4.0 possible solution using UIButton

     phoneButton = UIButton(frame: CGRect(x: view.frame.width * 0, y: view.frame.height * 0.1, width: view.frame.width * 1, height: view.frame.height * 0.05))
     phoneButton.setTitle("333-333-3333", for: .normal )
     phoneButton.setTitleColor(UIColor(red: 0 / 255, green: 0 / 255, blue: 238 / 255, alpha: 1.0), for: .normal)
     phoneButton.addTarget(self, action: #selector(self.callPhone), for: .touchUpInside )

     @objc func callPhone(){

         UIApplication.shared.open(URL(string:"tel://3333333333")!, options: [:] , completionHandler: nil)


    }

Get public/external IP address?

I had almost the same as Jesper, only I reused the webclient and disposed it correctly. Also I cleaned up some responses by removing the extra \n at the end.


    private static IPAddress GetExternalIp () {
      using (WebClient client = new WebClient()) {
        List<String> hosts = new List<String>();
        hosts.Add("https://icanhazip.com");
        hosts.Add("https://api.ipify.org");
        hosts.Add("https://ipinfo.io/ip");
        hosts.Add("https://wtfismyip.com/text");
        hosts.Add("https://checkip.amazonaws.com/");
        hosts.Add("https://bot.whatismyipaddress.com/");
        hosts.Add("https://ipecho.net/plain");
        foreach (String host in hosts) {
          try {
            String ipAdressString = client.DownloadString(host);
            ipAdressString = ipAdressString.Replace("\n", "");
            return IPAddress.Parse(ipAdressString);
          } catch {
          }
        }
      }
      return null;
    }

How do I get the day month and year from a Windows cmd.exe script?

Extract Day, Month and Year

The highest voted function and the accepted one do NOT work locale-independently since the DATE command is subject to localization too. For example (the accepted one): In English you have YYYY for year and in Holland it is JJJJ. So this is a no-go. The following script takes the users' localization from the registry, which is locale-independent.

@echo off

::: Begin set date
setlocal EnableExtensions EnableDelayedExpansion

:: Determine short date format (independent from localization) from registry
for /f "skip=1 tokens=3-5 delims=- " %%L in ( '2^>nul reg query "HKCU\Control Panel\International" /v "sShortDate"' ) do ( 

    :: Since we can have multiple (short) date formats we only use the first char from the format in a new variable
    set "_L=%%L" && set "_L=!_L:~0,1!" && set "_M=%%M" && set "_M=!_M:~0,1!" && set "_N=%%N" && set "_N=!_N:~0,1!"

    :: Now assign the date values to the new vars
    for /f "tokens=2-4 delims=/-. " %%D in ( "%date%" ) do ( set "!_L!=%%D" && set "!_M!=%%E" && set "!_N!=%%F" )
)


:: Print the values as is
echo.
echo This is the original date string --^> %date%
echo These are the splitted values    --^> Day: %d%, Month:%m%, Year: %y%.
echo.

endlocal

Extract only the Year

For a script I wrote I wanted only to extract the year (locale-independent) so I came up with this oneliner as I couldn't find any solution. It uses the 'DATE' var, multiple delimiters and checks for a number greater than 31. That then will be the current year. It's low on resources in contrast to some of the other solutions.

@echo off

setlocal EnableExtensions

for /f " tokens=2-4 delims=-./ " %%D in ( "%date%" ) do ( if %%D gtr 31 ( set "_YEAR=%%D" ) else ( if %%E gtr 31 ( set "_YEAR=%%E" ) else ( if %%F gtr 31 ( set "_YEAR=%%F" ) ) ) )

echo And the year is... %_YEAR%.
echo.

endlocal

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

const vs constexpr on variables

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

but:

constexpr double PI3 = PI2;  // ok

and:

static_assert(PI1 == 3.141592653589793, "");  // error

but:

static_assert(PI2 == 3.141592653589793, "");  // ok

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

Convert Data URI to File then append to FormData

make it simple :D

function dataURItoBlob(dataURI,mime) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs

    var byteString = window.atob(dataURI);

    // separate out the mime component


    // write the bytes of the string to an ArrayBuffer
    //var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ia], { type: mime });

    return blob;
}

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

Using AES encryption in C#

Try this code, maybe useful.
1.Create New C# Project and add follows code to Form1:

using System;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace ExampleCrypto
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strOriginalData = string.Empty;
            string strEncryptedData = string.Empty;
            string strDecryptedData = string.Empty;

            strOriginalData = "this is original data 1234567890"; // your original data in here
            MessageBox.Show("ORIGINAL DATA:\r\n" + strOriginalData);

            clsCrypto aes = new clsCrypto();
            aes.IV = "this is your IV";     // your IV
            aes.KEY = "this is your KEY";    // your KEY      
            strEncryptedData = aes.Encrypt(strOriginalData, CipherMode.CBC);    // your cipher mode
            MessageBox.Show("ENCRYPTED DATA:\r\n" + strEncryptedData);

            strDecryptedData = aes.Decrypt(strEncryptedData, CipherMode.CBC);
            MessageBox.Show("DECRYPTED DATA:\r\n" + strDecryptedData);
        }

    }
}

2.Create clsCrypto.cs and copy paste follows code in your class and run your code. I used MD5 to generated Initial Vector(IV) and KEY of AES.

using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Remoting.Metadata.W3cXsd2001;

namespace ExampleCrypto
{
    public class clsCrypto
    {
        private string _KEY = string.Empty;
        protected internal string KEY
        {
            get
            {
                return _KEY;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _KEY = value;
                }
            }
        }

        private string _IV = string.Empty;
        protected internal string IV
        {
            get
            {
                return _IV;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    _IV = value;
                }
            }
        }

        private string CalcMD5(string strInput)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    StringBuilder strHex = new StringBuilder();
                    using (MD5 md5 = MD5.Create())
                    {
                        byte[] bytArText = Encoding.Default.GetBytes(strInput);
                        byte[] bytArHash = md5.ComputeHash(bytArText);
                        for (int i = 0; i < bytArHash.Length; i++)
                        {
                            strHex.Append(bytArHash[i].ToString("X2"));
                        }
                        strOutput = strHex.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

        private byte[] GetBytesFromHexString(string strInput)
        {
            byte[] bytArOutput = new byte[] { };
            if ((!string.IsNullOrEmpty(strInput)) && strInput.Length % 2 == 0)
            {
                SoapHexBinary hexBinary = null;
                try
                {
                    hexBinary = SoapHexBinary.Parse(strInput);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                bytArOutput = hexBinary.Value;
            }
            return bytArOutput;
        }

        private byte[] GenerateIV()
        {
            byte[] bytArOutput = new byte[] { };
            try
            {
                string strIV = CalcMD5(IV);
                bytArOutput = GetBytesFromHexString(strIV);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return bytArOutput;
        }

        private byte[] GenerateKey()
        {
            byte[] bytArOutput = new byte[] { };
            try
            {
                string strKey = CalcMD5(KEY);
                bytArOutput = GetBytesFromHexString(strKey);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return bytArOutput;
        }

        protected internal string Encrypt(string strInput, CipherMode cipherMode)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    byte[] bytePlainText = Encoding.Default.GetBytes(strInput);
                    using (RijndaelManaged rijManaged = new RijndaelManaged())
                    {
                        rijManaged.Mode = cipherMode;
                        rijManaged.BlockSize = 128;
                        rijManaged.KeySize = 128;
                        rijManaged.IV = GenerateIV();
                        rijManaged.Key = GenerateKey();
                        rijManaged.Padding = PaddingMode.Zeros;
                        ICryptoTransform icpoTransform = rijManaged.CreateEncryptor(rijManaged.Key, rijManaged.IV);
                        using (MemoryStream memStream = new MemoryStream())
                        {
                            using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Write))
                            {
                                cpoStream.Write(bytePlainText, 0, bytePlainText.Length);
                                cpoStream.FlushFinalBlock();
                            }
                            strOutput = Encoding.Default.GetString(memStream.ToArray());
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

        protected internal string Decrypt(string strInput, CipherMode cipherMode)
        {
            string strOutput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                try
                {
                    byte[] byteCipherText = Encoding.Default.GetBytes(strInput);
                    byte[] byteBuffer = new byte[strInput.Length];
                    using (RijndaelManaged rijManaged = new RijndaelManaged())
                    {
                        rijManaged.Mode = cipherMode;
                        rijManaged.BlockSize = 128;
                        rijManaged.KeySize = 128;
                        rijManaged.IV = GenerateIV();
                        rijManaged.Key = GenerateKey();
                        rijManaged.Padding = PaddingMode.Zeros;
                        ICryptoTransform icpoTransform = rijManaged.CreateDecryptor(rijManaged.Key, rijManaged.IV);
                        using (MemoryStream memStream = new MemoryStream(byteCipherText))
                        {
                            using (CryptoStream cpoStream = new CryptoStream(memStream, icpoTransform, CryptoStreamMode.Read))
                            {
                                cpoStream.Read(byteBuffer, 0, byteBuffer.Length);
                            }
                            strOutput = Encoding.Default.GetString(byteBuffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            return strOutput;
        }

    }
}

when I run mockito test occurs WrongTypeOfReturnValue Exception

For me the issue were the multithreaded tests that were doing stubbing/verification on a shared mocks. It leaded to randomly throwing WrongTypeOfReturnValue exception.

This is not properly written test using Mockito. Mocks should not be accessed from multiple threads.

The solution was to make mocks local to each test.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Create a pointer to two-dimensional array

You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;

how to destroy bootstrap modal window completely?

For 3.x version

$( '.modal' ).modal( 'hide' ).data( 'bs.modal', null );

For 2.x version (risky; read comments below) When you create bootstrap modal three elements on your page being changed. So if you want to completely rollback all changes, you have to do it manually for each of it.

$( '.modal' ).remove();
$( '.modal-backdrop' ).remove();
$( 'body' ).removeClass( "modal-open" );

What is difference between functional and imperative programming languages?

Here is the difference:

Imperative:

  • Start
  • Turn on your shoes size 9 1/2.
  • Make room in your pocket to keep an array[7] of keys.
  • Put the keys in the room for the keys in the pocket.
  • Enter garage.
  • Open garage.
  • Enter Car.

... and so on and on ...

  • Put the milk in the refrigerator.
  • Stop.

Declarative, whereof functional is a subcategory:

  • Milk is a healthy drink, unless you have problems digesting lactose.
  • Usually, one stores milk in a refrigerator.
  • A refrigerator is a box that keeps the things in it cool.
  • A store is a place where items are sold.
  • By "selling" we mean the exchange of things for money.
  • Also, the exchange of money for things is called "buying".

... and so on and on ...

  • Make sure we have milk in the refrigerator (when we need it - for lazy functional languages).

Summary: In imperative languages you tell the computer how to change bits, bytes and words in it's memory and in what order. In functional ones, we tell the computer what things, actions etc. are. For example, we say that the factorial of 0 is 1, and the factorial of every other natural number is the product of that number and the factorial of its predecessor. We don't say: To compute the factorial of n, reserve a memory region and store 1 there, then multiply the number in that memory region with the numbers 2 to n and store the result at the same place, and at the end, the memory region will contain the factorial.

What HTTP status response code should I use if the request is missing a required parameter?

For those interested, Spring MVC (3.x at least) returns a 400 in this case, which seems wrong to me.

I tested several Google URLs (accounts.google.com) and removed required parameters, and they generally return a 404 in this case.

I would copy Google.

How to change font of UIButton with Swift

If you need to change only size (Swift 4.0):

button.titleLabel?.font = button.titleLabel?.font.withSize(12)

Formatting code snippets for blogging on Blogger

Easiest way to share code is with a public gist. Just write one up and paste in the embed code. Easy peasy.

http://gist.github.com

To address the search engine issue, one can use hidden div on the page as simple as:

<div style="display:none"> content </div>

How do you obtain a Drawable object from a resource id in android package?

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

How to break out of jQuery each Loop

According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How to get evaluated attributes inside a custom directive

For an attribute value that needs to be interpolated in a directive that is not using an isolated scope, e.g.,

<input my-directive value="{{1+1}}">

use Attributes' method $observe:

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

From the directive page,

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

If the attribute value is just a constant, e.g.,

<input my-directive value="123">

you can use $eval if the value is a number or boolean, and you want the correct type:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

If the attribute value is a string constant, or you want the value to be string type in your directive, you can access it directly:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

In your case, however, since you want to support interpolated values and constants, use $observe.

Make sure that the controller has a parameterless public constructor error

I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.

For example:

Defining UnityContainer:

var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);

SiteController (the wrong way - notice repo type):

private readonly DashboardRepository _repo;

public SiteController(DashboardRepository repo)
{
    _repo = repo;
}

SiteController (the right way):

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

psql - save results of command to a file

This approach will work with any psql command from the simplest to the most complex without requiring any changes or adjustments to the original command.

NOTE: For Linux servers.


  • Save the contents of your command to a file

MODEL

read -r -d '' FILE_CONTENT << 'HEREDOC'
[COMMAND_CONTENT]

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd

EXAMPLE

read -r -d '' FILE_CONTENT << 'HEREDOC'
DO $f$
declare
    curid INT := 0;
    vdata BYTEA;
    badid VARCHAR;
    loc VARCHAR;
begin
FOR badid IN SELECT some_field FROM public.some_base LOOP
    begin
    select 'ctid - '||ctid||'pagenumber - '||(ctid::text::point) [0]::bigint
        into loc
        from public.some_base where some_field = badid;
        SELECT file||' '
        INTO vdata
        FROM public.some_base where some_field = badid;
    exception
        when others then
        raise notice 'Block/PageNumber - % ',loc;
            raise notice 'Corrupted id - % ', badid;
            --return;
    end;
end loop;
end;
$f$;

HEREDOC
echo -n "$FILE_CONTENT" > sqlcmd
  • Run the command

MODEL

sudo -u postgres psql [some_db] -c "$(cat sqlcmd)" >>sqlop 2>&1

EXAMPLE

sudo -u postgres psql some_db -c "$(cat sqlcmd)" >>sqlop 2>&1

  • View/track your command output

cat sqlop

Done! Thanks! =D

How do I list loaded plugins in Vim?

:help local-additions

Lists local plugins added.

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

How do I add my new User Control to the Toolbox or a new Winform?

I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.

How do I convert a float number to a whole number in JavaScript?

To truncate:

_x000D_
_x000D_
// Math.trunc() is part of the ES6 spec
console.log(Math.trunc( 1.5 ));  // returns 1
console.log(Math.trunc( -1.5 )); // returns -1
// Math.floor( -1.5 ) would return -2, which is probably not what you wanted
_x000D_
_x000D_
_x000D_

To round:

_x000D_
_x000D_
console.log(Math.round( 1.5 ));  // 2
console.log(Math.round( 1.49 )); // 1
console.log(Math.round( -1.6 )); // -2
console.log(Math.round( -1.3 )); // -1
_x000D_
_x000D_
_x000D_

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

setAllowUrlEncodedSlash(true) didn't work for me. Still internal method isNormalized return false when having double slash.

I replaced StrictHttpFirewall with DefaultHttpFirewall by having the following code only:

@Bean
public HttpFirewall defaultHttpFirewall() {
    return new DefaultHttpFirewall();
}

Working well for me.
Any risk by using DefaultHttpFirewall?

Get the first element of an array

Some arrays don't work with functions like list, reset or current. Maybe they're "faux" arrays - partially implementing ArrayIterator, for example.

If you want to pull the first value regardless of the array, you can short-circuit an iterator:

foreach($array_with_unknown_keys as $value) break;

Your value will then be available in $value and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).

You can grab the key this way too:

foreach($array_with_unknown_keys as $key=>$value) break;

If you're calling this from a function, simply return early:

function grab_first($arr) {
    foreach($arr as $value) return $value;
}

TypeScript enum to object array

I didn't like any of the above answers because none of them correctly handle the mixture of strings/numbers that can be values in TypeScript enums.

The following function follows the semantics of TypeScript enums to give a proper Map of keys to values. From there, getting an array of objects or just the keys or just the values is trivial.

/**
 * Converts the given enum to a map of the keys to the values.
 * @param enumeration The enum to convert to a map.
 */
function enumToMap(enumeration: any): Map<string, string | number> {
  const map = new Map<string, string | number>();
  for (let key in enumeration) {
      //TypeScript does not allow enum keys to be numeric
      if (!isNaN(Number(key))) continue;

      const val = enumeration[key] as string | number;

      //TypeScript does not allow enum value to be null or undefined
      if (val !== undefined && val !== null)
          map.set(key, val);
  }

  return map;
}

Example Usage:

enum Dog {
    Rover = 1,
    Lassie = "Collie",
    Fido = 3,
    Cody = "Mutt",
}

let map = enumToMap(Dog); //Map of keys to values

let objs = Array.from(map.entries()).map(m => ({id: m[1], name: m[0]})); //Objects as asked for in OP
let entries = Array.from(map.entries()); //Array of each entry
let keys = Array.from(map.keys()); //An array of keys
let values = Array.from(map.values()); //An array of values

I'll also point out that the OP is thinking of enums backwards. The "key" in the enum is technically on the left hand side and the value is on the right hand side. TypeScript allows you to repeat the values on the RHS as much as you'd like.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

Javascript Drag and drop for touch devices

Thanks for the above codes! - I tried several options and this was the ticket. I had problems in that preventDefault was preventing scrolling on the ipad - I am now testing for draggable items and it works great so far.

if (event.target.id == 'draggable_item' ) {
    event.preventDefault();
}

Angular - POST uploaded file

Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await by .then().

Input change handler:

/**
 * @param fileInput
 */
public psdTemplateSelectionHandler (fileInput: any){
    let FileList: FileList = fileInput.target.files;

    for (let i = 0, length = FileList.length; i < length; i++) {
        this.psdTemplates.push(FileList.item(i));
    }

    this.progressBarVisibility = true;
}

Submit handler:

public async psdTemplateUploadHandler (): Promise<any> {
    let result: any;

    if (!this.psdTemplates.length) {
        return;
    }

    this.isSubmitted = true;

    this.fileUploadService.getObserver()
        .subscribe(progress => {
            this.uploadProgress = progress;
        });

    try {
        result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
    } catch (error) {
        document.write(error)
    }

    if (!result['images']) {
        return;
    }

    this.saveUploadedTemplatesData(result['images']);
    this.redirectService.redirect(this.redirectRoute);
}

FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.

import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';

@Injectable()
export class FileUploadService {
/**
 * @param Observable<number>
 */
private progress$: Observable<number>;

/**
 * @type {number}
 */
private progress: number = 0;

private progressObserver: any;

constructor () {
    this.progress$ = new Observable(observer => {
        this.progressObserver = observer
    });
}

/**
 * @returns {Observable<number>}
 */
public getObserver (): Observable<number> {
    return this.progress$;
}

/**
 * Upload files through XMLHttpRequest
 *
 * @param url
 * @param files
 * @returns {Promise<T>}
 */
public upload (url: string, files: File[]): Promise<any> {
    return new Promise((resolve, reject) => {
        let formData: FormData = new FormData(),
            xhr: XMLHttpRequest = new XMLHttpRequest();

        for (let i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        FileUploadService.setUploadUpdateInterval(500);

        xhr.upload.onprogress = (event) => {
            this.progress = Math.round(event.loaded / event.total * 100);

            this.progressObserver.next(this.progress);
        };

        xhr.open('POST', url, true);
        xhr.send(formData);
    });
}

/**
 * Set interval for frequency with which Observable inside Promise will share data with subscribers.
 *
 * @param interval
 */
private static setUploadUpdateInterval (interval: number): void {
    setInterval(() => {}, interval);
}
}

Custom Listview Adapter with filter Android

I hope it will be helpful for others.

// put below code (method) in Adapter class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    myList.clear();
    if (charText.length() == 0) {
        myList.addAll(arraylist);
    }
    else
    {
        for (MyBean wp : arraylist) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                myList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}

declare below code in adapter class

private ArrayList<MyBean> myList;  // for loading main list
private ArrayList<MyBean> arraylist=null;  // for loading  filter data

below code in adapter Constructor

this.arraylist = new ArrayList<MyBean>();
    this.arraylist.addAll(myList);

and below code in your activity class

final EditText searchET = (EditText)findViewById(R.id.search_et);
    // Capture Text in EditText
    searchET.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1,
                                      int arg2, int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            // TODO Auto-generated method stub
        }
    });

What is the purpose of nameof?

I find that nameof increases the readability of very long and complex SQL statements in my applications. It makes the variables stand out of that sea of strings and eliminates your job of figuring out where the variables are used in your SQL statements.

public bool IsFooAFoo(string foo, string bar)
{
    var aVeryLongAndComplexQuery = $@"SELECT yada, yada
    -- long query in here
    WHERE fooColumn = @{nameof(foo)}
    AND barColumn = @{nameof(bar)}
    -- long query here";


    SqlParameter[] parameters = {
        new SqlParameter(nameof(foo), SqlDBType.VarChar, 10){ Value = foo },
        new SqlParameter(nameof(bar), SqlDBType.VarChar, 10){ Value = bar },
    }
}

Generate a dummy-variable

For the usecase as presented in the question, you can also just multiply the logical condition with 1 (or maybe even better, with 1L):

# example data
df1 <- data.frame(yr = 1951:1960)

# create the dummies
df1$is.1957 <- 1L * (df1$yr == 1957)
df1$after.1957 <- 1L * (df1$yr >= 1957)

which gives:

> df1
     yr is.1957 after.1957
1  1951       0          0
2  1952       0          0
3  1953       0          0
4  1954       0          0
5  1955       0          0
6  1956       0          0
7  1957       1          1
8  1958       0          1
9  1959       0          1
10 1960       0          1

For the usecases as presented in for example the answers of @zx8754 and @Sotos, there are still some other options which haven't been covered yet imo.

1) Make your own make_dummies-function

# example data
df2 <- data.frame(id = 1:5, year = c(1991:1994,1992))

# create a function
make_dummies <- function(v, prefix = '') {
  s <- sort(unique(v))
  d <- outer(v, s, function(v, s) 1L * (v == s))
  colnames(d) <- paste0(prefix, s)
  d
}

# bind the dummies to the original dataframe
cbind(df2, make_dummies(df2$year, prefix = 'y'))

which gives:

  id year y1991 y1992 y1993 y1994
1  1 1991     1     0     0     0
2  2 1992     0     1     0     0
3  3 1993     0     0     1     0
4  4 1994     0     0     0     1
5  5 1992     0     1     0     0

2) use the dcast-function from either or

 dcast(df2, id + year ~ year, fun.aggregate = length)

which gives:

  id year 1991 1992 1993 1994
1  1 1991    1    0    0    0
2  2 1992    0    1    0    0
3  3 1993    0    0    1    0
4  4 1994    0    0    0    1
5  5 1992    0    1    0    0

However, this will not work when there are duplicate values in the column for which the dummies have to be created. In the case a specific aggregation function is needed for dcast and the result of of dcast need to be merged back to the original:

# example data
df3 <- data.frame(var = c("B", "C", "A", "B", "C"))

# aggregation function to get dummy values
f <- function(x) as.integer(length(x) > 0)

# reshape to wide with the cumstom aggregation function and merge back to the original
merge(df3, dcast(df3, var ~ var, fun.aggregate = f), by = 'var', all.x = TRUE)

which gives (note that the result is ordered according to the by column):

  var A B C
1   A 1 0 0
2   B 0 1 0
3   B 0 1 0
4   C 0 0 1
5   C 0 0 1

3) use the spread-function from (with mutate from )

library(dplyr)
library(tidyr)

df2 %>% 
  mutate(v = 1, yr = year) %>% 
  spread(yr, v, fill = 0)

which gives:

  id year 1991 1992 1993 1994
1  1 1991    1    0    0    0
2  2 1992    0    1    0    0
3  3 1993    0    0    1    0
4  4 1994    0    0    0    1
5  5 1992    0    1    0    0

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

Convert a number range to another range, maintaining ratio

NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin

Or a little more readable:

OldRange = (OldMax - OldMin)  
NewRange = (NewMax - NewMin)  
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):

OldRange = (OldMax - OldMin)
if (OldRange == 0)
    NewValue = NewMin
else
{
    NewRange = (NewMax - NewMin)  
    NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}

Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: NewMin (see sample), NewMax or (NewMin + NewMax) / 2

How to scale Docker containers in production

One option not mentioned in other posts is Helios. It is built by spotify and does not try to do too much.

https://github.com/spotify/helios

Encoding conversion in java

UTF-8 and UCS-2/UTF-16 can be distinguished reasonably easily via a byte order mark at the start of the file. If this exists then it's a pretty good bet that the file is in that encoding - but it's not a dead certainty. You may well also find that the file is in one of those encodings, but doesn't have a byte order mark.

I don't know much about ISO-8859-2, but I wouldn't be surprised if almost every file is a valid text file in that encoding. The best you'll be able to do is check it heuristically. Indeed, the Wikipedia page talking about it would suggest that only byte 0x7f is invalid.

There's no idea of reading a file "as it is" and yet getting text out - a file is a sequence of bytes, so you have to apply a character encoding in order to decode those bytes into characters.

Source by stackoverflow

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

What's the difference between unit, functional, acceptance, and integration tests?

unit test: testing of individual module or independent component in an application is known to be unit testing , the unit testing will be done by developer.

integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not , this testing also performed by developers.

funcional test checking the individual functionality of an application is mean to be functional testing

acceptance testing this testing is done by end user or customer whether the build application is according to the customer requirement , and customer specification this is known to be acceptance testing

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

In Swift 3, you can simply use CGPoint.zero or CGRect.zero in place of CGRectZero or CGPointZero.

However, in Swift 4, CGRect.zero and 'CGPoint.zero' will work

Add Bean Programmatically to Spring Web App Context

Why do you need it to be of type GenericWebApplicationContext?
I think you can probably work with any ApplicationContext type.

Usually you would use an init method (in addition to your setter method):

@PostConstruct
public void init(){
    AutowireCapableBeanFactory bf = this.applicationContext
        .getAutowireCapableBeanFactory();
    // wire stuff here
}

And you would wire beans by using either

AutowireCapableBeanFactory.autowire(Class, int mode, boolean dependencyInject)

or

AutowireCapableBeanFactory.initializeBean(Object existingbean, String beanName)

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Try a case statement

WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END

Emulator: ERROR: x86 emulation currently requires hardware acceleration

I was able to resolve my problem of the missing acceleration with the following workflow on Windows 10, Lenovo, Intel Core i7 CPU:

Changed to the HAXM setup folder: C:\Users\\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager

Opened a cmd (MS-DOS) shell Window and executed haxm_check.exe to check whether CPU supports HAXM - it outputs in my case:

VT support -- yes
NX support -- yes

So, I knew this most be a setup problem. So, I started the setup program intelhaxm-android.exe in the same folder with Admin account and removed the installed components. After that, I've attempted to re-install with the same setup program and got this output:

HAXM Supported but not turned on So, I went into the CPU section of the BIOS and turned on acceleration/Virtualization - went back to the setup program and re-ran it, this time I was pleased to see this output:

enter image description here

After that, I restarted Android Studio and used Tools>AVD Manager to define a new image for an emulator. I was then able to see the emulator starting up succesfully by clicking the play button in the list of emulators in the AVD Manager's list:

enter image description here

or by - Opening a sample project that compiles OK - using File > Sync Project with Gradle Files (to build all artifacts) - Select the app item in the Android (TW) and click Run > Run 'app' - Select the previously configured Emaulator showed me this :-)

Hope this helps to troubleshoot others with their problems that are really caused by a bad setup implementation since the missing acceleration option was silently swallowed by the Android Studio setup program ... :-(

enter image description here

How to check if an element is in an array

For those who came here looking for a find and remove an object from an array:

Swift 1

if let index = find(itemList, item) {
    itemList.removeAtIndex(index)
}

Swift 2

if let index = itemList.indexOf(item) {
    itemList.removeAtIndex(index)
}

Swift 3, 4

if let index = itemList.index(of: item) {
    itemList.remove(at: index)
}

Swift 5.2

if let index = itemList.firstIndex(of: item) {
    itemList.remove(at: index)
}

Set Locale programmatically

There is a super simple way.

in BaseActivity, Activity or Fragment override attachBaseContext

 override fun attachBaseContext(context: Context) {
    super.attachBaseContext(context.changeLocale("tr"))
}

extension

fun Context.changeLocale(language:String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)
    val config = this.resources.configuration
    config.setLocale(locale)
    return createConfigurationContext(config)
}

I want to get the type of a variable at runtime

So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:

val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x

But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:

val x: Any = 5
def f[T](v: T) = v match {
  case _: Int    => "Int"
  case _: String => "String"
  case _         => "Unknown"
}
f(x)

Here it doesn't matter what is the type of the variable, Any. What matters, what is checked is the type of 5, the value. In fact, T is useless -- you might as well have written it def f(v: Any) instead. Also, this uses either ClassTag or a value's Class, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_] (List of something), but not whether it is, for example, a List[Int] or List[String].

Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag or a TypeTag. For example:

val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"

A ClassTag will also let you use type parameters you received on match. This won't work:

def f[A, B](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}

But this will:

val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
  case _: B => "A is a B"
  case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)

Here I'm using the context bounds syntax, B : ClassTag, which works just like the implicit parameter in the previous ClassTag example, but uses an anonymous variable.

One can also get a ClassTag from a value's Class, like this:

val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
  val B = ClassTag(b.getClass)
  ClassTag(a.getClass) match {
    case B => "a is the same class as b"
    case _ => "a is not the same class as b"
  }
}
f(x, y) == f(y, x) // true, a is the same class as b

A ClassTag is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag for List[Int] and List[String] is the same, List. If you need type parameters, then you must use a TypeTag instead. A TypeTag however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.

Examples with TypeTag can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:

import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int

Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag, so I'll stop here.

Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:

val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it

It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.

Creating SolidColorBrush from hex color value

I've been using:

new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));

Can my enums have friendly names?

Enum value names must follow the same naming rules as all identifiers in C#, therefore only first name is correct.

How to get the date from jQuery UI datepicker

NamingException's answer worked for me. Except I used

var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker didn't work but dtpicker did.

Swift: declare an empty dictionary

The Swift documentation recommends the following way to initialize an empty Dictionary:

var emptyDict = [String: String]()

I was a little confused when I first came across this question because different answers showed different ways to initialize an empty Dictionary. It turns out that there are actually a lot of ways you can do it, though some are a little redundant or overly verbose given Swift's ability to infer the type.

var emptyDict = [String: String]()
var emptyDict = Dictionary<String, String>()
var emptyDict: [String: String] = [:]
var emptyDict: [String: String] = [String: String]()
var emptyDict: [String: String] = Dictionary<String, String>()
var emptyDict: Dictionary = [String: String]()
var emptyDict: Dictionary = Dictionary<String, String>()
var emptyDict: Dictionary<String, String> = [:]
var emptyDict: Dictionary<String, String> = [String: String]()
var emptyDict: Dictionary<String, String> = Dictionary<String, String>()

After you have an empty Dictionary you can add a key-value pair like this:

emptyDict["some key"] = "some value"

If you want to empty your dictionary again, you can do the following:

emptyDict = [:]

The types are still <String, String> because that is how it was initialized.

How to run crontab job every week on Sunday

10 * * * Sun

Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12 
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday. 

jquery draggable: how to limit the draggable area?

Use the "containment" option:

jQuery UI API - Draggable Widget - containment

The documentation says it only accepts the values: 'parent', 'document', 'window', [x1, y1, x2, y2] but I seem to remember it will accept a selector such as '#container' too.

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Should I use window.navigate or document.location in JavaScript?

You can move your page using

window.location.href =Url;

How To have Dynamic SQL in MySQL Stored Procedure

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.

What's the difference between JavaScript and Java?

Java and Javascript are similar like Car and Carpet are similar.

How do I access my webcam in Python?

gstreamer can handle webcam input. If I remeber well, there are python bindings for it!

Mean per group in a data.frame

You can also accomplish this using the sqldf package as shown below:

library(sqldf)

x <- read.table(text='Name     Month  Rate1     Rate2
Aira       1      12        23
                Aira       2      18        73
                Aira       3      19        45
                Ben        1      53        19
                Ben        2      22        87
                Ben        3      19        45
                Cat        1      22        87
                Cat        2      67        43
                Cat        3      45        32', header=TRUE)

sqldf("
select 
  Name
  ,avg(Rate1) as Rate1_float
  ,avg(Rate2) as Rate2_float
  ,avg(Rate1) as Rate1
  ,avg(Rate2) as Rate2
from x
group by 
  Name
")

#  Name Rate1_float Rate2_float Rate1 Rate2
#1 Aira    16.33333    47.00000    16    47
#2  Ben    31.33333    50.33333    31    50
#3  Cat    44.66667    54.00000    44    54

I am a recent convert to dplyr as shown in other answers, but sqldf is nice as most data analysts/data scientists/developers have at least some fluency in SQL. In this way, I think it tends to make for more universally readable code than dplyr or other solutions presented above.

UPDATE: In responding to the comment below, I attempted to update the code as shown above. However, the behavior was not as I expected. It seems that the column definition (i.e. int vs float) is only carried through when the column alias matches the original column name. When you specify a new name, the aggregate column is returned without rounding.

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

Run an Ansible task only when the variable contains a specific string

If variable1 is a string, and you are searching for a substring in it, this should work:

when: '"value" in variable1'

if variable1 is an array or dict instead, in will search for the exact string as one of its items.

Using the Underscore module with Node.js

The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:

Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6

How to allocate aligned memory only using the standard library?

We do this sort of thing all the time for Accelerate.framework, a heavily vectorized OS X / iOS library, where we have to pay attention to alignment all the time. There are quite a few options, one or two of which I didn't see mentioned above.

The fastest method for a small array like this is just stick it on the stack. With GCC / clang:

 void my_func( void )
 {
     uint8_t array[1024] __attribute__ ((aligned(16)));
     ...
 }

No free() required. This is typically two instructions: subtract 1024 from the stack pointer, then AND the stack pointer with -alignment. Presumably the requester needed the data on the heap because its lifespan of the array exceeded the stack or recursion is at work or stack space is at a serious premium.

On OS X / iOS all calls to malloc/calloc/etc. are always 16 byte aligned. If you needed 32 byte aligned for AVX, for example, then you can use posix_memalign:

void *buf = NULL;
int err = posix_memalign( &buf, 32 /*alignment*/, 1024 /*size*/);
if( err )
   RunInCirclesWaivingArmsWildly();
...
free(buf);

Some folks have mentioned the C++ interface that works similarly.

It should not be forgotten that pages are aligned to large powers of two, so page-aligned buffers are also 16 byte aligned. Thus, mmap() and valloc() and other similar interfaces are also options. mmap() has the advantage that the buffer can be allocated preinitialized with something non-zero in it, if you want. Since these have page aligned size, you will not get the minimum allocation from these, and it will likely be subject to a VM fault the first time you touch it.

Cheesy: Turn on guard malloc or similar. Buffers that are n*16 bytes in size such as this one will be n*16 bytes aligned, because VM is used to catch overruns and its boundaries are at page boundaries.

Some Accelerate.framework functions take in a user supplied temp buffer to use as scratch space. Here we have to assume that the buffer passed to us is wildly misaligned and the user is actively trying to make our life hard out of spite. (Our test cases stick a guard page right before and after the temp buffer to underline the spite.) Here, we return the minimum size we need to guarantee a 16-byte aligned segment somewhere in it, and then manually align the buffer afterward. This size is desired_size + alignment - 1. So, In this case that is 1024 + 16 - 1 = 1039 bytes. Then align as so:

#include <stdint.h>
void My_func( uint8_t *tempBuf, ... )
{
    uint8_t *alignedBuf = (uint8_t*) 
                          (((uintptr_t) tempBuf + ((uintptr_t)alignment-1)) 
                                        & -((uintptr_t) alignment));
    ...
}

Adding alignment-1 will move the pointer past the first aligned address and then ANDing with -alignment (e.g. 0xfff...ff0 for alignment=16) brings it back to the aligned address.

As described by other posts, on other operating systems without 16-byte alignment guarantees, you can call malloc with the larger size, set aside the pointer for free() later, then align as described immediately above and use the aligned pointer, much as described for our temp buffer case.

As for aligned_memset, this is rather silly. You only have to loop in up to 15 bytes to reach an aligned address, and then proceed with aligned stores after that with some possible cleanup code at the end. You can even do the cleanup bits in vector code, either as unaligned stores that overlap the aligned region (providing the length is at least the length of a vector) or using something like movmaskdqu. Someone is just being lazy. However, it is probably a reasonable interview question if the interviewer wants to know whether you are comfortable with stdint.h, bitwise operators and memory fundamentals, so the contrived example can be forgiven.

What does the term "canonical form" or "canonical representation" in Java mean?

An easy way to remember it is the way "canonical" is used in theological circles, canonical truth is the real truth so if two people find it they have found the same truth. Same with canonical instance. If you think you have found two of them (i.e. a.equals(b)) you really only have one (i.e. a == b). So equality implies identity in the case of canonical object.

Now for the comparison. You now have the choice of using a==b or a.equals(b), since they will produce the same answer in the case of canonical instance but a==b is comparison of the reference (the JVM can compare two numbers extremely rapidly as they are just two 32 bit patterns compared to a.equals(b) which is a method call and involves more overhead.

Credentials for the SQL Server Agent service are invalid

You might encounter one of these three problems:

A blog post with the summary for all three possible problems might be found here: https://cms4j.wordpress.com/2016/11/29/0x851c0001-the-credentials-you-provided-for-the-sqlserveragent-service-is-invalid/