Programs & Examples On #Set

A set is a collection in which no element is repeated, which may be able to enumerate its elements according to an ordering criterion (an "ordered set") or retain no order (an "unordered set").

How to convert an Array to a Set in Java

Varargs will work too!

Stream.of(T... values).collect(Collectors.toSet());

How to Iterate over a Set/HashSet without an Iterator?

To demonstrate, consider the following set, which holds different Person objects:

Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));

Person Model Class

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //TODO - getters,setters ,overridden toString & compareTo methods

}
  1. The for statement has a form designed for iteration through Collections and arrays .This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
for(Person p:people){
  System.out.println(p.getName());
}
  1. Java 8 - java.lang.Iterable.forEach(Consumer)
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:

The default implementation behaves as if: 

for (T t : this)
     action.accept(t);

Parameters: action - The action to be performed for each element

Throws: NullPointerException - if the specified action is null

Since: 1.8

How to set background image in Java?

The Path is the only thing you really have to worry about if you are really new to Java. You need to drag your image into the main project file, and it will show up at the very bottom of the list.

Then the file path is pretty straight forward. This code goes into the constructor for the class.

    img = Toolkit.getDefaultToolkit().createImage("/home/ben/workspace/CS2/Background.jpg");

CS2 is the name of my project, and everything before that is leading to the workspace.

Python set to list

s = set([1,2,3])
print [ x for x in iter(s) ]

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Python convert set to string and vice versa

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

Copying sets Java

Another way to do this is to use the copy constructor:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);

Or create an empty set and add the elements:

Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);

Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.


Note that the result of copying a Set is a new Set containing references to the objects that are elements if the original Set. The element objects themselves are not copied or cloned. This conforms with the way that the Java Collection APIs are designed to work: they don't copy the element objects.

Java Set retain order?

Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?

Get difference between two lists

I prefer to use converting to sets and then using the "difference()" function. The full code is :

temp1 = ['One', 'Two', 'Three', 'Four'  ]                   
temp2 = ['One', 'Two']
set1 = set(temp1)
set2 = set(temp2)
set3 = set1.difference(set2)
temp3 = list(set3)
print(temp3)

Output:

>>>print(temp3)
['Three', 'Four']

It's the easiest to undersand, and morover in future if you work with large data, converting it to sets will remove duplicates if duplicates are not required. Hope it helps ;-)

How to get all subsets of a set? (powerset)

Just a quick power set refresher !

Power set of a set X, is simply the set of all subsets of X including the empty set

Example set X = (a,b,c)

Power Set = { { a , b , c } , { a , b } , { a , c } , { b , c } , { a } , { b } , { c } , { } }

Here is another way of finding power set:

def power_set(input):
    # returns a list of all subsets of the list a
    if (len(input) == 0):
        return [[]]
    else:
        main_subset = [ ]
        for small_subset in power_set(input[1:]):
            main_subset += [small_subset]
            main_subset += [[input[0]] + small_subset]
        return main_subset

print(power_set([0,1,2,3]))

full credit to source

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Add list to set?

You want to add a tuple, not a list:

>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> t = tuple(l)
>>> t
('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])

If you have a list, you can convert to the tuple, as shown above. A tuple is immutable, so it can be added to the set.

In Python, when to use a Dictionary, List or Set?

Although this doesn't cover sets, it is a good explanation of dicts and lists:

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.

Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.

http://www.sthurlow.com/python/lesson06/

How to check if a table contains an element in Lua?

I can't think of another way to compare values, but if you use the element of the set as the key, you can set the value to anything other than nil. Then you get fast lookups without having to search the entire table.

Getting the difference between two sets

You can make a union using .addAll(), and an intersection using .retainAll(), of the two sets and use .removeIf(), to remove the intersection (or the duplicated element) from the union.

HashSet union = new HashSet(group1);
union.addAll(group2);
        
System.out.println("Union: " + union);
        
HashSet intersection = new HashSet(group1);
intersection.retainAll(group2);
        
System.out.println("Intersection: " + intersection);
        
HashSet difference = new HashSet(union);
difference.removeIf(n -> (difference.contains(intersection)));
        
System.out.println("Difference: " + difference);

How to convert a set to a list in python?

Python is a dynamically typed language, which means that you cannot define the type of the variable as you do in C or C++:

type variable = value

or

type variable(value)

In Python, you use coercing if you change types, or the init functions (constructors) of the types to declare a variable of a type:

my_set = set([1,2,3])
type my_set

will give you <type 'set'> for an answer.

If you have a list, do this:

my_list = [1,2,3]
my_set = set(my_list)

Does Python have an ordered set?

If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The sortedcontainers module provides a SortedSet for just this purpose. Some benefits: pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.

Installing from PyPI is easy with pip:

pip install sortedcontainers

Note that if you can't pip install, simply pull down the sortedlist.py and sortedset.py files from the open-source repository.

Once installed you can simply:

from sortedcontainers import SortedSet
help(SortedSet)

The sortedcontainers module also maintains a performance comparison with several alternative implementations.

For the comment that asked about Python's bag data type, there's alternatively a SortedList data type which can be used to efficiently implement a bag.

Properties file with a list as the value for an individual key

Try writing the properties as a comma separated list, then split the value after the properties file is loaded. For example

a=one,two,three
b=nine,ten,fourteen

You can also use org.apache.commons.configuration and change the value delimiter using the AbstractConfiguration.setListDelimiter(char) method if you're using comma in your values.

Append values to a set in Python

keep.update((0,1,2,3,4,5,6,7,8,9,10))

Or

keep.update(np.arange(11))

Understanding the set() function

Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.

Here's an example of a set changing order after a lot of values are added and then removed:

>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
    s.remove(v)
>>> print(s)
{1, 6, 8}

This is implementation dependent though, and so you should not rely upon it.

Difference between Iterator and Listiterator?

The differences are listed in the Javadoc for ListIterator

You can

  • iterate backwards
  • obtain the iterator at any point.
  • add a new value at any point.
  • set a new value at that point.

Python Sets vs Lists

I was interested in the results when checking, with CPython, if a value is one of a small number of literals. set wins in Python 3 vs tuple, list and or:

from timeit import timeit

def in_test1():
  for i in range(1000):
    if i in (314, 628):
      pass

def in_test2():
  for i in range(1000):
    if i in [314, 628]:
      pass

def in_test3():
  for i in range(1000):
    if i in {314, 628}:
      pass

def in_test4():
  for i in range(1000):
    if i == 314 or i == 628:
      pass

print("tuple")
print(timeit("in_test1()", setup="from __main__ import in_test1", number=100000))
print("list")
print(timeit("in_test2()", setup="from __main__ import in_test2", number=100000))
print("set")
print(timeit("in_test3()", setup="from __main__ import in_test3", number=100000))
print("or")
print(timeit("in_test4()", setup="from __main__ import in_test4", number=100000))

Output:

tuple
4.735646052286029
list
4.7308746771886945
set
3.5755991376936436
or
4.687681658193469

For 3 to 5 literals, set still wins by a wide margin, and or becomes the slowest.

In Python 2, set is always the slowest. or is the fastest for 2 to 3 literals, and tuple and list are faster with 4 or more literals. I couldn't distinguish the speed of tuple vs list.

When the values to test were cached in a global variable out of the function, rather than creating the literal within the loop, set won every time, even in Python 2.

These results apply to 64-bit CPython on a Core i7.

How to sort a HashSet?

We can not decide that the elements of a HashSet would be sorted automatically. But we can sort them by converting into TreeSet or any List like ArrayList or LinkedList etc.

// Create a TreeSet object of class E
TreeSet<E> ts = new TreeSet<E> ();

// Convert your HashSet into TreeSet
ts.addAll(yourHashSet);

System.out.println(ts.toString() + "\t Sorted Automatically");

Python Set Comprehension

You can generate pairs like this:

{(x, x + 2) for x in r if x + 2 in r}

Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.

A different way of doing it: (Although slower for large sets of primes)

{(x, y) for x in r for y in r if x + 2 == y}

C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

Any implementation of Ordered Set in Java?

Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.

You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.

Also, you can't insert at a certain position.

Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Finally, I have found a solution and it's a simple one:

document.getElementById("texens").value = "tinkumaster";

Works like a charm. No clue why jQuery does not fall back to this.

Best way to find the intersection of multiple sets?

I believe the simplest thing to do is:

#assuming three sets
set1 = {1,2,3,4,5}
set2 = {2,3,8,9}
set3 = {2,10,11,12}

#intersection
set4 = set1 & set2 & set3

set4 will be the intersection of set1 , set2, set3 and will contain the value 2.

print(set4)

set([2])

OpenMP set_num_threads() is not working

Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4

#pragma omp parallel
{
   omp_set_num_threads(4);
   int id = omp_get_num_threads();
   #pragma omp for
   for (i = 0:n){foo(A);}
}

printf("Number of threads: %d", id);

What is the difference between Set and List?

List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered (thank you, Quinn Taylor).

List<E>:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Set<E>:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Getting an element from a Set

Why:

It seems that Set plays a useful role in providing a means of comparison. It is designed not to store duplicate elements.

Because of this intention/design, if one were to get() a reference to the stored object, then mutate it, it is possible that the design intentions of Set could be thwarted and could cause unexpected behavior.

From the JavaDocs

Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set.

How:

Now that Streams have been introduced one can do the following

mySet.stream()
.filter(object -> object.property.equals(myProperty))
.findFirst().get();

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

Converting a list to a set changes element order

In mathematics, there are sets and ordered sets (osets).

  • set: an unordered container of unique elements (Implemented)
  • oset: an ordered container of unique elements (NotImplemented)

In Python, only sets are directly implemented. We can emulate osets with regular dict keys (3.7+).

Given

a = [1, 2, 20, 6, 210, 2, 1]
b = {2, 6}

Code

oset = dict.fromkeys(a).keys()
# dict_keys([1, 2, 20, 6, 210])

Demo

Replicates are removed, insertion-order is preserved.

list(oset)
# [1, 2, 20, 6, 210]

Set-like operations on dict keys.

oset - b
# {1, 20, 210}

oset | b
# {1, 2, 5, 6, 20, 210}

oset & b
# {2, 6}

oset ^ b
# {1, 5, 20, 210}

Details

Note: an unordered structure does not preclude ordered elements. Rather, maintained order is not guaranteed. Example:

assert {1, 2, 3} == {2, 3, 1}                    # sets (order is ignored)

assert [1, 2, 3] != [2, 3, 1]                    # lists (order is guaranteed)

One may be pleased to discover that a list and multiset (mset) are two more fascinating, mathematical data structures:

  • list: an ordered container of elements that permits replicates (Implemented)
  • mset: an unordered container of elements that permits replicates (NotImplemented)*

Summary

Container | Ordered | Unique | Implemented
----------|---------|--------|------------
set       |    n    |    y   |     y
oset      |    y    |    y   |     n
list      |    y    |    n   |     y
mset      |    n    |    n   |     n*  

*A multiset can be indirectly emulated with collections.Counter(), a dict-like mapping of multiplicities (counts).

How to get the first element of the List or Set?

I'm surprised that nobody suggested guava solution yet:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

or if you expect single element:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

Why doesn't java.util.Set have get(int index)?

Please note only 2 basic data structure can be accessed via index.

  • Array data structure can be accessed via index with O(1) time complexity to achieve get(int index) operation.
  • LinkedList data structure can also be accessed via index, but with O(n) time complexity to achieve get(int index) operation.

In Java, ArrayList is implemented using Array data structure.

While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1) time complexity contains operation. In Java, HashSet is the most common used implementation of Set, it is implemented by calling HashMap API, and HashMap is implemented using separate chaining with linked lists (a combination of Array and LinkedList).

Since Set can be implemented via different data structure, there is no get(int index) method for it.

Swift Set to Array

The current answer for Swift 2.x and higher (from the Swift Programming Language guide on Collection Types) seems to be to either iterate over the Set entries like so:

for item in myItemSet {
   ...
}

Or, to use the "sorted" method:

let itemsArray = myItemSet.sorted()

It seems the Swift designers did not like allObjects as an access mechanism because Sets aren't really ordered, so they wanted to make sure you didn't get out an array without an explicit ordering applied.

If you don't want the overhead of sorting and don't care about the order, I usually use the map or flatMap methods which should be a bit quicker to extract an array:

let itemsArray = myItemSet.map { $0 }

Which will build an array of the type the Set holds, if you need it to be an array of a specific type (say, entitles from a set of managed object relations that are not declared as a typed set) you can do something like:

var itemsArray : [MyObjectType] = []
if let typedSet = myItemSet as? Set<MyObjectType> {
 itemsArray = typedSet.map { $0 }
}

How do I iterate and modify Java Sets?

You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:

Set<Integer> set = new TreeSet<Integer>();
    set.add(1);
    set.add(2);
    set.add(3);

    //good way:
    Iterator<Integer> iterator = set.iterator();
    while(iterator.hasNext()) {
        Integer setElement = iterator.next();
        if(setElement==2) {
            iterator.remove();
        }
    }

    //bad way:
    for(Integer setElement:set) {
        if(setElement==2) {
            //might work or might throw exception, Java calls it indefined behaviour:
            set.remove(setElement);
        } 
    }

As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :

Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:

https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html

stipulate, amongst others, that (emphasis mine):

"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)

"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."

To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).

This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.

Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.

How to set background color of a View

Let suppose we have a primary color in values=>colors.xml as:

<resources>
    <color name="primary">#FDD835</color>
</resources>

so if we want to use our custom color into setBackgroundColor(@ColorInt int Color) then we just need an annotation @SuppressLint("ResourceAsColor") with constructor/method which will be used as:

    @SuppressLint("ResourceAsColor")
    public _LinearLayout(Context context) {
        super(context);

        // Formatting our layout : )
        super.setBackgroundColor(R.color.primary);

        ....


    }

Set the Value of a Hidden field using JQuery

Drop the hash - that's for identifying the id attribute.

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

How to join two sets in one line without using "|"

Assuming you also can't use s.union(t), which is equivalent to s | t, you could try

>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])

Or, if you want a comprehension,

>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])

How do I add the contents of an iterable to a set?

Use list comprehension.

Short circuiting the creation of iterable using a list for example :)

>>> x = [1, 2, 3, 4]
>>> 
>>> k = x.__iter__()
>>> k
<listiterator object at 0x100517490>
>>> l = [y for y in k]
>>> l
[1, 2, 3, 4]
>>> 
>>> z = Set([1,2])
>>> z.update(l)
>>> z
set([1, 2, 3, 4])
>>> 

[Edit: missed the set part of question]

What is the fastest way to compare two sets in Java?

firstSet.equals(secondSet)

It really depends on what you want to do in the comparison logic... ie what happens if you find an element in one set not in the other? Your method has a void return type so I assume you'll do the necessary work in this method.

More fine-grained control if you need it:

if (!firstSet.containsAll(secondSet)) {
  // do something if needs be
}
if (!secondSet.containsAll(firstSet)) {
  // do something if needs be
}

If you need to get the elements that are in one set and not the other.
EDIT: set.removeAll(otherSet) returns a boolean, not a set. To use removeAll(), you'll have to copy the set then use it.

Set one = new HashSet<>(firstSet);
Set two = new HashSet<>(secondSet);
one.removeAll(secondSet);
two.removeAll(firstSet);

If the contents of one and two are both empty, then you know that the two sets were equal. If not, then you've got the elements that made the sets unequal.

You mentioned that the number of records might be high. If the underlying implementation is a HashSet then the fetching of each record is done in O(1) time, so you can't really get much better than that. TreeSet is O(log n).

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

How to retrieve an element from a set without removing it?

tl;dr

for first_item in muh_set: break remains the optimal approach in Python 3.x. Curse you, Guido.

y u do this

Welcome to yet another set of Python 3.x timings, extrapolated from wr.'s excellent Python 2.x-specific response. Unlike AChampion's equally helpful Python 3.x-specific response, the timings below also time outlier solutions suggested above – including:

Code Snippets for Great Joy

Turn on, tune in, time it:

from timeit import Timer

stats = [
    "for i in range(1000): \n\tfor x in s: \n\t\tbreak",
    "for i in range(1000): next(iter(s))",
    "for i in range(1000): s.add(s.pop())",
    "for i in range(1000): list(s)[0]",
    "for i in range(1000): random.sample(s, 1)",
]

for stat in stats:
    t = Timer(stat, setup="import random\ns=set(range(100))")
    try:
        print("Time for %s:\t %f"%(stat, t.timeit(number=1000)))
    except:
        t.print_exc()

Quickly Obsoleted Timeless Timings

Behold! Ordered by fastest to slowest snippets:

$ ./test_get.py
Time for for i in range(1000): 
    for x in s: 
        break:   0.249871
Time for for i in range(1000): next(iter(s)):    0.526266
Time for for i in range(1000): s.add(s.pop()):   0.658832
Time for for i in range(1000): list(s)[0]:   4.117106
Time for for i in range(1000): random.sample(s, 1):  21.851104

Faceplants for the Whole Family

Unsurprisingly, manual iteration remains at least twice as fast as the next fastest solution. Although the gap has decreased from the Bad Old Python 2.x days (in which manual iteration was at least four times as fast), it disappoints the PEP 20 zealot in me that the most verbose solution is the best. At least converting a set into a list just to extract the first element of the set is as horrible as expected. Thank Guido, may his light continue to guide us.

Surprisingly, the RNG-based solution is absolutely horrible. List conversion is bad, but random really takes the awful-sauce cake. So much for the Random Number God.

I just wish the amorphous They would PEP up a set.get_first() method for us already. If you're reading this, They: "Please. Do something."

How to get first item from a java.util.Set?

To Access the element you need to get an iterator . But Iterator does not guarantee in a particular order unless it is some Exceptional case. so it is not sure to get the first Element.

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

Deleting elements from std::set while iterating

This behaviour is implementation specific. To guarantee the correctness of the iterator you should use "it = numbers.erase(it);" statement if you need to delete the element and simply incerement iterator in other case.

Collection that allows only unique items in .NET?

How about just an extension method on HashSet?

public static void AddOrThrow<T>(this HashSet<T> hash, T item)
{
    if (!hash.Add(item))
        throw new ValueExistingException();
}

Better/Faster to Loop through set or list?

For simplicity's sake: newList = list(set(oldList))

But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

JavaScript Array to Set

If you start out with:

let array = [
    {name: "malcom", dogType: "four-legged"},
    {name: "peabody", dogType: "three-legged"},
    {name: "pablo", dogType: "two-legged"}
];

And you want a set of, say, names, you would do:

let namesSet = new Set(array.map(item => item.name));

Convert Set to List without creating new List

Recently I found this:

ArrayList<T> yourList = Collections.list(Collections.enumeration(yourSet<T>));

Most concise way to convert a Set<T> to a List<T>

not really sure what you're doing exactly via the context of your code but...

why make the listOfTopicAuthors variable at all?

List<String> list = Arrays.asList((....).toArray( new String[0] ) );

the "...." represents however your set came into play, whether it's new or came from another location.

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

How to set a Javascript object values dynamically?

myObj.name=value

or

myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/

Get unique values from arraylist in java

you can use this for making a list Unique

ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");

ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());

Simplest way to merge ES6 Maps/Sets?

Transform the sets into arrays, flatten them and finally the constructor will uniqify.

const union = (...sets) => new Set(sets.map(s => [...s]).flat());

Is there any kind of hash code function in JavaScript?

The JavaScript specification defines indexed property access as performing a toString conversion on the index name. For example,

myObject[myProperty] = ...;

is the same as

myObject[myProperty.toString()] = ...;

This is necessary as in JavaScript

myObject["someProperty"]

is the same as

myObject.someProperty

And yes, it makes me sad as well :-(

Get all unique values in a JavaScript array (remove duplicates)

Finding unique in Array of objects using One Liner

const uniqueBy = (x,f)=>Object.values(x.reduce((a,b)=>((a[f(b)]=b),a),{}));
// f -> should must return string because it will be use as key

const data = [
  { comment: "abc", forItem: 1, inModule: 1 },
  { comment: "abc", forItem: 1, inModule: 1 },
  { comment: "xyz", forItem: 1, inModule: 2 },
  { comment: "xyz", forItem: 1, inModule: 2 },
];

uniqueBy(data, (x) => x.forItem +'-'+ x.inModule); // find unique by item with module
// output
// [
//   { comment: "abc", forItem: 1, inModule: 1 },
//   { comment: "xyz", forItem: 1, inModule: 2 },
// ];

// can also use for strings and number or other primitive values

uniqueBy([1, 2, 2, 1], (v) => v); // [1, 2]
uniqueBy(["a", "b", "a"], (v) => v); // ['a', 'b']

uniqueBy(
  [
    { id: 1, name: "abc" },
    { id: 2, name: "xyz" },
    { id: 1, name: "abc" },
  ],
  (v) => v.id
);
// output
// [
//   { id: 1, name: "abc" },
//   { id: 2, name: "xyz" },
// ];

How can I simulate an array variable in MySQL?

Isn't the point of arrays to be efficient? If you're just iterating through values, I think a cursor on a temporary (or permanent) table makes more sense than seeking commas, no? Also cleaner. Lookup "mysql DECLARE CURSOR".

For random access a temporary table with numerically indexed primary key. Unfortunately the fastest access you'll get is a hash table, not true random access.

Picking a random element from a set

This is identical to accepted answer (Khoth), but with the unnecessary size and i variables removed.

    int random = new Random().nextInt(myhashSet.size());
    for(Object obj : myhashSet) {
        if (random-- == 0) {
            return obj;
        }
    }

Though doing away with the two aforementioned variables, the above solution still remains random because we are relying upon random (starting at a randomly selected index) to decrement itself toward 0 over each iteration.

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

How to join entries in a set into one string?

Sets don't have a join method but you can use str.join instead.

', '.join(set_3)

The str.join method will work on any iterable object including lists and sets.

Note: be careful about using this on sets containing integers; you will need to convert the integers to strings before the call to join. For example

set_4 = {1, 2}
', '.join(str(s) for s in set_4)

How to store Query Result in variable using mysql

Additionally, if you want to set multiple variables at once by one query, you can use the other syntax for setting variables which goes like this: SELECT @varname:=value.

A practical example:

SELECT @total_count:=COUNT(*), @total_price:=SUM(quantity*price) FROM items ...

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

How to check that an element is in a std::set?

Another way of simply telling if an element exists is to check the count()

if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

Most of the times, however, I find myself needing access to the element wherever I check for its existence.

So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.

set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it
}

C++ 20

In C++20 set gets a contains function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 
}

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Convert string to Boolean in javascript

javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')

will not work because any non-empty string is true

javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')

works because compared with string represenation

How to redirect back to form with input - Laravel 5

You can use the following:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

Checkboxes in web pages – how to make them bigger?

Actually there is a way to make them bigger, checkboxes just like anything else (even an iframe like a facebook button).

Wrap them in a "zoomed" element:

_x000D_
_x000D_
.double {_x000D_
  zoom: 2;_x000D_
  transform: scale(2);_x000D_
  -ms-transform: scale(2);_x000D_
  -webkit-transform: scale(2);_x000D_
  -o-transform: scale(2);_x000D_
  -moz-transform: scale(2);_x000D_
  transform-origin: 0 0;_x000D_
  -ms-transform-origin: 0 0;_x000D_
  -webkit-transform-origin: 0 0;_x000D_
  -o-transform-origin: 0 0;_x000D_
  -moz-transform-origin: 0 0;_x000D_
}
_x000D_
<div class="double">_x000D_
  <input type="checkbox" name="hello" value="1">_x000D_
</div>
_x000D_
_x000D_
_x000D_

It might look a little bit "rescaled" but it works.

Of course you can make that div float:left and put your label besides it, float:left too.

How do I output the results of a HiveQL query to CSV?

You should use CREATE TABLE AS SELECT (CTAS) statement to create a directory in HDFS with the files containing the results of the query. After that you will have to export those files from HDFS to your regular disk and merge them into a single file.

You also might have to do some trickery to convert the files from '\001' - delimited to CSV. You could use a custom CSV SerDe or postprocess the extracted file.

Generics in C#, using type of a variable as parameter

You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.

In other words, after compilation,

DoesEntityExist<int>

is a different type to

DoesEntityExist<string>

This is how the compiler is able to enfore compile-time type safety.

For the scenario you describe, you should pass the type as an argument that can be examined at run time.

The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

Why does foo = filter(...) return a <filter object>, not a list?

Please see this sample implementation of filter to understand how it works in Python 3:

def my_filter(function, iterable):
    """my_filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true."""
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

The following is an example of how you might use filter or my_filter generators:

>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

Truncate (not round) decimal places in SQL Server

Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.

CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789

Why does background-color have no effect on this DIV?

Floats don't have a height so the containing div has a height of zero.

<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>

overflow:hidden clears the float for most browsers.

zoom:1 clears the float for IE.

How to get UTC+0 date in Java 8?

With Java 8 you can write:

OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

To answer your comment, you can then convert it to a Date (unless you depend on legacy code I don't see any reason why) or to millis since the epochs:

Date date = Date.from(utc.toInstant());
long epochMillis = utc.toInstant().toEpochMilli();

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

How to Batch Rename Files in a macOS Terminal?

In your specific case you can use the following bash command (bash is the default shell on macOS):

for f in *.png; do echo mv "$f" "${f/_*_/_}"; done

Note: If there's a chance that your filenames start with -, place -- before them[1]:
mv -- "$f" "${f/_*_/_}"

Note: echo is prepended to mv so as to perform a dry run. Remove it to perform actual renaming.

You can run it from the command line or use it in a script.

  • "${f/_*_/_}" is an application of bash parameter expansion: the (first) substring matching pattern _*_ is replaced with literal _, effectively cutting the middle token from the name.
  • Note that _*_ is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash and search for Pattern Matching).

If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename utility. On macOS you can install it using popular package manager Homebrew as follows:

brew install rename

Here's the equivalent of the command at the top using rename:

rename -n -e 's/_.*_/_/'  *.png

Again, this command performs a dry run; remove -n to perform actual renaming.

  • Similar to the bash solution, s/.../.../ performs text substitution, but - unlike in bash - true regular expressions are used.

[1] The purpose of special argument --, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -, as Jacob C. notes.

How to replace values at specific indexes of a python list?

numpy has arrays that allow you to use other lists/arrays as indices:

import numpy
S=numpy.array(s)
S[a]=m

Setting the correct PATH for Eclipse

I have resolved this problem by adding or changing variables in environment variables. Go to Win7 -> My Computer - > Properties - > Advanced system settings -> environment Variables

  1. If there is no variable JAVA_HOME, add it with value of variable, with route to folder where your JDK installed, for examle C:\Program Files\Java\jdk-11.0.2
  2. If there is no variable PATH or it have another value, change the value of variable to C:\Program Files\Java\jdk-11.0.2\bin or add variable PATH with this value

Good Luck

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

After a lot of research i found the solution for this huge error which i was struggling for 2 days.

Instead of changing the minSdkVerison & targetSdkVersion in build.gradle

Just open the Manifest file and use this

<uses-sdk 
android:minSdkVersion="17" 
android:targetSdkVersion="21"/

ArrayList vs List<> in C#

Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList ?” and “Why is it slower overall ?”, have a look below.

Whenever value types are used as elements, performance drops dramatically with ArrayList. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList’s Add only takes object parameters - the Garbage Collector gets triggered into performing a lot more work than with List<T>.

How much is the time difference ? At least several times slower than with List<T>. Just take a look at what happens with code adding 10 mil int values to an ArrayList vs List<T>: enter image description here

That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).

Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity: enter image description here

I’ve written a detailed analysis of what goes on with the above ArrayList scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.

Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):

[…] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.

00:00:01.6246959 (GCs= 6) List<Int32>
00:00:10.8555008 (GCs=390) ArrayList of Int32
00:00:02.5427847 (GCs= 4) List<String>
00:00:02.7944831 (GCs= 7) ArrayList of String

The output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.

What is the difference between __init__ and __call__?

So, __init__ is called when you are creating an instance of any class and initializing the instance variable also.

Example:

class User:

    def __init__(self,first_n,last_n,age):
        self.first_n = first_n
        self.last_n = last_n
        self.age = age

user1 = User("Jhone","Wrick","40")

And __call__ is called when you call the object like any other function.

Example:

class USER:
    def __call__(self,arg):
        "todo here"
         print(f"I am in __call__ with arg : {arg} ")


user1=USER()
user1("One") #calling the object user1 and that's gonna call __call__ dunder functions

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

What are all possible pos tags of NLTK?

You can download the list here: ftp://ftp.cis.upenn.edu/pub/treebank/doc/tagguide.ps.gz. It includes confusing parts of speech, capitalization, and other conventions. Also, wikipedia has an interesting section similar to this. Section: Part-of-speech tags used.

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in

ngOnInt(){

    userForm = new FormGroup({
        name: new FormControl(),
        email: new FormControl(),
        adresse: new FormGroup({
            rue: new FormControl(),
            ville: new FormControl(),
            cp: new FormControl(),
        })
     });
)

Java creating .jar file

Often you need to put more into the manifest than what you get with the -e switch, and in that case, the syntax is:

jar -cvfm myJar.jar myManifest.txt myApp.class

Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include.

Note that the name of the manifest file you supply can be anything, as jar will automatically rename it and put it into the right place within the jar file.

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

How can I strip first and last double quotes?

If you are sure there is a " at the beginning and at the end, which you want to remove, just do:

string = string[1:len(string)-1]

or

string = string[1:-1]

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

Get list of certificates from the certificate store in C#

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

foreach (X509Certificate2 certificate in store.Certificates){
    //TODO's
}

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

Running PHP script from the command line

UPDATE:

After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?

Look for lines that start with LoadModule php... There probably are configuration files/directories named mods or something like that, start from there.

You could also check output from php -r 'phpinfo();' | grep php and compare lines to phpinfo(); from web server.

To run php interactively:

(so you can paste/write code in the console)

php -a

To make it parse file and output to console:

php -f file.php

Parse file and output to another file:

php -f file.php > results.html

Do you need something else?

To run only small part, one line or like, you can use:

php -r '$x = "Hello World"; echo "$x\n";'

If you are running linux then do man php at console.

if you need/want to run php through fpm, use cli fcgi

SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"

where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.

Android Webview - Webpage should fit the device screen

Friends,

I found a lot of import and great informations from you. But, the only way works for me was this way:

webView = (WebView) findViewById(R.id.noticiasWebView);
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.loadUrl("http://www.resource.com.br/");

I am working on Android 2.1 because of the kind of devices from the company. But I fixed my problem using the part of informations from each one.

Thanks you!

Invoke-customs are only supported starting with android 0 --min-api 26

If you have Java 7 so include the below following snippet within your app-level build.gradle :

compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

}

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

As described in the API of java.sql.PreparedStatement.setBinaryStream() it is available since 1.6 so it is a JDBC 4.0 API! You use a JDBC 3 Driver so this method is not available!

How to make function decorators and chain them together?

Here is a simple example of chaining decorators. Note the last line - it shows what is going on under the covers.

############################################################
#
#    decorators
#
############################################################

def bold(fn):
    def decorate():
        # surround with bold tags before calling original function
        return "<b>" + fn() + "</b>"
    return decorate


def uk(fn):
    def decorate():
        # swap month and day
        fields = fn().split('/')
        date = fields[1] + "/" + fields[0] + "/" + fields[2]
        return date
    return decorate

import datetime
def getDate():
    now = datetime.datetime.now()
    return "%d/%d/%d" % (now.day, now.month, now.year)

@bold
def getBoldDate(): 
    return getDate()

@uk
def getUkDate():
    return getDate()

@bold
@uk
def getBoldUkDate():
    return getDate()


print getDate()
print getBoldDate()
print getUkDate()
print getBoldUkDate()
# what is happening under the covers
print bold(uk(getDate))()

The output looks like:

17/6/2013
<b>17/6/2013</b>
6/17/2013
<b>6/17/2013</b>
<b>6/17/2013</b>

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    System.out.println(employees);
    Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    System.out.println(format.format(maxDate));
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);

}

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();
}
}

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    System.out.println(format.format(maxDate));
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

Get path of executable

I'm not sure about Linux, but try this for Windows:

#include <windows.h>
#include <iostream>

using namespace std ;

int main()
{
     char ownPth[MAX_PATH]; 

     // When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
     HMODULE hModule = GetModuleHandle(NULL);
     if (hModule != NULL)
     {
         // Use GetModuleFileName() with module handle to get the path
         GetModuleFileName(hModule, ownPth, (sizeof(ownPth))); 
         cout << ownPth << endl ;
         system("PAUSE");
         return 0;
     }
     else
     {
         cout << "Module handle is NULL" << endl ;
         system("PAUSE");
         return 0;
     }
}

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have used in my many projects and never got any single issue :)

for your reference, Code are in snippet

_x000D_
_x000D_
* {_x000D_
 margin: 0;_x000D_
}_x000D_
html, body {_x000D_
 height: 100%;_x000D_
}_x000D_
.wrapper {_x000D_
 min-height: 100%;_x000D_
 height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */_x000D_
 height: 100%;_x000D_
 margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */_x000D_
  background:green;_x000D_
}_x000D_
.footer, .push {_x000D_
 height: 50px; /* .push must be the same height as .footer */_x000D_
}_x000D_
_x000D_
.footer{_x000D_
  background:gold;_x000D_
  }
_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="wrapper">_x000D_
    Content Area_x000D_
    </div>_x000D_
  _x000D_
  <div class="push">_x000D_
    </div>_x000D_
  _x000D_
  <div class="footer">_x000D_
    Footer Area_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

How do I convert a pandas Series or index to a Numpy array?

You can use df.index to access the index object and then get the values in a list using df.index.tolist(). Similarly, you can use df['col'].tolist() for Series.

Android Button setOnClickListener Design

Implement OnClickListener() on your Activity...

public class MyActivity extends Activity implements View.OnClickListener {
}

For each button use...

buttonX.setOnClickListener(this);

In your Activity onClick() method test for which button it is...

@Override
public void onClick(View view) {
    if (View.equals(buttonX))
        // Do something
}

Also in onClick you could use view.getId() to get the resource ID and then use that in a switch/case block to identify each button and perform the relevant action.

How to add rows dynamically into table layout

Solution 1. Set your TableLayout tl as class member variable, only call TableLayout tl=(TableLayout)findViewById(R.id.maintable); when you initiate the class. When button clicked use tl directly, eg. tl.addView(row), don't call FindViewById anymore. So the next new row wouldn't replace the previous new row.

Solution 2. Everytime after button click save your updated data into an array, and then re-render your whole table layout by loop through the array.

How to get Activity's content view?

There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

If content view was already set, requestWindowFeature will throw an exception.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

I have changed in my activity but effected. Here is my code:

View layout = getLayoutInflater().inflate(R.layout.list_group,null);
        try {
            LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.ldrawernav);
            linearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
        }
        catch (Exception e) {

        }

    }

Best Way to do Columns in HTML/CSS

You should probably consider using css3 for this though it does include the use of vendor prefixes.

I've knocked up a quick fiddle to demo but the crux is this.

<style>
.3col
{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count:3;
    column-gap:10px;
}
</style>
<div class="3col">
<p>col1</p>
<p>col2</p>
<p>col3</p>
</div>

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

What data type to use for money in Java?

BigDecimal can be used, good explanation of why to not use Float or Double can be seen here: Why not use Double or Float to represent currency?

Scala list concatenation, ::: vs ++

A different point is that the first sentence is parsed as:

scala> List(1,2,3).++(List(4,5))
res0: List[Int] = List(1, 2, 3, 4, 5)

Whereas the second example is parsed as:

scala> List(4,5).:::(List(1,2,3))
res1: List[Int] = List(1, 2, 3, 4, 5)

So if you are using macros, you should take care.

Besides, ++ for two lists is calling ::: but with more overhead because it is asking for an implicit value to have a builder from List to List. But microbenchmarks did not prove anything useful in that sense, I guess that the compiler optimizes such calls.

Micro-Benchmarks after warming up.

scala>def time(a: => Unit): Long = { val t = System.currentTimeMillis; a; System.currentTimeMillis - t}
scala>def average(a: () => Long) = (for(i<-1 to 100) yield a()).sum/100

scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ++ List(e) } })
res1: Long = 46
scala>average (() => time { (List[Int]() /: (1 to 1000)) { case (l, e) => l ::: List(e ) } })
res2: Long = 46

As Daniel C. Sobrai said, you can append the content of any collection to a list using ++, whereas with ::: you can only concatenate lists.

How to TryParse for Enum value?

There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.

Split function equivalent in T-SQL?

/* *Object:  UserDefinedFunction [dbo].[Split]    Script Date: 10/04/2013 18:18:38* */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Split]
(@List varchar(8000),@SplitOn Nvarchar(5))
RETURNS @RtnValue table
(Id int identity(1,1),Value nvarchar(100))
AS
BEGIN
    Set @List = Replace(@List,'''','')
    While (Charindex(@SplitOn,@List)>0)
    Begin

    Insert Into @RtnValue (value)
    Select
    Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))

    Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
    End

    Insert Into @RtnValue (Value)
    Select Value = ltrim(rtrim(@List))

    Return
END
go

Select *
From [Clv].[Split] ('1,2,3,3,3,3,',',')
GO

How do I convert a double into a string in C++?

The boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>

assign value using linq

using Linq would be:

 listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";

UPDATE

This can be simplified to be...

 listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";

UPDATE

For multiple items (condition is met by multiple items):

 listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

What is the volatile keyword useful for?

Assume that a thread modifies the value of a shared variable, if you didn't use volatile modifier for that variable. When other threads want to read this variable's value, they don't see the updated value because they read the variable's value from the CPU's cache instead of RAM memory. This problem also known as Visibility Problem.

By declaring the shared variable volatile, all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory.

public class SharedObject {
    public volatile int sharedVariable = 0;
}

With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads data from main memory into CPU caches, or writes data from CPU caches to main memory. This can cause several problems which I will explain in the following sections.


Example:

Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:

public class SharedObject {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory. This situation is illustrated here:

volatile

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called a "visibility" problem. The updates of one thread are not visible to other threads.

Efficient SQL test query or validation query that will work across all (or most) databases

Unfortunately there is no SELECT statement that will always work regardless of database.

Most databases support:

SELECT 1

Some databases don't support this but have a table called DUAL that you can use when you don't need a table:

SELECT 1 FROM DUAL

MySQL also supports this for compatibility reasons, but not all databases do. A workaround for databases that don't support either of the above is to create a table called DUAL that contains a single row, then the above will work.

HSQLDB supports neither of the above, so you can either create the DUAL table or else use:

SELECT 1 FROM any_table_that_you_know_exists_in_your_database

How to set JAVA_HOME in Linux for all users

This is a very simple script to solve the problem

export JAVA_HOME_BIN=`which java`
export JAVA_HOME_DIR=`dirname $JAVA_HOME_BIN`
export JAVA_HOME=`dirname $JAVA_HOME_DIR`

And for testing:

echo $JAVA_HOME

how to load CSS file into jsp

I had the same problem too. Then i realized that in the MainPageServlet the urlPatterns parameter in @WebServlet annotation contained "/", because i wanted to forward to the MainPage if the user entered the section www.site.com/ . When i tried to open the css file from the browser, the url was www.site.com/css/desktop.css, but the page content was THE PAGE MainPage.jsp. So, i removed the "/" urlPattern and now i can use CSS files in my jsp file using one of the most common solutions (${pageContext.request.contextPath}/css/desktop.css). Make sure your servlet doesn't contain the "/" urlPattern. I hope this worked for u too, - Axel Montini

IOError: [Errno 32] Broken pipe: Python

To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:

  • Standard Unix signal SIGPIPE is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).

    • This is not necessarily an error condition; some Unix utilities such as head by design stop reading prematurely from a pipe, once they've received enough data.
  • By default - i.e., if the writing process does not explicitly trap SIGPIPE - the writing process is simply terminated, and its exit code is set to 141, which is calculated as 128 (to signal termination by signal in general) + 13 (SIGPIPE's specific signal number).

  • By design, however, Python itself traps SIGPIPE and translates it into a Python IOError instance with errno value errno.EPIPE, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.

  • If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe and terminates the script with exit code 1 - this is the symptom the OP saw.

  • In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:

    • Using the signal module allows just that, as stated in akhan's answer; signal.signal() takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL represents the system's default behavior:

      from signal import signal, SIGPIPE, SIG_DFL
      signal(SIGPIPE, SIG_DFL) 
      

How do ACID and database transactions work?

[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.

I have written more about this in a blog post: "ACID Does Not Make Sense".

http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html

[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf

[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

Extract Google Drive zip from Google colab notebook

in my idea, you must go to a certain path for example:

from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/

then :

!apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here

Oracle JDBC ojdbc6 Jar as a Maven Dependency

Below config worked for me. Refer this link for more details.

<dependency>
 <groupId>com.oracle.jdbc</groupId>
 <artifactId>ojdbc7</artifactId>
 <version>12.1.0.2</version>
</dependency>

How to delete a stash created with git stash create?

You should be using

git stash save

and not

git stash create

because this creates a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. Hence won't be accessible with stash apply.

Use git stash save "some comment" is used when you have unstaged changes you wanna replicate/move onto another branch

Use git stash apply stash@{0} (assuming your saved stash index is 0) when you want your saved(stashed) changes to reflect on your current branch

you can always use git stash list to check all you stash indexes

and use git stash drop stash@{0} (assuming your saved stash index is 0 and you wanna delete it) to delete a particular stash.

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

You can also use as Vector instead, as vectors are thread safe and arraylist are not. Though vectors are old but they can solve your purpose easily.

But you can make your Arraylist synchronized like code given this:

Collections.synchronizedList(new ArrayList(numberOfRaceCars())); 

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

You can use:

Bulk collect along with FOR ALL that is called Bulk binding.

Because PL/SQL forall operator speeds 30x faster for simple table inserts.

BULK_COLLECT and Oracle FORALL together these two features are known as Bulk Binding. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT, UPDATE, and DELETE statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement instead of using INTO.

It improves performance.

Open popup and refresh parent page on close popup

You can reach main page with parent command (parent is the window) after the step you can make everything...

    function funcx() {
        var result = confirm('bla bla bla.!');
        if(result)
            //parent.location.assign("http://localhost:58250/Ekocc/" + document.getElementById('hdnLink').value + "");
            parent.location.assign("http://blabla.com/" + document.getElementById('hdnLink').value + "");
    } 

How can I configure Logback to log different levels for a logger to different destinations?

I believe this would be the simplest solution:

<configuration>
    <contextName>selenium-plugin</contextName>
    <!-- Logging configuration -->  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <Target>System.out</Target>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder>
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
            <Target>System.err</Target>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <encoder> 
            <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] [%thread] %logger{10} [%file:%line] %msg%n</pattern> 
        </encoder> 
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="STDERR" />
    </root>
</configuration>

How to determine when Fragment becomes visible in ViewPager

I encountered this problem when I was trying to get a timer to fire when the fragment in the viewpager was on-screen for the user to see.

The timer always started just before the fragment was seen by the user. This is because the onResume() method in the fragment is called before we can see the fragment.

My solution was to do a check in the onResume() method. I wanted to call a certain method 'foo()' when fragment 8 was the view pagers current fragment.

@Override
public void onResume() {
    super.onResume();
    if(viewPager.getCurrentItem() == 8){
        foo();
        //Your code here. Executed when fragment is seen by user.
    }
}

Hope this helps. I've seen this problem pop up a lot. This seems to be the simplest solution I've seen. A lot of others are not compatible with lower APIs etc.

How do I remove objects from an array in Java?

In an array of Strings like

String name = 'a b c d e a f b d e' // could be like String name = 'aa bb c d e aa f bb d e'

I build the following class

class clearname{
def parts
def tv
public def str = ''
String name
clearname(String name){
    this.name = name
    this.parts = this.name.split(" ")
    this.tv = this.parts.size()
}
public String cleared(){

        int i
        int k
        int j=0        
    for(i=0;i<tv;i++){
        for(k=0;k<tv;k++){
            if(this.parts[k] == this.parts[i] && k!=i){
               this.parts[k] = '';
                j++
            }
        }
    }
    def str = ''
    for(i=0;i<tv;i++){
        if(this.parts[i]!='')

           this.str += this.parts[i].trim()+' '
    } 
    return this.str    
}}



return new clearname(name).cleared()

getting this result

a b c d e f

hope this code help anyone Regards

merge one local branch into another local branch

Just in case you arrived here because you copied a branch name from Github, note that a remote branch is not automatically also a local branch, so a merge will not work and give the "not something we can merge" error.

In that case, you have two options:

git checkout [branchYouWantToMergeInto]
git merge origin/[branchYouWantToMerge]

or

# this creates a local branch
git checkout [branchYouWantToMerge]

git checkout [branchYouWantToMergeInto]
git merge [branchYouWantToMerge]

Using sed, how do you print the first 'N' characters of a line?

How about head ?

echo alonglineoftext | head -c 9

What is the difference between varchar and varchar2 in Oracle?

Currently, they are the same. but previously

  1. Somewhere on the net, I read that,

VARCHAR is reserved by Oracle to support distinction between NULL and empty string in future, as ANSI standard prescribes.

VARCHAR2 does not distinguish between a NULL and empty string, and never will.

  1. Also,

Emp_name varchar(10) - if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.

Emp_name varchar2(10) - if you enter value less than 10 digits then remaining space is automatically deleted

Oracle PL Sql Developer cannot find my tnsnames.ora file

Which Oracle client are you using?

Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You should change the

<a href="#">My Link</a>

to

<a href="javascript:;">My Link</a>

This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.

I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();

How to randomize Excel rows

Use Excel Online (Google Sheets).. And install Power Tools for Google Sheets.. Then in Google Sheets go to Addons tab and start Power Tools. Then choose Randomize from Power Tools menu. Select Shuffle. Then select choices of your test in excel sheet. Then select Cells in each row and click Shuffle from Power Tools menu. This will shuffle each row's selected cells independently from one another.

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

Session 'app': Error Installing APK

Ensure you android device has enough memory to install the app. Sometimes it so happens working with multimedia app where the device storage keeps on increasing and you keep wondering about the error.

Therefore, free up some memory and try installing again!

Where do I find the definition of size_t?

I'm not familiar with void_t except as a result of a Google search (it's used in a vmalloc library by Kiem-Phong Vo at AT&T Research - I'm sure it's used in other libraries as well).

The various xxx_t typedefs are used to abstract a type from a particular definite implementation, since the concrete types used for certain things might differ from one platform to another. For example:

  • size_t abstracts the type used to hold the size of objects because on some systems this will be a 32-bit value, on others it might be 16-bit or 64-bit.
  • Void_t abstracts the type of pointer returned by the vmalloc library routines because it was written to work on systems that pre-date ANSI/ISO C where the void keyword might not exist. At least that's what I'd guess.
  • wchar_t abstracts the type used for wide characters since on some systems it will be a 16 bit type, on others it will be a 32 bit type.

So if you write your wide character handling code to use the wchar_t type instead of, say unsigned short, that code will presumably be more portable to various platforms.

What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte?

To answer you first question:
Yes, it means that 1 byte allocates for 1 character. Look at this example

SQL> conn / as sysdba
Connected.
SQL> create table test (id number(10), v_char varchar2(10));

Table created.

SQL> insert into test values(11111111111,'darshan');
insert into test values(11111111111,'darshan')
*
ERROR at line 1:
ORA-01438: value larger than specified precision allows for this column


SQL> insert into test values(11111,'darshandarsh');
insert into test values(11111,'darshandarsh')
*
ERROR at line 1:
ORA-12899: value too large for column "SYS"."TEST"."V_CHAR" (actual: 12,
maximum: 10)


SQL> insert into test values(111,'Darshan');

1 row created.

SQL> 

And to answer your next one: The difference between varchar2 and varchar :

  1. VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000 bytes of characters.
  2. If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of VARCHAR2 datatype it will not occupy any space.

How to run crontab job every week on Sunday

The crontab website gives the real time results display: https://crontab.guru/#5_8_*_*_0

enter image description here

Convert xlsx file to csv using batch

Alternative way of converting to csv. Use libreoffice:

libreoffice --headless --convert-to csv *

Please be aware that this will only convert the first worksheet of your Excel file.

Convert string to int if string is a number

Just use Val():

currentLoad = Int(Val([f4]))

Now currentLoad has a integer value, zero if [f4] is not numeric.

Getting data-* attribute for onclick event for an html element

You can achieve this $(identifier).data('id') using jquery,

    <script type="text/javascript">

        function goDoSomething(identifier){     
            alert("data-id:"+$(identifier).data('id')+", data-option:"+$(identifier).data('option'));               
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

javascript : You can use getAttribute("attributename") if want to use javascript tag,

    <script type="text/javascript">

        function goDoSomething(d){
            alert(d.getAttribute("data-id"));
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this);">
           Click to do something
    </a>

Or:

    <script type="text/javascript">

        function goDoSomething(data_id, data_option){       

            alert("data-id:"+data_id+", data-option:"+data_option);
        }

    </script>

    <a id="option1" 
       data-id="10" 
       data-option="21" 
       href="#" 
       onclick="goDoSomething(this.getAttribute('data-id'), this.getAttribute('data-option'));">
           Click to do something
    </a>

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

CMD: Export all the screen content to a text file

If you want to append a file instead of constantly making a new one/deleting the old one's content, use double > marks. A single > mark will overwrite all the file's content.

Overwrite file

MyCommand.exe>file.txt

^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output

Append file from its end-point

MyCommand.exe>>file.txt

^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.


Update #1 (advanced):

My batch-fu has improved over time, so here's some minor updates.

If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT/STDERR, you can do this with minor changes to the syntax. I'll just use > for overwriting for these examples, but they work perfectly fine with >> for append, in regards to file-piping output re-direction.

The 1 before the >> or > is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2 before the re-direction symbols is for STDERR.

Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul. Now, outputting to nul works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.

STDERR to file and suppress STDOUT

MyCommand.exe 1>nul 2>errors.txt

STDERR to file to only log errors. Will keep STDOUT in console

MyCommand.exe 2>errors.txt

STDOUT to file and suppress STDERR

MyCommand.exe 1>file.txt 2>nul

STDOUT only to file. Will keep STDERR in console

MyCommand.exe 1>file.txt

STDOUT to one file and STDERR to another file

MyCommand.exe 1>stdout.txt 2>errors.txt

The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.

Update #2

I started noticing weird behavior when writing console apps that wrote directly to STDERR, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1 and 2 or just use STDOUT. The problem with that problem is I didn't know about the correct way to combine streams, which is this:

%command% > outputfile 2>&1

Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:

MyCommand.exe > file.txt 2>&1

The redirector actually defaults to 1> or 1>>, even if you don't explicitly use 1 in front of it if you don't use a number in front of it, and the 2>&1 combines the streams.

Update #3 (simple)

Null for Everything

If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.

STD* to null MyCommand.exe>nul 2>&1

Copying a CMD or Powershell session's command output

If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.

Node - how to run app.js?

To run app.js file check "main": "app.js" in your package.json file.

Then run command $ node app.js That should run your app and check.

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

Counting the number of option tags in a select tag in jQuery

$('#input1 option').length;

This will produce 2.

Freezing Row 1 and Column A at the same time

Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.

For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".

Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html

Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx

What does this thread join code mean?

Hope it helps!

package join;

public class ThreadJoinApp {

    Thread th = new Thread("Thread 1") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());
            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    Thread th2 = new Thread("Thread 2") {
        public void run() {
            System.out.println("Current thread execution - " + Thread.currentThread().getName());

            //Thread 2 waits until the thread 1 successfully completes.
            try {
            th.join();
            } catch( InterruptedException ex) {
                System.out.println("Exception has been caught");
            }

            for (int i = 0; i < 10; i++) {
                System.out.println("Current thread execution - " + Thread.currentThread().getName() + " at index - " + i);
            }
        }
    };

    public static void main(String[] args) {
        ThreadJoinApp threadJoinApp = new ThreadJoinApp();
        threadJoinApp.th.start();
        threadJoinApp.th2.start();
    }

    //Happy coding -- Parthasarathy S
}

How to handle the click event in Listview in android?

According to my test,

  1. implements OnItemClickListener -> works.

  2. setOnItemClickListener -> works.

  3. ListView is clickable by default (API 19)

The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".

Create File If File Does Not Exist

This works as well for me

string path = TextFile + ".txt";

if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
    File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
    w.WriteLine("{0}", "Hello World");
    w.Flush();
    w.Close();
}

How can I convert a dictionary into a list of tuples?

since no one else did, I'll add py3k versions:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

C Linking Error: undefined reference to 'main'

You are overwriting your object file runexp.o by running this command :

 gcc -o runexp.o scd.o data_proc.o -lm -fopenmp

In fact, the -o is for the output file. You need to run :

gcc -o runexp.out runexp.o scd.o data_proc.o -lm -fopenmp

runexp.out will be you binary file.

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

Changing the highlight color when selecting text in an HTML text input

Try this code to use:

/* For Mozile Firefox Browser */

::-moz-selection { background-color: #4CAF50; }

/* For Other Browser*/
::selection { background-color: #4CAF50; }

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to

private SSLSocketFactory delegate;

This is my TLSSocketFactory class

public class TLSSocketFactory extends SSLSocketFactory {

private SSLSocketFactory delegate;

public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    delegate = context.getSocketFactory();
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket() throws IOException {
    return enableTLSOnSocket(delegate.createSocket());
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket enableTLSOnSocket(Socket socket) {
    if(socket != null && (socket instanceof SSLSocket)) {
        ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
    }
    return socket;
}
}

and this is how i used it with okhttp and retrofit

 OkHttpClient client=new OkHttpClient();
    try {
        client = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .build();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Selecting with complex criteria from pandas.DataFrame

You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)

df[['A']][df.B.gt(50) & df.C.ne(900)]

df[['A']] will give you back column A in DataFrame format.

pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

How to use jQuery with Angular?

//installing jquerynpm install jquery --save

//installing type defintion for the jquerytypings install dt~jquery --global --save

//adding jquery library into build configuration file as specified(in "angular-cli-build.js" file)

vendorNpmFiles: [
  .........
  .........
  'jquery/dist/jquery.min.js'
]

//run the build to add the jquery library in the build ng build

//adding the relative path configuration(in system-config.js) /** Map relative paths to URLs. */ const map: any = { ....., ......., 'jquery': 'vendor/jquery/dist' };

/** User packages configuration. */
const packages: any = {
......,
'jquery':{ main: 'jquery.min',
format: 'global',
defaultExtension: 'js'}};

//import the jquery library in your component file

import 'jquery';

below is the code snipppet of my sample component

import { Component } from '@angular/core';
import 'jquery';
@Component({
  moduleId: module.id,
  selector: 'app-root',
  templateUrl: 'app.component.html',  
  styleUrls: ['app.component.css']
})
export class AppComponent {
  list:Array<number> = [90,98,56,90];
  title = 'app works!';
  isNumber:boolean = jQuery.isNumeric(89)  
  constructor(){}
}

Using Alert in Response.Write Function in ASP.NET

Try using RegisterScriptBlock. Example from the link:

public void Page_Load(Object sender, EventArgs e)
{
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
}

Declaring variables inside loops, good practice or bad practice?

Once upon a time (pre C++98); the following would break:

{
    for (int i=0; i<.; ++i) {std::string foo;}
    for (int i=0; i<.; ++i) {std::string foo;}
}

with the warning that i was already declared (foo was fine as that's scoped within the {}). This is likely the WHY people would first argue it's bad. It stopped being true a long time ago though.

If you STILL have to support such an old compiler (some people are on Borland) then the answer is yes, a case could be made to put the i out the loop, because not doing so makes it makes it "harder" for people to put multiple loops in with the same variable, though honestly the compiler will still fail, which is all you want if there's going to be a problem.

If you no longer have to support such an old compiler, variables should be kept to the smallest scope you can get them so that you not only minimise the memory usage; but also make understanding the project easier. It's a bit like asking why don't you have all your variables global. Same argument applies, but the scopes just change a bit.

How do I find the duplicates in a list and create another list with them?

A bit late, but maybe helpful for some. For a largish list, I found this worked for me.

l=[1,2,3,5,4,1,3,1]
s=set(l)
d=[]
for x in l:
    if x in s:
        s.remove(x)
    else:
        d.append(x)
d
[1,3,1]

Shows just and all duplicates and preserves order.

Which data type for latitude and longitude?

Use Point data type to store Longitude and Latitude in a single column:

CREATE TABLE table_name (
    id integer NOT NULL,
    name text NOT NULL,
    location point NOT NULL,
    created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT table_name_pkey PRIMARY KEY (id)
)

Create an Indexing on a 'location' column :

CREATE INDEX ON table_name USING GIST(location);

GiST index is capable of optimizing “nearest-neighbor” search :

SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;

Note: The point first element is longitude and the second element is latitude.

For more info check this Query Operators.

Secondary axis with twinx(): how to add to legend?

A quick hack that may suit your needs..

Take off the frame of the box and manually position the two legends next to each other. Something like this..

ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)

Where the loc tuple is left-to-right and bottom-to-top percentages that represent the location in the chart.

Ordering by specific field value first

Generally you can do

select * from your_table
order by case when name = 'core' then 1 else 2 end,
         priority 

Especially in MySQL you can also do

select * from your_table
order by name <> 'core',
         priority 

Since the result of a comparision in MySQL is either 0 or 1 and you can sort by that result.

Change old commit message on Git

If you don't want to deal with interactive mode then do this:

Update your last pushed commit

git commit --amend -m "New commit message."

Push your new commit message (this will replace the old last commit message to this new one)

git push origin --force **branch-name**

More on this - https://linuxize.com/post/change-git-commit-message/

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>teste4</groupId>
    <artifactId>teste4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>prime-repo</id>
            <name>PrimeFaces Maven Repository</name>
            <url>http://repository.primefaces.org</url>
            <layout>default</layout>
        </repository>
    </repositories>



    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.4</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.4</version>
        </dependency>



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>4.0</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.7.Final</version>
        </dependency>

    </dependencies>


</project>

jQuery change method on input type="file"

I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange="" attribute to the input tag:

<input type='file' onchange='getFilename(this)'/>

function getFileName(elm) {
   var fn = $(elm).val();
   ....
}

EDIT:

function getFileName(elm) {
   var fn = $(elm).val();
   var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
   alert(filename);
}

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

Use LINQ to get items in one List<>, that are not in another List<>

Once you write a generic FuncEqualityComparer you can use it everywhere.

peopleList2.Except(peopleList1, new FuncEqualityComparer<Person>((p, q) => p.ID == q.ID));

public class FuncEqualityComparer<T> : IEqualityComparer<T>
{
    private readonly Func<T, T, bool> comparer;
    private readonly Func<T, int> hash;

    public FuncEqualityComparer(Func<T, T, bool> comparer)
    {
        this.comparer = comparer;
        if (typeof(T).GetMethod(nameof(object.GetHashCode)).DeclaringType == typeof(object))
            hash = (_) => 0;
        else
            hash = t => t.GetHashCode(); 
    }

    public bool Equals(T x, T y) => comparer(x, y);
    public int GetHashCode(T obj) => hash(obj);
}

How to query between two dates using Laravel and Eloquent?

Another option if your field is datetime instead of date (although it works for both cases):

$fromDate = "2016-10-01";
$toDate   = "2016-10-31";

$reservations = Reservation::whereRaw(
  "(reservation_from >= ? AND reservation_from <= ?)", 
  [$fromDate." 00:00:00", $toDate." 23:59:59"]
)->get();

How to change MySQL timezone in a database connection using Java?

JDBC uses a so-called "connection URL", so you can escape "+" by "%2B", that is

useTimezone=true&serverTimezone=GMT%2B8

Neither BindingResult nor plain target object for bean name available as request attr

We faced the same issue and changed commandname="" to modelAttribute="" in jsp page to solve this issue.

Windows batch command(s) to read first line from text file

Here is a workaround using powershell:

powershell (Get-Content file.txt)[0]

(You can easily read also a range of lines with powershell (Get-Content file.txt)[0..3])

If you need to set a variable inside a batch script as the first line of file.txt you may use:

for /f "usebackq delims=" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set "head=%%a")

Div Scrollbar - Any way to style it?

No, you can't in Firefox, Safari, etc. You can in Internet Explorer. There are several scripts out there that will allow you to make a scroll bar.

How to get a list of images on docker registry v2

Since each registry runs as a container the container ID has an associated log file ID-json.log this log file contains the vars.name=[image] and vars.reference=[tag]. A script can be used to extrapolate and print these. This is perhaps one method to list images pushed to registry V2-2.0.1.

Select Multiple Fields from List in Linq

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How to list files in an android directory?

Try these

 String appDirectoryName = getResources().getString(R.string.app_name);
    File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
    directory.mkdirs();
    File[] fList = directory.listFiles();
    int a = 1;
    for (int x = 0; x < fList.length; x++) {

        //txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
        a++;
    }
    //get all the files from a directory
    for (File file : fList) {
        if (file.isFile()) {
            list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
        }
    }

Replace one character with another in Bash

Try this

 echo "hello world" | sed 's/ /./g' 

How is a CRC32 checksum calculated?

In order to reduce crc32 to taking the reminder you need to:

  1. Invert bits on each byte
  2. xor first four bytes with 0xFF (this is to avoid errors on the leading 0s)
  3. Add padding at the end (this is to make the last 4 bytes take part in the hash)
  4. Compute the reminder
  5. Reverse the bits again
  6. xor the result again.

In code this is:


func CRC32 (file []byte) uint32 {
    for i , v := range(file) {
        file[i] = bits.Reverse8(v)
    }
    for i := 0; i < 4; i++ {
        file[i] ^= 0xFF
    }

    // Add padding
    file = append(file, []byte{0, 0, 0, 0}...)
    newReminder := bits.Reverse32(reminderIEEE(file))

    return newReminder ^ 0xFFFFFFFF
}

where reminderIEEE is the pure reminder on GF(2)[x]

What is Java EE?

I would say that J2EE experience = in-depth experience with a few J2EE technologies, general knowledge about most J2EE technologies, and general experience with enterprise software in general.

Seeing the console's output in Visual Studio 2010?

I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:

Click View ? Output (or just hold Ctrl and hit W > O)

Console output then appears where your Error List, Locals, and Watch windows are.

Note: I'm using Visual Studio 2015.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

How to delete all the rows in a table using Eloquent?

The best way for accomplishing this operation in Laravel 3 seems to be the use of the Fluent interface to truncate the table as shown below

DB::query("TRUNCATE TABLE mytable");

What is *.o file?

Ink-Jet is right. More specifically, an .o (.obj) -- or object file is a single source file compiled in to machine code (I'm not sure if the "machine code" is the same or similar to an executable machine code). Ultimately, it's an intermediate between an executable program and plain-text source file.

The linker uses the o files to assemble the file executable.

Wikipedia may have more detailed information. I'm not sure how much info you'd like or need.

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.

Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository". I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.

After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.

1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear

2) Followed github's instructions here to generate a new key pair and upload the public key to git

3) using git bash- heroku keys:add to upload the same key to heroku.

Now git push heroku master works.

what a nightmare, hope this helped somebody.

Bryan

jQuery - multiple $(document).ready ...?

Both will get called, first come first served. Take a look here.

$(document).ready(function(){
    $("#page-title").html("Document-ready was called!");
  });

$(document).ready(function(){
    $("#page-title").html("Document-ready 2 was called!");
  });

Output:

Document-ready 2 was called!

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

First, go to that folder which is containing pycharm.sh and open terminal from there. Then type

./pycharm.sh

this will open pycharm.

bin folder contains pycharm.sh file.

How to change visibility of layout programmatically

Use this Layout in your xml file

<LinearLayout
  android:id="@+id/contacts_type"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:visibility="gone">
</LinearLayout>

Define your layout in .class file

 LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);

Now if you want to display this layout just write

 linearLayout.setVisibility(View.VISIBLE);

and if you want to hide layout just write

 linearLayout.setVisibility(View.INVISIBLE);

Two dimensional array in python

the above method did not work for me for a for loop, where I wanted to transfer data from a 2D array to a new array under an if the condition. This method would work

a_2d_list = [[1, 2], [3, 4]]
a_2d_list.append([5, 6])
print(a_2d_list)

OUTPUT - [[1, 2], [3, 4], [5, 6]]

Is it possible to install both 32bit and 64bit Java on Windows 7?

To install 32-bit Java on Windows 7 (64-bit OS + Machine). You can do:

1) Download JDK: http://javadl.sun.com/webapps/download/AutoDL?BundleId=58124
2) Download JRE: http://www.java.com/en/download/installed.jsp?jre_version=1.6.0_22&vendor=Sun+Microsystems+Inc.&os=Linux&os_version=2.6.41.4-1.fc15.i686

3) System variable create: C:\program files (x86)\java\jre6\bin\

4) Anywhere you type java -version

it use 32-bit on (64-bit). I have to use this because lots of third party libraries do not work with 64-bit. Java wake up from the hell, give us peach :P. Go-language is killer.

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

Select SQL Server database size

Worked perfectly for me to calculate SQL database size in SQL Server 2012

exec sp_spaceused

enter image description here

How to pass the button value into my onclick event function?

You can do like this.

<input type="button" value="mybutton1" onclick="dosomething(this)">

function dosomething(element){
    alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};

How to generate a create table script for an existing table in phpmyadmin?

Use the following query in sql tab:

SHOW CREATE TABLE tablename

To view full query There is this Hyperlink named +Options left above, There select Full Texts

How can I make git show a list of the files that are being tracked?

If you want to list all the files currently being tracked under the branch master, you could use this command:

git ls-tree -r master --name-only

If you want a list of files that ever existed (i.e. including deleted files):

git log --pretty=format: --name-only --diff-filter=A | sort - | sed '/^$/d'

How can I use jQuery in Greasemonkey?

You can create a new script using the New User Script in Greasemonkey but you have to edit the config.xml file inside the gm_scripts folder.

Your config.xml file should have a similar syntax as this:

<Script filename="jquery_test.user.js" name="jQuery Test" namespace="http://www.example.com/jQueryPlay/" description="Just a test" enabled="true" basedir="jquery_test">
        <Include>http://*</Include>
        <Require filename="jquery.js"/>
</Script>

Notice the <Require> tag.

In your script you can use direct jQuery syntax. Make sure you have the require tag in the Greasemonkey header. Here is a Hello World example:

// ==UserScript==
// @name           Test jQuery
// @namespace      http://www.example.com/jQueryPlay/
// @description    Just a test
// @include        http://*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// ==/UserScript==

$(document).ready(function() {  
        alert("Hello world!");
});

Remember that after modifying the config.xml you have to restart your browser for Greasemonkey to reload the settings again.

Also note that you need to copy the jquery.js file to your script directory folder in order for this to work. I tested this, and it only works if you actually copy the file manually there.

Happy jQuerying!

How to update an "array of objects" with Firestore?

Here is the latest example from the Firestore documentation:

firebase.firestore.FieldValue.ArrayUnion

var washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});

Custom Input[type="submit"] style not working with jquerymobile button

I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important property.

HTML

<a href="#" class="selected_btn" data-role="button">Button name</a>

CSS

.selected_btn
{
    border:1px solid red;
    text-decoration:none;
    font-family:helvetica;
    color:red !important;            
    background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}

Here is the demo

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

Measuring function execution time in R

The built-in function system.time() will do it.

Use like: system.time(result <- myfunction(with, arguments))

Delete keychain items when an app is uninstalled

This seems to be the default behavior on iOS 10.3 based on behavior people have been witnessing in beta #2. Haven't found any official documentation about this yet so please comment if you have.

Counting the occurrences / frequency of array elements

You can use an object to hold the results:

_x000D_
_x000D_
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];_x000D_
var counts = {};_x000D_
_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
  var num = arr[i];_x000D_
  counts[num] = counts[num] ? counts[num] + 1 : 1;_x000D_
}_x000D_
_x000D_
console.log(counts[5], counts[2], counts[9], counts[4]);
_x000D_
_x000D_
_x000D_

So, now your counts object can tell you what the count is for a particular number:

console.log(counts[5]); // logs '3'

If you want to get an array of members, just use the keys() functions

keys(counts); // returns ["5", "2", "9", "4"]

Node.js global proxy setting

replace {userid} and {password} with your id and password in your organization or login to your machine.

npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false

How do I get the different parts of a Flask request's url?

If you are using Python, I would suggest by exploring the request object:

dir(request)

Since the object support the method dict:

request.__dict__

It can be printed or saved. I use it to log 404 codes in Flask:

@app.errorhandler(404)
def not_found(e):
    with open("./404.csv", "a") as f:
        f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
    return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How can I get argv[] as int?

You can use the function int atoi (const char * str);.
You need to include #include <stdlib.h> and use the function in this way:
int x = atoi(argv[1]);
Here more information if needed: atoi - C++ Reference

String comparison - Android

try this.

        String g1 = "Male";
        String g2 = "Female";
        String gender = "Male";
        String salutation = "";
        if (gender.equalsIgnoreCase(g1))

            salutation = "Mr.";
        else if (gender.equalsIgnoreCase(g2))

            salutation = "Ms.";
        System.out.println("Welcome " + salutation);

Output:

Welcome Mr.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Adam Luter gave me the idea for this, but it actually turned out to be really simple:

img {
  width:  75px;
  height: auto;
}

IE6 now scales the image fine and this seems to be what all the other browsers use by default.

Thanks for both the answers though!

SQL Server: Difference between PARTITION BY and GROUP BY

Suppose we have 14 records of name column in table

in group by

select name,count(*) as totalcount from person where name='Please fill out' group BY name;

it will give count in single row i.e 14

but in partition by

select row_number() over (partition by name) as total from person where name = 'Please fill out';

it will 14 rows of increase in count

How do I convert datetime.timedelta to minutes, hours in Python?

Just use strftime :)

Something like that:

my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
print(my_date.strftime("%Y, %d %B"))

After edited your question to format timedelta, you could use:

def timedelta_tuple(timedelta_object):
   return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60

how to change the default positioning of modal in bootstrap?

I get a better result setting this class:

.modal-dialog {
  position: absolute;
  top: 50px;
  right: 100px;
  bottom: 0;
  left: 0;
  z-index: 10040;
  overflow: auto;
  overflow-y: auto;
}

With bootstrap 3.3.7.

(all credits to msnfreaky for the idea...)

Setting Windows PATH for Postgres tools

Incase any one still wondering how to add environment variables then please use this link to add variables. Link: https://sqlbackupandftp.com/blog/setting-windows-path-for-postgres-tools

Bash syntax error: unexpected end of file

I just cut-and-pasted your example into a file; it ran fine under bash. I don't see any problems with it.

For good measure you may want to ensure it ends with a newline, though bash shouldn't care. (It runs for me both with and without the final newline.)

You'll sometimes see strange errors if you've accidentally embedded a control character in the file. Since it's a short script, try creating a new script by pasting it from your question here on StackOverflow, or by simply re-typing it.

What version of bash are you using? (bash --version)

Good luck!

Add space between two particular <td>s

td:nth-of-type(n) { padding-right: 10px;}

it will adjust auto space between all td

use mysql SUM() in a WHERE clause

Not tested, but I think this will be close?

SELECT m1.id
FROM mytable m1
INNER JOIN mytable m2 ON m1.id < m2.id
GROUP BY m1.id
HAVING SUM(m1.cash) > 500
ORDER BY m1.id
LIMIT 1,2

The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.

How do you perform address validation?

USPS has an address cleaner online, which someone has screen scraped into a poor man's webservice. However, if you're doing this often enough, it'd be a better idea to apply for a USPS account and call their own webservice.

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

New to unit testing, how to write great tests?

Don't write tests to get full coverage of your code. Write tests that guarantee your requirements. You may discover codepaths that are unnecessary. Conversely, if they are necessary, they are there to fulfill some kind of requirement; find it what it is and test the requirement (not the path).

Keep your tests small: one test per requirement.

Later, when you need to make a change (or write new code), try writing one test first. Just one. Then you'll have taken the first step in test-driven development.

Pandas get the most frequent values of a column

By using mode

df.name.mode()
Out[712]: 
0     alex
1    helen
dtype: object

How to re import an updated package while in Python Interpreter?

No matter how many times you import a module, you'll get the same copy of the module from sys.modules - which was loaded at first import mymodule

I am answering this late, as each of the above/previous answer has a bit of the answer, so I am attempting to sum it all up in a single answer.

Using built-in function:

For Python 2.x - Use the built-in reload(mymodule) function.

For Python 3.x - Use the imp.reload(mymodule).

For Python 3.4 - In Python 3.4 imp has been deprecated in favor of importlib i.e. importlib.reload(mymodule)

Few caveats:

  • It is generally not very useful to reload built-in or dynamically loaded modules. Reloading sys, __main__, builtins and other key modules is not recommended.
  • In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded. If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.
  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

External packages:

reimport - Reimport currently supports Python 2.4 through 2.7.

xreload- This works by executing the module in a scratch namespace, and then patching classes, methods and functions in place. This avoids the need to patch instances. New objects are copied into the target namespace.

livecoding - Code reloading allows a running application to change its behaviour in response to changes in the Python scripts it uses. When the library detects a Python script has been modified, it reloads that script and replaces the objects it had previously made available for use with newly reloaded versions. As a tool, it allows a programmer to avoid interruption to their workflow and a corresponding loss of focus. It enables them to remain in a state of flow. Where previously they might have needed to restart the application in order to put changed code into effect, those changes can be applied immediately.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

In Android Studio 1.4 with buildToolsVersion '22.0.1' the approach of fvasquezc23 worked for me with a restart and cache invalidation.

So, after you change the location of your project folder – copy/paste the folder onto disk D: (or somewhere else with no big ‘folder in folder’ structure), just

  • go to “File” -> “Invalidate Caches/Restart” (below “Synchronize”)
  • select first option “Invalidate and Restart”

Android turn On/Off WiFi HotSpot programmatically

For Android 8.0, there is a new API to handle Hotspots. As far as I know, the old way using reflection doesn't work anymore. Please refer to:

Android Developers https://developer.android.com/reference/android/net/wifi/WifiManager.html#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)

void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback, 
                Handler handler)

Request a local only hotspot that an application can use to communicate between co-located devices connected to the created WiFi hotspot. The network created by this method will not have Internet access.

Stack Overflow
How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)

onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.

Least common multiple for 3 or more numbers

In R, we can use the functions mGCD(x) and mLCM(x) from the package numbers, to compute the greatest common divisor and least common multiple for all numbers in the integer vector x together:

    library(numbers)
    mGCD(c(4, 8, 12, 16, 20))
[1] 4
    mLCM(c(8,9,21))
[1] 504
    # Sequences
    mLCM(1:20)
[1] 232792560

Return Type for jdbcTemplate.queryForList(sql, object, classType)

In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.

See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.

In short, you'll need something like:

List<Conversation> actors = jdbcTemplate.query(
    SELECT_ALL_CONVERSATIONS_SQL_FULL,
    new Object[] {userId, dateFrom, dateTo},
    new RowMapper<Conversation>() {
        public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Conversation c = new Conversation();
            c.setId(rs.getLong(1));
            c.setRoom(rs.getString(2));
            [...]
            return c;
        }
    });

How do I force git to use LF instead of CR+LF under windows?

Context

If you

  1. want to force all users to have LF line endings for text files and
  2. you cannot ensure that all users change their git config,

you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.

Solution

Put a .gitattributes file in the root of your git repository having following contents:

* text=auto eol=lf

Commit it.

Optional tweaks

You can also add an .editorconfig in the root of your repository to ensure that modern tooling creates new files with the desired line endings.

# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

check if file exists on remote host with ssh

You're missing ;s. The general syntax if you put it all in one line would be:

if thing ; then ... ; else ... ; fi

The thing can be pretty much anything that returns an exit code. The then branch is taken if that thing returns 0, the else branch otherwise.

[ isn't syntax, it's the test program (check out ls /bin/[, it actually exists, man test for the docs – although can also have a built-in version with different/additional features.) which is used to test various common conditions on files and variables. (Note that [[ on the other hand is syntax and is handled by your shell, if it supports it).

For your case, you don't want to use test directly, you want to test something on the remote host. So try something like:

if ssh user@host test -e "$file" ; then ... ; else ... ; fi

Why am I getting a "401 Unauthorized" error in Maven?

If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847

The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.

ASP.NET Core 1.0 on IIS error 502.5

I had a similar issue, and to quote Sherlock Holmes: "when you have eliminated the impossible, whatever remains, however improbable, must be the truth?"

I checked if the .NET framework I was targeting was installed on the server, and it turns out it wasn't. I installed the 4.6.2 .NET Framework and it worked.

How to add bootstrap to an angular-cli project

Run this following command inside the project

npm install --save @bootsrap@4

and if you get a confirmation like this

+ [email protected]
updated 1 package in 8.245s

It means boostrap 4 is successfully installed. However, in order to use it, you need to update the "styles" array under the angular.json file.

Update it the following way so that bootstrap will be able to override the existing styles

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
           "src/styles.css"
          ],

To make sure everything is set up correctly, run ng serve > open browser at http://localhost:4200/ or a port you run the angular app > right click > inspect > under the head check the styles if you have bootsrap like shown below, then you are good to use boostrap. enter image description here

How to insert tab character when expandtab option is on in Vim

You can disable expandtab option from within Vim as below:

:set expandtab!

or

:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).

phpmailer error "Could not instantiate mail function"

If you are sending file attachments and your code works for small attachments but fails for large attachments:

If you get the error "Could not instantiate mail function" error when you try to send large emails and your PHP error log contains the message "Cannot send message: Too big" then your mail transfer agent (sendmail, postfix, exim, etc) is refusing to deliver these emails.

The solution is to configure the MTA to allow larger attachments. But this is not always possible. The alternate solution is to use SMTP. You will need access to a SMTP server (and login credentials if your SMTP server requires authentication):

$mail             = new PHPMailer();
$mail->IsSMTP();                           // telling the class to use SMTP
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "mail.yourdomain.com"; // set the SMTP server
$mail->Port       = 26;                    // set the SMTP port
$mail->Username   = "yourname@yourdomain"; // SMTP account username
$mail->Password   = "yourpassword";        // SMTP account password

PHPMailer defaults to using PHP mail() function which uses settings from php.ini which normally defaults to use sendmail (or something similar). In the above example we override the default behavior.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

For .Net <= 4.0 Use the TimeSpan class.

TimeSpan t = TimeSpan.FromSeconds( secs );

string answer = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", 
                t.Hours, 
                t.Minutes, 
                t.Seconds, 
                t.Milliseconds);

(As noted by Inder Kumar Rathore) For .NET > 4.0 you can use

TimeSpan time = TimeSpan.FromSeconds(seconds);

//here backslash is must to tell that colon is
//not the part of format, it just a character that we want in output
string str = time .ToString(@"hh\:mm\:ss\:fff");

(From Nick Molyneux) Ensure that seconds is less than TimeSpan.MaxValue.TotalSeconds to avoid an exception.

Change navbar color in Twitter Bootstrap

It took me a while, but I discovered that including the following was what made it possible to change the navbar color:

.navbar{ 
    background-image: none;
}

Load dimension value from res/values/dimension.xml from source code

Context.getResources().getDimension(int id);

How to get history on react-router v4?

Basing on this answer if you need history object only in order to navigate to other component:

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

Multiple github accounts on the same computer?

I use shell scripts to switch me to whatever account I want to be "active". Essentially you start from a fresh start, get one account configured properly and working, then move the these files to a name with the proper prefix. From then on you can use the command "github", or "gitxyz" to switch:

# my github script
cd ~/.ssh

if [ -f git_dhoerl -a -f git_dhoerl.pub -a -f config_dhoerl ]
then
    ; 
else 
    echo "Error: missing new files"
    exit 1
fi 

# Save a copy in /tmp, just in case
cp id_rsa /tmp
cp id_rsa.pub /tmp
cp config /tmp
echo "Saved old files in /tmp, just in case"

rm id_rsa
rm id_rsa.pub
rm config
echo "Removed current links/files"

ln git_dhoerl id_rsa
ln git_dhoerl.pub id_rsa.pub
ln config_dhoerl config

git config --global user.email "dhoerl@<company>.com"
git config --global github.user "dhoerl"        
git config --global github.token "whatever_it_is"

ssh-add -D

I've had great luck with this. I also created a run script in Xcode (for you Mac users) so it would not build my project unless I had the proper setting (since its using git):

Run Script placed after Dependencies (using /bin/ksh as the shell):

if [ "$(git config --global --get user.email)" != "dhoerl@<company>.com" ]
then
    exit 1
fi

EDIT: added tests for new files existence and copying old files to /tmp to address comment by @naomik below.

What does the ELIFECYCLE Node.js error mean?

I had the same error code when I was running npm run build inside node docker container.

Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM

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

How do I use a custom deleter with a std::unique_ptr member?

Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*). In other words, half of the bytes of the unique_ptr object are wasted.

Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:

Since C++17:

template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;

template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;

// usage:
my_unique_ptr<Bar, destroy> p{create()};

Prior to C++17:

template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;

template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;

// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};

Git - Won't add files?

Best bet is to copy your folder. Delete the original. Clone the project from github, copy your new files into the new cloned folder, and then try again.

Passive Link in Angular 2 - <a href=""> equivalent

If you have Angular 5 or above, just change

<a href="" (click)="passTheSalt()">Click me</a>

into

<a [routerLink]="" (click)="passTheSalt()">Click me</a>

A link will be displayed with a hand icon when hovering over it and clicking it won't trigger any route.

Note: If you want to keep the query parameters, you should set queryParamsHandling option to preserve:

<a [routerLink]=""
   queryParamsHandling="preserve"
   (click)="passTheSalt()">Click me</a>

Javascript | Set all values of an array

map is the most logical solution for this problem.

let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]

However, if there is a chance that the array is sparse, you'll need to use for or, even better, for .. of.

See:

Github: Can I see the number of downloads for a repo?

Based on VonC and Michele Milidoni answers I've created this bookmarklet which displays downloads statistics of github hosted released binaries.

Note: Because of issues with browsers related to Content Security Policy implementation, bookmarklets can temporarily violate some CSP directives and basically may not function properly when running on github while CSP is enabled.

Though its highly discouraged, you can disable CSP in Firefox as a temporary workaround. Open up about:config and set security.csp.enable to false.

MySql server startup error 'The server quit without updating PID file '

Try to remove ib_logfile0 and ib_logfile1 files and then run mysql again

rm /usr/local/var/mysql/ib_logfile0
rm /usr/local/var/mysql/ib_logfile1

It works for me.

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

Scheduling recurring task in Android

I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Timer;
 import java.util.TimerTask;

 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.app.Activity;
 import android.content.Intent;

 public class MainActivity extends Activity {

     CheckBox optSingleShot;
     Button btnStart, btnCancel;
     TextView textCounter;

     Timer timer;
     MyTimerTask myTimerTask;

     int tobeShown = 0  ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    optSingleShot = (CheckBox)findViewById(R.id.singleshot);
    btnStart = (Button)findViewById(R.id.start);
    btnCancel = (Button)findViewById(R.id.cancel);
    textCounter = (TextView)findViewById(R.id.counter);
    tobeShown = 1;

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }

    btnStart.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {


            Intent i = new Intent(MainActivity.this, ActivityB.class);
            startActivity(i);

            /*if(timer != null){
                timer.cancel();
            }

            //re-schedule timer here
            //otherwise, IllegalStateException of
            //"TimerTask is scheduled already" 
            //will be thrown
            timer = new Timer();
            myTimerTask = new MyTimerTask();

            if(optSingleShot.isChecked()){
                //singleshot delay 1000 ms
                timer.schedule(myTimerTask, 1000);
            }else{
                //delay 1000ms, repeat in 5000ms
                timer.schedule(myTimerTask, 1000, 1000);
            }*/
        }});

    btnCancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }
}


@Override
protected void onPause() {
    super.onPause();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

@Override
protected void onStop() {
    super.onStop();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        final String strDate = simpleDateFormat.format(calendar.getTime());

        runOnUiThread(new Runnable(){

            @Override
            public void run() {
                textCounter.setText(strDate);
            }});
    }
}

}