Programs & Examples On #List

The list tag may refer to: a linked list (an ordered set of nodes, each referencing its successor), or a form of dynamic array. Not to be used for HTML lists, use [html-lists] instead.

Access item in a list of lists

50 - List1[0][0] + List[0][1] - List[0][2]

List[0] gives you the first list in the list (try out print List[0]). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0].

How to merge lists into a list of tuples?

In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b)).

Search for an item in a Lua list

Sort of solution using metatable...

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end

How to get the nth element of a python list or a default if not available

Combining @Joachim's with the above, you could use

next(iter(my_list[index:index+1]), default)

Examples:

next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:index + 1] else default

How Big can a Python List Get?

12000 elements is nothing in Python... and actually the number of elements can go as far as the Python interpreter has memory on your system.

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.

How do I check in python if an element of a list is empty?

Suppose

letter= ['a','','b','c']

for i in range(len(letter)):
    if letter[i] =='':
        print(str(i) + ' is empty')

output- 1 is emtpy

So we can see index 1 is empty.

Finding the average of a list

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

l = map(float,l)
print '%.2f' %(sum(l)/len(l))

Modifying list while iterating

Use a while loop that checks for the truthfulness of the array:

while array:
    value = array.pop(0)
    # do some calculation here

And it should do it without any errors or funny behaviour.

Fastest way to count number of occurrences in a Python list

You can convert list in string with elements seperated by space and split it based on number/char to be searched..

Will be clean and fast for large list..

>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

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

and further

Set<String> set = new TreeSet<>();
    set.add("2");
    set.add("1");
    set.add("3");
    String first = set.stream().findFirst().get();

This will help you retrieve the first element of the list or set. Given that the set or list is not empty (get() on empty optional will throw java.util.NoSuchElementException)

orElse() can be used as: (this is just a work around - not recommended)

String first = set.stream().findFirst().orElse("");
set.removeIf(String::isEmpty);

Below is the appropriate approach :

Optional<String> firstString = set.stream().findFirst();
if(firstString.isPresent()){
    String first = firstString.get();
}

Similarly first element of the list can be retrieved.

Hope this helps.

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Avoid Adding duplicate elements to a List C#

Your this check:

if (!lines2.Contains(lines3.ToString()))

is invalid. You are checking if your lines2 contains System.String[] since lines3.ToString() will give you that. You need to check if item from lines3 exists in lines2 or not.

You can iterate each item in lines3 check if it exists in the lines2 and then add it. Something like.

foreach (string str in lines3)
{
    if (!lines2.Contains(str))
        lines2.Add(str);
}

Or if your lines2 is any empty list, then you can simply add the lines3 distinct values to the list like:

lines2.AddRange(lines3.Distinct());

then your lines2 will contain distinct values.

Transpose/Unzip Function (inverse of zip)?

You could also do

result = ([ a for a,b in original ], [ b for a,b in original ])

It should scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.

(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like zip does.)

If generators instead of actual lists are ok, this would do that:

result = (( a for a,b in original ), ( b for a,b in original ))

The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.

How to input matrix (2D list) in Python?

This code takes number of row and column from user then takes elements and displays as a matrix.

m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
  b = []
  print("{0} Row".format(i))
  for j in range(1,n+1):
    b.append(int(input("{0} Column: " .format(j))))
  a.append(b)
print(a)

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

How to create a list of objects?

I have some hacky answers that are likely to be terrible... but I have very little experience at this point.

a way:

class myClass():
    myInstances = []
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02
        self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
    thisStep += 1
    if "myClass object at" in thisLocalsLine:
        print(thisLocalsLine)
        print(myLocals[(thisStep - 2)])
        #myInstances.append(myLocals[(thisStep - 2)])
        print(myInstances)
        myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Another more 'clever' hack:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myInstances = []
myClasses = {
    "myObj01": ["Foo", "Bar"],
    "myObj02": ["FooBar",  "Baz"]
    }

for thisClass in myClasses.keys():
    exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
    myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Check if list is empty in C#

gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.

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

Use tuple unpacking:

>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
...    print a, b
... 
a 1
b 2
c 3

See also: Tuple unpacking in for loops.

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Converting list to *args when calling function

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

so:

>>> def printer(*args):
 print args


>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>> 

How to split() a delimited string to a List<String>

Include using namespace System.Linq

List<string> stringList = line.Split(',').ToList();

you can make use of it with ease for iterating through each item.

foreach(string str in stringList)
{

}

String.Split() returns an array, hence convert it to a list using ToList()

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Getting a map() to return a list in Python 3.x

Do this:

list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

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

Those list comprehensions are messy after a while.

I like this Pythonic approach:

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

If you need your code to be all super performant:

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

Flatten an irregular list of lists

totally hacky but I think it would work (depending on your data_type)

flat_list = ast.literal_eval("[%s]"%re.sub("[\[\]]","",str(the_list)))

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

TypeError: 'float' object is not subscriptable

PriceList[0][1][2][3][4][5][6]

This says: go to the 1st item of my collection PriceList. That thing is a collection; get its 2nd item. That thing is a collection; get its 3rd...

Instead, you want slicing:

PriceList[:7] = [PizzaChange]*7

Java ArrayList clear() function

If you in any doubt, have a look at JDK source code

ArrayList.clear() source code:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

You will see that size is set to 0 so you start from 0 position.

Please note that when adding elements to ArrayList, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear() you only remove references to array elements and sets size to 0, however, capacity stays as it was.

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

Merge Two Lists in R

This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

appendList <- function (x, val) 
{
    stopifnot(is.list(x), is.list(val))
    xnames <- names(x)
    for (v in names(val)) {
        x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]])) 
            appendList(x[[v]], val[[v]])
        else c(x[[v]], val[[v]])
    }
    x
}

> appendList(first,second)
$a
[1] 1 2

$b
[1] 2 3

$c
[1] 3 4

Break string into list of characters in Python

fO = open(filename, 'rU')
lst = list(fO.read())

Iterating through list of list in Python

Create a method to recursively iterate through nested lists. If the current element is an instance of list, then call the same method again. If not, print the current element. Here's an example:

data = [1,2,3,[4,[5,6,7,[8,9]]]]

def print_list(the_list):

    for each_item in the_list:
        if isinstance(each_item, list):
            print_list(each_item)
        else:
            print(each_item)

print_list(data)

Filtering a list based on a list of booleans

To do this using numpy, ie, if you have an array, a, instead of list_a:

a = np.array([1, 2, 4, 6])
my_filter = np.array([True, False, True, False], dtype=bool)
a[my_filter]
> array([1, 4])

What exactly does the .join() method do?

There is a good explanation of why it is costly to use + for concatenating a large number of strings here

Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.

''.join([a, b, c]) trick is a performance optimization.

Extract first item of each sublist

lst = [['a','b','c'], [1,2,3], ['x','y','z']]
outputlist = []
for values in lst:
    outputlist.append(values[0])

print(outputlist) 

Output: ['a', 1, 'x']

Print a list in reverse order with range()?

Suppose you have a list call it a={1,2,3,4,5} Now if you want to print the list in reverse then simply use the following code.

a.reverse
for i in a:
   print(i)

I know you asked using range but its already answered.

How do I join two lists in Java?

I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)

Is there a concurrent List in Java's JDK?

Mostly if you need a concurrent list it is inside a model object (as you should not use abstract data types like a list to represent a node in a application model graph) or it is part of a particular service, you can synchronize the access yourself.

class MyClass {
  List<MyType> myConcurrentList = new ArrayList<>();
  void myMethod() {
    synchronzied(myConcurrentList) {
      doSomethingWithList;
    }
  }
}

Often this is enough to get you going. If you need to iterate, iterate over a copy of the list not the list itself and only synchronize the part where you copy the list not while you are iterating over it.

Also when concurrently working on a list you usually do something more than just adding or removing or copying, meaning that the operation becomes meaningful enough to warrent its own method and the list becomes member of a special class representing just this particular list with thread safe behavior.

Even if I agree that a concurrent list implementation is needed and Vector / Collections.sychronizeList(list) do not do the trick as for sure you need something like compareAndAdd or compareAndRemove or get(..., ifAbsentDo), even if you have a ConcurrentList implementation developers often introduce bugs by not considering what is the true transaction when working with a concurrent lists (and maps).

These scenarios where the transactions are too small for what the intended purpose of the interaction with a concurrent ADT (abstract data type) always lead to me hide the list in a special class and synchronizing access to this class objects method using the synchronized on the method level. Its the only way to be sure that the transactions are correct.

I have seen too many bugs to do it any other way - at least if the code is important and handles something like money or security or guarantees some quality of service measures (e.g sending message at least once and only once).

How can I get a resource "Folder" from inside my jar File?

Below code gets .yaml files from a custom resource directory.

ClassLoader classLoader = this.getClass().getClassLoader();
            URI uri = classLoader.getResource(directoryPath).toURI();
    
            if("jar".equalsIgnoreCase(uri.getScheme())){
                Pattern pattern = Pattern.compile("^.+" +"/classes/" + directoryPath + "/.+.yaml$");
                log.debug("pattern {} ", pattern.pattern());
                ApplicationHome home = new ApplicationHome(SomeApplication.class);
                JarFile file = new JarFile(home.getSource());
                Enumeration<JarEntry>  jarEntries = file.entries() ;
                while(jarEntries.hasMoreElements()){
                    JarEntry entry = jarEntries.nextElement();
                    Matcher matcher = pattern.matcher(entry.getName());
                    if(matcher.find()){
                        InputStream in =
                                file.getInputStream(entry);
                        //work on the stream
    
    
                    }
                }
    
            }else{
                //When Spring boot application executed through Non-Jar strategy like through IDE or as a War.
    
                String path = uri.getPath();
                File[] files = new File(path).listFiles();
               
                for(File file: files){
                    if(file != null){
                        try {
                            InputStream is = new FileInputStream(file);
                           //work on stream
                            
                        } catch (Exception e) {
                            log.error("Exception while parsing file yaml file {} : {} " , file.getAbsolutePath(), e.getMessage());
                        }
                    }else{
                        log.warn("File Object is null while parsing yaml file");
                    }
                }
            }
             

How can I add an item to a IEnumerable<T> collection?

Have you considered using ICollection<T> or IList<T> interfaces instead, they exist for the very reason that you want to have an Add method on an IEnumerable<T>.

IEnumerable<T> is used to 'mark' a type as being...well, enumerable or just a sequence of items without necessarily making any guarantees of whether the real underlying object supports adding/removing of items. Also remember that these interfaces implement IEnumerable<T> so you get all the extensions methods that you get with IEnumerable<T> as well.

Python: finding an element in a list

assuming you want to find a value in a numpy array, I guess something like this might work:

Numpy.where(arr=="value")[0]

Pythonic way to print list items

[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items

How does one convert a HashMap to a List in Java?

Collection Interface has 3 views

  • keySet
  • values
  • entrySet

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

      Map m=new HashMap();
          m.put(3, "dev2");
          m.put(4, "dev3");

      List<Entry> entryList = new ArrayList<Entry>(m.entrySet());

      for (Entry s : entryList) {
        System.out.println(s);
      }

ArrayList has this constructor.

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

What is the difference between Set and List?

1.List allows duplicate values and set does'nt allow duplicates

2.List maintains the order in which you inserted elements in to the list Set does'nt maintain order. 3.List is an ordered sequence of elements whereas Set is a distinct list of elements which is unordered.

How to 'update' or 'overwrite' a python list

If you are trying to take a value from the same array and trying to update it, you can use the following code.

{  'condition': { 
                     'ts': [   '5a81625ba0ff65023c729022',
                               '5a8161ada0ff65023c728f51',
                               '5a815fb4a0ff65023c728dcd']}

If the collection is userData['condition']['ts'] and we need to

    for i,supplier in enumerate(userData['condition']['ts']): 
        supplier = ObjectId(supplier)
        userData['condition']['ts'][i] = supplier

The output will be

{'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                            ObjectId('5a8161ada0ff65023c728f51'),
                            ObjectId('5a815fb4a0ff65023c728dcd')]}

Join a list of items with different types as string in Python

Calling str(...) is the Pythonic way to convert something to a string.

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:

print(','.join(str(x) for x in list_of_ints))

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

How to iterate over each string in a list of strings and operate on it's elements

The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
count = 0  
for i in words:  
     if i[0]==i[-1]:
        count = count + 1  
print(count)  

Output:

$python main.py
3

List<String> to ArrayList<String> conversion issue

Take a look at ArrayList#addAll(Collection)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)

So basically you could use

ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);

How can I remove an element from a list?

if you'd like to avoid numeric indices, you can use

a <- setdiff(names(a),c("name1", ..., "namen"))

to delete names namea...namen from a. this works for lists

> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2

as well as for vectors

> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b 
2

How to Correctly Use Lists in R?

Regarding your questions, let me address them in order and give some examples:

1) A list is returned if and when the return statement adds one. Consider

 R> retList <- function() return(list(1,2,3,4)); class(retList())
 [1] "list"
 R> notList <- function() return(c(1,2,3,4)); class(notList())
 [1] "numeric"
 R> 

2) Names are simply not set:

R> retList <- function() return(list(1,2,3,4)); names(retList())
NULL
R> 

3) They do not return the same thing. Your example gives

R> x <- list(1,2,3,4)
R> x[1]
[[1]]
[1] 1
R> x[[1]]
[1] 1

where x[1] returns the first element of x -- which is the same as x. Every scalar is a vector of length one. On the other hand x[[1]] returns the first element of the list.

4) Lastly, the two are different between they create, respectively, a list containing four scalars and a list with a single element (that happens to be a vector of four elements).

Python list iterator behavior and next(iterator)

For those who still do not understand.

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0 # print(i) printed this
1 # next(a) printed this
2 # print(i) printed this
3 # next(a) printed this
4 # print(i) printed this
5 # next(a) printed this
6 # print(i) printed this
7 # next(a) printed this
8 # print(i) printed this
9 # next(a) printed this

As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.

Removing duplicates in the lists

Check for the string 'a' and 'b'

clean_list = []
    for ele in raw_list:
        if 'b' in ele or 'a' in ele:
            pass
        else:
            clean_list.append(ele)

Initialising an array of fixed size in python

>>> n = 5                     #length of list
>>> list = [None] * n         #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]

or with really nothing in the list to begin with:

>>> n = 5                     #length of list
>>> list = []                 # create list
>>> print(list)
[]

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1]

on the 4th iteration of append:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]

5 and all subsequent:

>>> list.append(1)            #append 1 to right side of list
>>> list = list[-n:]          #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]

How can I sort a List alphabetically?

Assuming that those are Strings, use the convenient static method sort

 java.util.Collections.sort(listOfCountryNames)

Java 8 stream reverse order

For the specific question of generating a reverse IntStream, try something like this:

static IntStream revRange(int from, int to) {
    return IntStream.range(from, to)
                    .map(i -> to - i + from - 1);
}

This avoids boxing and sorting.

For the general question of how to reverse a stream of any type, I don't know of there's a "proper" way. There are a couple ways I can think of. Both end up storing the stream elements. I don't know of a way to reverse a stream without storing the elements.

This first way stores the elements into an array and reads them out to a stream in reverse order. Note that since we don't know the runtime type of the stream elements, we can't type the array properly, requiring an unchecked cast.

@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
    Object[] temp = input.toArray();
    return (Stream<T>) IntStream.range(0, temp.length)
                                .mapToObj(i -> temp[temp.length - i - 1]);
}

Another technique uses collectors to accumulate the items into a reversed list. This does lots of insertions at the front of ArrayList objects, so there's lots of copying going on.

Stream<T> input = ... ;
List<T> output =
    input.collect(ArrayList::new,
                  (list, e) -> list.add(0, e),
                  (list1, list2) -> list1.addAll(0, list2));

It's probably possible to write a much more efficient reversing collector using some kind of customized data structure.

UPDATE 2016-01-29

Since this question has gotten a bit of attention recently, I figure I should update my answer to solve the problem with inserting at the front of ArrayList. This will be horribly inefficient with a large number of elements, requiring O(N^2) copying.

It's preferable to use an ArrayDeque instead, which efficiently supports insertion at the front. A small wrinkle is that we can't use the three-arg form of Stream.collect(); it requires the contents of the second arg be merged into the first arg, and there's no "add-all-at-front" bulk operation on Deque. Instead, we use addAll() to append the contents of the first arg to the end of the second, and then we return the second. This requires using the Collector.of() factory method.

The complete code is this:

Deque<String> output =
    input.collect(Collector.of(
        ArrayDeque::new,
        (deq, t) -> deq.addFirst(t),
        (d1, d2) -> { d2.addAll(d1); return d2; }));

The result is a Deque instead of a List, but that shouldn't be much of an issue, as it can easily be iterated or streamed in the now-reversed order.

Deleting multiple elements from a list

As a specialisation of Greg's answer, you can even use extended slice syntax. eg. If you wanted to delete items 0 and 2:

>>> a= [0, 1, 2, 3, 4]
>>> del a[0:3:2]
>>> a
[1, 3, 4]

This doesn't cover any arbitrary selection, of course, but it can certainly work for deleting any two items.

How to remove square brackets from list in Python?

Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.

How to Sort a List<T> by a property in the object

Please let me complete the answer by @LukeH with some sample code, as I have tested it I believe it may be useful for some:

public class Order
{
    public string OrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public int Quantity { get; set; }
    public int Total { get; set; }

    public Order(string orderId, DateTime orderDate, int quantity, int total)
    {
        OrderId = orderId;
        OrderDate = orderDate;
        Quantity = quantity;
        Total = total;
    }
}

public void SampleDataAndTest()
{
    List<Order> objListOrder = new List<Order>();

    objListOrder.Add(new Order("tu me paulo ", Convert.ToDateTime("01/06/2016"), 1, 44));
    objListOrder.Add(new Order("ante laudabas", Convert.ToDateTime("02/05/2016"), 2, 55));
    objListOrder.Add(new Order("ad ordinem ", Convert.ToDateTime("03/04/2016"), 5, 66));
    objListOrder.Add(new Order("collocationem ", Convert.ToDateTime("04/03/2016"), 9, 77));
    objListOrder.Add(new Order("que rerum ac ", Convert.ToDateTime("05/02/2016"), 10, 65));
    objListOrder.Add(new Order("locorum ; cuius", Convert.ToDateTime("06/01/2016"), 1, 343));


    Console.WriteLine("Sort the list by date ascending:");
    objListOrder.Sort((x, y) => x.OrderDate.CompareTo(y.OrderDate));

    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    Console.WriteLine("Sort the list by date descending:");
    objListOrder.Sort((x, y) => y.OrderDate.CompareTo(x.OrderDate));
    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    Console.WriteLine("Sort the list by OrderId ascending:");
    objListOrder.Sort((x, y) => x.OrderId.CompareTo(y.OrderId));
    foreach (Order o in objListOrder)
        Console.WriteLine("OrderId = " + o.OrderId + " OrderDate = " + o.OrderDate.ToString() + " Quantity = " + o.Quantity + " Total = " + o.Total);

    //etc ...
}

Python 3 turn range to a list

in Python 3.x, the range() function got its own type. so in this case you must use iterator

list(range(1000))

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)

Getting all file names from a folder using C#

It depends on what you want to do.

ref: http://www.csharp-examples.net/get-files-from-directory/

This will bring back ALL the files in the specified directory

string[] fileArray = Directory.GetFiles(@"c:\Dir\");

This will bring back ALL the files in the specified directory with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg");

This will bring back ALL the files in the specified directory AS WELL AS all subdirectories with a certain extension

string[] fileArray = Directory.GetFiles(@"c:\Dir\", "*.jpg", SearchOption.AllDirectories);

Hope this helps

Looping over a list in Python

Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.

list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
  change = list1[i] - list1[i-1]
  list2.append(change)

Note that while len(list1) is 11 (elements), len(list2) will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Sorting list based on values from another list

list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]

output=[]
cur_loclist = []

To get unique values present in list2

list_set = set(list2)

To find the loc of the index in list2

list_str = ''.join(str(s) for s in list2)

Location of index in list2 is tracked using cur_loclist

[0, 3, 7, 1, 2, 4, 8, 5, 6]

for i in list_set:
cur_loc = list_str.find(str(i))

while cur_loc >= 0:
    cur_loclist.append(cur_loc)
    cur_loc = list_str.find(str(i),cur_loc+1)

print(cur_loclist)

for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

Convert List to Pandas Dataframe Column

Use:

L = ['Thanks You', 'Its fine no problem', 'Are you sure']

#create new df 
df = pd.DataFrame({'col':L})
print (df)

                   col
0           Thanks You
1  Its fine no problem
2         Are you sure

df = pd.DataFrame({'oldcol':[1,2,3]})

#add column to existing df 
df['col'] = L
print (df)
   oldcol                  col
0       1           Thanks You
1       2  Its fine no problem
2       3         Are you sure

Thank you DYZ:

#default column name 0
df = pd.DataFrame(L)
print (df)
                     0
0           Thanks You
1  Its fine no problem
2         Are you sure

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

How to remove \n from a list element?

To handle many newline delimiters, including character combinations like \r\n, use splitlines. Combine join and splitlines to remove/replace all newlines from a string s:

''.join(s.splitlines())

To remove exactly one trailing newline, pass True as the keepends argument to retain the delimiters, removing only the delimiters on the last line:

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

Simultaneously merge multiple data.frames in a list

Reduce makes this fairly easy:

merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)

Here's a fully example using some mock data:

set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
#    x  a  b         y
#12 12 NA 18        NA
#13 13 NA 19        NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352

And here's an example using these data to replicate my.list:

merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]

#  matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1   ALGIERE   200 RI      026       S         NA   <NA>   NA   NA   NA         NA   <NA>
#2     ALVES   100 RI      019       S         NA   <NA>   NA   NA   NA         NA   <NA>
#3    BADEAU   100 RI      032       S         NA   <NA>   NA   NA   NA         NA   <NA>

Note: It looks like this is arguably a bug in merge. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame which does make.unique the names, causing the rbind to fail.

# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname    party        st           district     chamber      senate1993   name.x      
# [8] votes.year.x senate1994   name.y       votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname    party        st           district     chamber      senate1993   name.x      
# [8] votes.year.x senate1994   name.y       votes.year.y senate1995   name         votes.year  
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.

Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge. Eg:

my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
      names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))

The merge/Reduce will then work fine.

Alphabet range in Python

[chr(i) for i in range(ord('a'),ord('z')+1)]

Binding List<T> to DataGridView in WinForm

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

But I would even go further and bind your grid to a BindingSource

var list = new List<Person>()
{
    new Person { Name = "Joe", },
    new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

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

You can use the str.split method.

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

If you want to convert it to a tuple, just

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

If you are looking to append to a list, try this:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']

Python Sets vs Lists

Lists are slightly faster than sets when you just want to iterate over the values.

Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.

It turns out tuples perform in almost exactly the same way as lists, except for their immutability.

Iterating

>>> def iter_test(iterable):
...     for i in iterable:
...         pass
...
>>> from timeit import timeit
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = set(range(10000))",
...     number=100000)
12.666952133178711
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = list(range(10000))",
...     number=100000)
9.917098999023438
>>> timeit(
...     "iter_test(iterable)",
...     setup="from __main__ import iter_test; iterable = tuple(range(10000))",
...     number=100000)
9.865639209747314

Determine if an object is present

>>> def in_test(iterable):
...     for i in range(1000):
...         if i in iterable:
...             pass
...
>>> from timeit import timeit
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = set(range(1000))",
...     number=10000)
0.5591847896575928
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = list(range(1000))",
...     number=10000)
50.18339991569519
>>> timeit(
...     "in_test(iterable)",
...     setup="from __main__ import in_test; iterable = tuple(range(1000))",
...     number=10000)
51.597304821014404

Multiple parameters in a List. How to create without a class?

If appropriate, you might use a Dictionary which is also a generic collection:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);

How do I multiply each element in a list by a number?

You can just use a list comprehension:

my_list = [1, 2, 3, 4, 5]
my_new_list = [i * 5 for i in my_list]

>>> print(my_new_list)
[5, 10, 15, 20, 25]

Note that a list comprehension is generally a more efficient way to do a for loop:

my_new_list = []
for i in my_list:
    my_new_list.append(i * 5)

>>> print(my_new_list)
[5, 10, 15, 20, 25]

As an alternative, here is a solution using the popular Pandas package:

import pandas as pd

s = pd.Series(my_list)

>>> s * 5
0     5
1    10
2    15
3    20
4    25
dtype: int64

Or, if you just want the list:

>>> (s * 5).tolist()
[5, 10, 15, 20, 25]

How can I order a List<string>?

ListaServizi.Sort();

Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.

How to convert a column of DataTable to a List

var list = dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<string>(columnName)).ToList();

[Edit: Add a reference to System.Data.DataSetExtensions to your project if this does not compile]

When to use a linked list over an array/array list?

A simple answer to the question can be given using these points:

  1. Arrays are to be used when a collection of similar type data elements is required. Whereas, linked list is a collection of mixed type data linked elements known as nodes.

  2. In array, one can visit any element in O(1) time. Whereas, in linked list we would need to traverse entire linked list from head to the required node taking O(n) time.

  3. For arrays, a specific size needs to be declared initially. But linked lists are dynamic in size.

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

Difference between del, remove, and pop on lists

Since no-one else has mentioned it, note that del (unlike pop) allows the removal of a range of indexes because of list slicing:

>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]

This also allows avoidance of an IndexError if the index is not in the list:

>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

Python data structure sort list alphabetically

ListName.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: ListName.sort(reverse=False)

How to get first object out from List<Object> using Linq

I do so.

List<Object> list = new List<Object>();

if(list.Count>0){
  Object obj = list[0];
}

how to check if List<T> element contains an item with a Particular Property Value

You can using the exists

if (pricePublicList.Exists(x => x.Size == 200))
{
   //code
}

How to find all occurrences of an element in a list

Here is a time performance comparison between using np.where vs list_comprehension. Seems like np.where is faster on average.

# np.where
start_times = []
end_times = []
for i in range(10000):
    start = time.time()
    start_times.append(start)
    temp_list = np.array([1,2,3,3,5])
    ixs = np.where(temp_list==3)[0].tolist()
    end = time.time()
    end_times.append(end)
print("Took on average {} seconds".format(
    np.mean(end_times)-np.mean(start_times)))
Took on average 3.81469726562e-06 seconds
# list_comprehension
start_times = []
end_times = []
for i in range(10000):
    start = time.time()
    start_times.append(start)
    temp_list = np.array([1,2,3,3,5])
    ixs = [i for i in range(len(temp_list)) if temp_list[i]==3]
    end = time.time()
    end_times.append(end)
print("Took on average {} seconds".format(
    np.mean(end_times)-np.mean(start_times)))
Took on average 4.05311584473e-06 seconds

How can I count the occurrences of a list item?

It was suggested to use numpy's bincount, however it works only for 1d arrays with non-negative integers. Also, the resulting array might be confusing (it contains the occurrences of the integers from min to max of the original list, and sets to 0 the missing integers).

A better way to do it with numpy is to use the unique function with the attribute return_counts set to True. It returns a tuple with an array of the unique values and an array of the occurrences of each unique value.

# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True)  # array([0, 1, 2, 3]), array([2, 3, 1, 2]

and then we can pair them as

dict(zip(a_uniq, counts))  # {0: 2, 1: 3, 2: 1, 3: 2}

It also works with other data types and "2d lists", e.g.

>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

How to append multiple values to a list in Python

You can use the sequence method list.extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.

>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]

>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

So you can use list.append() to append a single value, and list.extend() to append multiple values.

How to sort List<Integer>?

Ascending order:

 Collections.sort(lList); 

Descending order:

Collections.sort(lList, Collections.reverseOrder()); 

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Regular expression field validation in jQuery

A simple nowadays example:

$('#some_input_id').attr('oninput',
"this.value=this.value.replace(/[^0-9A-Za-z\s_-]/g,'');")

that means all that doesnt match regex becomes nothing , i.e. ''

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

creating array without declaring the size - java

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List<Float> unindexedVectors = new ArrayList<Float>();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);

Elegant way to read file into byte[] array in Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

jquery clear input default value

$(document).ready(function() {
  //...
//clear on focus
$('.input').focus(function() {
    $('.input').val("");
});
   //clear when submitted
$('.button').click(function() {
    $('.input').val("");
});

});

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Here is some relevant code:

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Install the all-trusting trust manager
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// Now you can access an https URL without having the certificate in the truststore
try {
    URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}

This will completely disable SSL checking—just don't learn exception handling from such code!

To do what you want, you would have to implement a check in your TrustManager that prompts the user.

HTML: can I display button text in multiple lines?

Yes it is, and you can also use it like this

<button>Click here to<br/> start playing</button>

if you want to make the break yourself.

What is the recommended way to delete a large number of items from DynamoDB?

What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.

An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:

  1. Use Query rather than Scan to retrieve all items for user_id - this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..

    • Please note that you''ll have to deal with the query API paging here as usual, see the ExclusiveStartKey parameter:

      Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.

  2. Loop over all returned items and either facilitate DeleteItem as usual

    • Update: Most likely BatchWriteItem is more appropriate for a use case like this (see below for details).

Update

As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:

To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.

Please note that this still has some relevant limitations, most notably:

  • Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).

  • Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]

Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

Java - Best way to print 2D array?

Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):

System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
    System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[row].length; col++) {
        if (col < 1) {
            System.out.print(row);
            System.out.print("\t" + array[row][col]);
        } else {

            System.out.print("\t" + array[row][col]);
        }
    }
    System.out.println();
}

How do you find all subclasses of a given class in Java?

Don't forget that the generated Javadoc for a class will include a list of known subclasses (and for interfaces, known implementing classes).

How can I enable CORS on Django REST Framework

Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0

Follow the official instruction doesn't work

Finally use the old way to figure it out.

ADD:

# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening

#proj/settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'proj.middlewares.CsrfExemptSessionAuthentication',
    ),
}

Is <img> element block level or inline level?

is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}

Returning binary file from controller in ASP.NET Web API

For Web API 2, you can implement IHttpActionResult. Here's mine:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

class FileResult : IHttpActionResult
{
    private readonly string _filePath;
    private readonly string _contentType;

    public FileResult(string filePath, string contentType = null)
    {
        if (filePath == null) throw new ArgumentNullException("filePath");

        _filePath = filePath;
        _contentType = contentType;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(File.OpenRead(_filePath))
        };

        var contentType = _contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(_filePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

        return Task.FromResult(response);
    }
}

Then something like this in your controller:

[Route("Images/{*imagePath}")]
public IHttpActionResult GetImage(string imagePath)
{
    var serverPath = Path.Combine(_rootPath, imagePath);
    var fileInfo = new FileInfo(serverPath);

    return !fileInfo.Exists
        ? (IHttpActionResult) NotFound()
        : new FileResult(fileInfo.FullName);
}

And here's one way you can tell IIS to ignore requests with an extension so that the request will make it to the controller:

<!-- web.config -->
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

I assume your column type is STRING (CHAR, VARCHAR, etc) and sorting procedure is sorting it as a string. What you need to do is to convert value into numeric value. How to do it will depend on SQL system you use.

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

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

How can I close a login form and show the main form without my application closing?

public void ShowMain()
  {
       if(auth()) // a method that returns true when the user exists.
       {        
         this.Hide();
         var main = new Main();
         main.Show();
       }
      else
       {
              MessageBox.Show("Invalid login details.");
        }         
   }

How does `scp` differ from `rsync`?

Difference b/w scp and rsync on different parameter

1. Performance over latency

  • scp : scp is relatively less optimise and speed

  • rsync : rsync is comparatively more optimise and speed

https://www.disk91.com/2014/technology/networks/compare-performance-of-different-file-transfer-protocol-over-latency/

2. Interruption handling

  • scp : scp command line tool cannot resume aborted downloads from lost network connections

  • rsync : If the above rsync session itself gets interrupted, you can resume it as many time as you want by typing the same command. rsync will automatically restart the transfer where it left off.

http://ask.xmodulo.com/resume-large-scp-file-transfer-linux.html

3. Command Example

scp

$ scp source_file_path destination_file_path

rsync

$ cd /path/to/directory/of/partially_downloaded_file
$ rsync -P --rsh=ssh [email protected]:bigdata.tgz ./bigdata.tgz 

The -P option is the same as --partial --progress, allowing rsync to work with partially downloaded files. The --rsh=ssh option tells rsync to use ssh as a remote shell.

4. Security :

scp is more secure. You have to use rsync --rsh=ssh to make it as secure as scp.

man document to know more :

performance chart

Getting the ID of the element that fired an event

I'm working with

jQuery Autocomplete

I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.

Change the image source on rollover using jQuery

<img src="img1.jpg" data-swap="img2.jpg"/>



img = {

 init: function() {
  $('img').on('mouseover', img.swap);
  $('img').on('mouseover', img.swap);
 }, 

 swap: function() {
  var tmp = $(this).data('swap');
  $(this).attr('data-swap', $(this).attr('src'));
  $(this).attr('str', tmp);
 }
}

img.init();

Use Async/Await with Axios in React.js

Async/Await with axios 

  useEffect(() => {     
    const getData = async () => {  
      await axios.get('your_url')  
      .then(res => {  
        console.log(res)  
      })  
      .catch(err => {  
        console.log(err)  
      });  
    }  
    getData()  
  }, [])

How do I force my .NET application to run as administrator?

In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.

How to disable Home and other system buttons in Android?

It used to be possible to disable the Home button, but now it isn't. It's due to malicious software that would trap the user.

You can see more detailes here: Disable Home button in Android 4.0+

Finally, the Back button can be disabled, as you can see in this other question: Disable back button in android

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

onclick="javascript:history.go(-1)" not working in Chrome

Try this:

<a href="www.mypage.com" onclick="history.go(-1); return false;"> Link </a>

Converting file into Base64String and back again

Another working example in VB.NET:

Public Function base64Encode(ByVal myDataToEncode As String) As String
    Try
        Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
        myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
        Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
        Return myEncodedData
    Catch ex As Exception
        Throw (New Exception("Error in base64Encode" & ex.Message))
    End Try
    '
End Function

R: Print list to a text file

Here is another

cat(sapply(mylist, toString), file, sep="\n")

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

How do I convert ticks to minutes?

The clearest way in my view is to use TimeSpan.FromTicks and then convert that to minutes:

TimeSpan ts = TimeSpan.FromTicks(ticks);
double minutes = ts.TotalMinutes;

System.BadImageFormatException: Could not load file or assembly

My cause was different I referenced a web service then I got this message.

Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.

hope this helps!

jQuery count number of divs with a certain class?

You can use the jquery .length property

var numItems = $('.item').length;

Why does integer division in C# return an integer and not a float?

Might be useful:

double a = 5.0/2.0;   
Console.WriteLine (a);      // 2.5

double b = 5/2;   
Console.WriteLine (b);      // 2

int c = 5/2;   
Console.WriteLine (c);      // 2

double d = 5f/2f;   
Console.WriteLine (d);      // 2.5

How to serve up images in Angular2?

Angular only points to src/assets folder, nothing else is public to access via url so you should use full path

 this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'

Or

 this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'

This will only work if the base href tag is set with /

You can also add other folders for data in angular/cli. All you need to modify is angular-cli.json

"assets": [
 "assets",
 "img",
 "favicon.ico",
 ".htaccess"
]

Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.

Create a git patch from the uncommitted changes in the current working directory

git diff for unstaged changes.

git diff --cached for staged changes.

git diff HEAD for both staged and unstaged changes.

Listing only directories using ls in Bash?

Adding on to make it full circle, to retrieve the path of every folder, use a combination of Albert's answer as well as Gordans. That should be pretty useful.

for i in $(ls -d /pathto/parent/folder/*/); do echo ${i%%/}; done

Output:

/pathto/parent/folder/childfolder1/
/pathto/parent/folder/childfolder2/
/pathto/parent/folder/childfolder3/
/pathto/parent/folder/childfolder4/
/pathto/parent/folder/childfolder5/
/pathto/parent/folder/childfolder6/
/pathto/parent/folder/childfolder7/
/pathto/parent/folder/childfolder8/

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

Get installed applications in a system

Iterating through the registry key "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" seems to give a comprehensive list of installed applications.

Aside from the example below, you can find a similar version to what I've done here.

This is a rough example, you'll probaby want to do something to strip out blank rows like in the 2nd link provided.

string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using(Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
    foreach(string subkey_name in key.GetSubKeyNames())
    {
        using(RegistryKey subkey = key.OpenSubKey(subkey_name))
        {
            Console.WriteLine(subkey.GetValue("DisplayName"));
        }
    }
}

Alternatively, you can use WMI as has been mentioned:

ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
foreach(ManagementObject mo in mos.Get())
{
    Console.WriteLine(mo["Name"]);
}

But this is rather slower to execute, and I've heard it may only list programs installed under "ALLUSERS", though that may be incorrect. It also ignores the Windows components & updates, which may be handy for you.

Android Button Onclick

If you write like this in Button tag in xml file : android:onClick="setLogin" then

Do like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn"
    android:onClick="onClickBtn" />

</LinearLayout>

and in Code part:

public class StartUpActivity extends Activity 
{
    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);    
    }

    public void onClickBtn(View v)
    {
        Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
    } 
}

and no need all this:

 Button button = (Button) findViewById(R.id.button1);
 button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
 });

Check it once;

How to get text of an input text box during onKeyPress?

There is a better way to do this. Use the concat Method. Example

declare a global variable. this works good on angular 10, just pass it to Vanilla JavaScript. Example:

HTML

<input id="edValue" type="text" onKeyPress="edValueKeyPress($event)"><br>
<span id="lblValue">The text box contains: </span>

CODE

emptyString = ''

edValueKeyPress ($event){
   this.emptyString = this.emptyString.concat($event.key);
   console.log(this.emptyString);
}

SQL: sum 3 columns when one column has a null value?

You can use ISNULL:

ISNULL(field, VALUEINCASEOFNULL)

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

Rotate camera in Three.js with mouse

OrbitControls and TrackballControls seems to be good for this purpose.

controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;

update in render

controls.update();

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

I recently submitted an app to Apple's App Store. My app was built using iOS 12, Xcode 10, and Swift 4.2. My app uses Google AdMob for the sole purpose of showing Interstitial Ads. When prompted these question, this is what I did:

1) Does this app use the Advertising Identifier (IDFA)? ANSWER: YES

a) Serve advertisements within the app - CHECKED

b) Attribute this app ... - NOT CHECKED

c) Attribute an action ... - NOT CHECKED

I, (my name), confirm that this app ... - CHECKED

My app was accepted and "Ready for Sale" in less than 24 hrs.

How do I read / convert an InputStream into a String in Java?

You can use Apache Commons.

In the IOUtils you can find the toString method with three helpful implementations.

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input, String encoding)
            throws IOException {
        return toString(input, Charsets.toCharset(encoding));
}

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

StringTokenizer is totally unsuited to the task of breaking a string into its individual characters. With String#split() you can do that easily by using a regex that matches nothing, e.g.:

String[] theChars = str.split("|");

But StringTokenizer doesn't use regexes, and there's no delimiter string you can specify that will match the nothing between characters. There is one cute little hack you can use to accomplish the same thing: use the string itself as the delimiter string (making every character in it a delimiter) and have it return the delimiters:

StringTokenizer st = new StringTokenizer(str, str, true);

However, I only mention these options for the purpose of dismissing them. Both techniques break the original string into one-character strings instead of char primitives, and both involve a great deal of overhead in the form of object creation and string manipulation. Compare that to calling charAt() in a for loop, which incurs virtually no overhead.

CSS – why doesn’t percentage height work?

A percentage value in a height property has a little complication, and the width and height properties actually behave differently to each other. Let me take you on a tour through the specs.

height property:

Let's have a look at what CSS Snapshot 2010 spec says about height:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'. A percentage height on the root element is relative to the initial containing block. Note: For absolutely positioned elements whose containing block is based on a block-level element, the percentage is calculated with respect to the height of the padding box of that element.

OK, let's take that apart step by step:

The percentage is calculated with respect to the height of the generated box's containing block.

What's a containing block? It's a bit complicated, but for a normal element in the default static position, it's:

the nearest block container ancestor box

or in English, its parent box. (It's well worth knowing what it would be for fixed and absolute positions as well, but I'm ignoring that to keep this answer short.)

So take these two examples:

_x000D_
_x000D_
<div   id="a"  style="width: 100px; height: 200px; background-color: orange">_x000D_
  <div id="aa" style="width: 100px; height: 50%;   background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="b"  style="width: 100px;              background-color: orange">_x000D_
  <div id="bb" style="width: 100px; height: 50%; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example, the containing block of #aa is #a, and so on for #b and #bb. So far, so good.

The next sentence of the spec for height is the complication I mentioned in the introduction to this answer:

If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

Aha! Whether the height of the containing block has been specified explicitly matters!

  • 50% of height:200px is 100px in the case of #aa
  • But 50% of height:auto is auto, which is 0px in the case of #bb since there is no content for auto to expand to

As the spec says, it also matters whether the containing block has been absolutely positioned or not, but let's move on to width.

width property:

So does it work the same way for width? Let's take a look at the spec:

The percentage is calculated with respect to the width of the generated box's containing block.

Take a look at these familiar examples, tweaked from the previous to vary width instead of height:

_x000D_
_x000D_
<div   id="c"  style="width: 200px; height: 100px; background-color: orange">_x000D_
  <div id="cc" style="width: 50%;   height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<div   id="d"  style="            height: 100px; background-color: orange">_x000D_
  <div id="dd" style="width: 50%; height: 100px; background-color: blue"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • 50% of width:200px is 100px in the case of #cc
  • 50% of width:auto is 50% of whatever width:auto ends up being, unlike height, there is no special rule that treats this case differently.

Now, here's the tricky bit: auto means different things, depending partly on whether its been specified for width or height! For height, it just meant the height needed to fit the contents*, but for width, auto is actually more complicated. You can see from the code snippet that's in this case it ended up being the width of the viewport.

What does the spec say about the auto value for width?

The width depends on the values of other properties. See the sections below.

Wahey, that's not helpful. To save you the trouble, I've found you the relevant section to our use-case, titled "calculating widths and margins", subtitled "block-level, non-replaced elements in normal flow":

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

OK, so width plus the relevant margin, border and padding borders must all add up to the width of the containing block (not descendents the way height works). Just one more spec sentence:

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

Aha! So in this case, 50% of width:auto is 50% of the viewport. Hopefully everything finally makes sense now!


Footnotes

* At least, as far it matters in this case. spec All right, everything only kind of makes sense now.

How to pass a single object[] to a params object[]

The params parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params parameter:

1) Calling with an array of the parameter type, in which case the params keyword has no effect and the array is passed directly to the method:

object[] array = new[] { "1", "2" };

// Foo receives the 'array' argument directly.
Foo( array );

2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:

// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );

// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );


In order to pass in an object array to a method with a "params object[]" parameter, you can either:

1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:

Foo( new object[] { array } );  // Equivalent to calling convention 1.

2) Or, cast the argument to object, as mentioned by Adam, in which case the compiler will create the wrapper array for you:

Foo( (object)array );  // Equivalent to calling convention 2.


However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]" parameter. This would allow you to pass multiple arrays as arguments:

void Foo( params object[][] arrays ) {
  foreach( object[] array in arrays ) {
    // process array
  }
}

...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );

// Equivalent to:
object[][] arrays = new[] {
  new[] { "1", "2" },
  new[] { "3", "4" }
};
Foo( arrays );

Edit: Raymond Chen describes this behavior and how it relates to the C# specification in a new post.

How do I fix a Git detached head?

Addendum

If the branch to which you wish to return was the last checkout that you had made, you can simply use checkout @{-1}. This will take you back to your previous checkout.

Further, you can alias this command with, for example, git global --config alias.prev so that you just need to type git prev to toggle back to the previous checkout.

Why do we need to use flatMap?

Simple:

[1,2,3].map(x => [x, x * 10])
// [[1, 10], [2, 20], [3, 30]]

[1,2,3].flatMap(x => [x, x * 10])
// [1, 10, 2, 20, 3, 30]]

Cannot serve WCF services in IIS on Windows 8

Seemed to be a no brainer; the WCF service should be enabled using Programs and Features -> Turn Windows features on or off in the Control Panel. Go to .NET Framework Advanced Services -> WCF Services and enable HTTP Activation as described in this blog post on mdsn.

From the command prompt (as admin), you can run:

C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /FeatureName:WCF-HTTP-Activation45

If you get an error then use the below

C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation
C:\> DISM /Online /Enable-Feature /all /FeatureName:WCF-HTTP-Activation45

dictionary update sequence element #0 has length 3; 2 is required

Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:

It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366

Like in the issue, I ended up just removing the value from the output.

Assign command output to variable in batch file

Okay here some more complex sample for the use of For /F

:: Main
@prompt -$G
    call :REGQUERY  "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"

@goto :EOF

:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\ 
:: for the key and lists its content

    @call :EXEC "REG QUERY  HKCU\%~1"
    @call :EXEC "REG QUERY "HKLM\%~1""

@goto :EOF    

:EXEC
    @set output=

    @for /F "delims=" %%i in ('%~1 2^>nul') do @(
        set output=%%i
    )

    @if not "%output%"=="" (
        echo %1 -^> %output%
    )

@goto :EOF

I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:

  1. the output from the command executed via call :EXEC command is stored in %output%. Batch cmd doesn't cares about scopes so %output% will be also available in the main script.
  2. the @ the beginning is just decoration and there to suppress echoing the command line. You may delete them all and just put some @echo off at the first line is really dislike that. However like this I find debugging much more nice. Decoration Number two is prompt -$G. It's there to make command prompt look like this ->
  3. I use :: instead of rem
  4. the tilde(~) in %~1 is to remove quotes from the first argument
  5. 2^>nul is there to suppress/discard stderr error output. Normally you would do it via 2>nul. Well the ^ the batch escape char is there avoids to early resolving the redirector(>). There's some simulare use a little later in the script: echo %1 -^>... so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.
  6. even if the compare at @if not "%output%"==""looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""-rerun and consider why this doesn't work. ;)

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

How to sum a list of integers with java streams?

From the docs

Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().

Of course, such operations can be readily implemented as simple sequential loops, as in:

int sum = 0;
for (int x : numbers) {
   sum += x;
}

However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:

int sum = numbers.stream().reduce(0, (x,y) -> x+y);

or:

int sum = numbers.stream().reduce(0, Integer::sum);

These reduction operations can run safely in parallel with almost no modification:

int sum = numbers.parallelStream().reduce(0, Integer::sum);

So, for a map you would use:

integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);

Or:

integers.values().stream().reduce(0, Integer::sum);

How can I inspect element in chrome when right click is disabled?

So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

how to reset <input type = "file">

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $('#uploadCaptureInputFile');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS

See How to reset file input with JavaScript for more information.

How to set size for local image using knitr for markdown?

The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:

Resizing local images

As of knitr 1.12, there is the function include_graphics. From ?include_graphics (emphasis mine):

The major advantage of using this function is that it is portable in the sense that it works for all document formats that knitr supports, so you do not need to think if you have to use, for example, LaTeX or Markdown syntax, to embed an external image. Chunk options related to graphics output that work for normal R plots also work for these images, such as out.width and out.height.

Example:

```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```

Advantages:

  • Over agastudy's answer: No need for external libraries or for re-rastering the image.
  • Over Shruti Kapoor's answer: No need to manually write HTML. Besides, the image is included in the self-contained version of the file.

Including generated images

To compose the path to a plot that is generated in a chunk (but not included), the chunk options opts_current$get("fig.path") (path to figure directory) as well as opts_current$get("label") (label of current chunk) may be useful. The following example uses fig.path to include the second of two images which were generated (but not displayed) in the first chunk:

```{r generate_figures, fig.show = "hide"}
library(knitr)
plot(1:10, col = "green")
plot(1:10, col = "red")
```

```{r}
include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path")))
```

The general pattern of figure paths is [fig.path]/[chunklabel]-[i].[ext], where chunklabel is the label of the chunk where the plot has been generated, i is the plot index (within this chunk) and ext is the file extension (by default png in RMarkdown documents).

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

git pull fails "unable to resolve reference" "unable to update local ref"

If git gc --prune=now dosen't help you. (bad luck like me)

What I did is remove the project in local, and re clone the whole project again.

jQuery - add additional parameters on submit (NOT ajax)

In your case it should suffice to just add another hidden field to your form dynamically.

var input = $("<input>").attr("type", "hidden").val("Bla");
$('#form').append($(input));

Difference between HashSet and HashMap?

Differences between HashSet and HashMap in Java

1) First and most significant difference between HashMap and HashSet is that HashMap is an implementation of Map interface while HashSet is an implementation of Set interface, which means HashMap is a key value based data-structure and HashSet guarantees uniqueness by not allowing duplicates.In reality HashSet is a wrapper around HashMap in Java, if you look at the code of add(E e) method of HashSet.java you will see following code :

public boolean add(E e) 
{
    return map.put(e, PRESENT)==null;
}

where its putting Object into map as key and value is an final object PRESENT which is dummy.

2) Second difference between HashMap and HashSet is that , we use add() method to put elements into Set but we use put() method to insert key and value into HashMap in Java.

3) HashSet allows only one null key, but HashMap can allow one null key + multiple null values.

That's all on difference between HashSet and HashMap in Java. In summary HashSet and HashMap are two different type of Collection one being Set and other being Map.

Storing database records into array

$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;
  $c++;
}

for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}

Vagrant shared and synced folders

shared folders VS synced folders

Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf between host and guest (there is known performance issues if there are large numbers of files/directories).

Vagrantfile directory mounted as /vagrant in guest

Vagrant is mounting the current working directory (where Vagrantfile resides) as /vagrant in the guest, this is the default behaviour.

See docs

NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.

You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true in your Vagrantfile.

Why synced folder is not working

Based on the output /tmp on host was NOT mounted during up time.

Use VAGRANT_INFO=debug vagrant up or VAGRANT_INFO=debug vagrant reload to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp on host should be drwxrwxrwt).

I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)

config.vm.synced_folder "/tmp", "/tmp/src"

output

$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src

Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw).

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

JUnit Eclipse Plugin?

Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.

Passing a method as a parameter in Ruby

you also can use "eval", and pass the method as a string argument, and then simply eval it in the other method.

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

C++ static virtual members?

No, this is not possible, because static member functions lack a this pointer. And static members (both functions and variables) are not really class members per-se. They just happen to be invoked by ClassName::member, and adhere to the class access specifiers. Their storage is defined somewhere outside the class; storage is not created each time you instantiated an object of the class. Pointers to class members are special in semantics and syntax. A pointer to a static member is a normal pointer in all regards.

virtual functions in a class needs the this pointer, and is very coupled to the class, hence they can't be static.

Pdf.js: rendering a pdf file using a base64 file source instead of url

from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js

/**
 * This is the main entry point for loading a PDF and interacting with it.
 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
 * is used, which means it must follow the same origin rules that any XHR does
 * e.g. No cross domain requests without CORS.
 *
 * @param {string|TypedAray|object} source Can be an url to where a PDF is
 * located, a typed array (Uint8Array) already populated with data or
 * and parameter object with the following possible fields:
 *  - url   - The URL of the PDF.
 *  - data  - A typed array with PDF data.
 *  - httpHeaders - Basic authentication headers.
 *  - password - For decrypting password-protected PDFs.
 *
 * @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
 */

So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).

But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746

var BASE64_MARKER = ';base64,';

function convertDataURIToBinary(dataURI) {
  var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
  var base64 = dataURI.substring(base64Index);
  var raw = window.atob(base64);
  var rawLength = raw.length;
  var array = new Uint8Array(new ArrayBuffer(rawLength));

  for(var i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

tl;dr

var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)

How do you run `apt-get` in a dockerfile behind a proxy?

UPDATE:

You have wrong capitalization of environment variables in ENV. Correct one is http_proxy. Your example should be:

FROM ubuntu:13.10
ENV http_proxy <HTTP_PROXY>
ENV https_proxy <HTTPS_PROXY>
RUN apt-get update && apt-get upgrade

or

FROM centos
ENV http_proxy <HTTP_PROXY>
ENV https_proxy <HTTPS_PROXY>
RUN yum update 

All variables specified in ENV are prepended to every RUN command. Every RUN command is executed in own container/environment, so it does not inherit variables from previous RUN commands!

Note: There is no need to call docker daemon with proxy for this to work, although if you want to pull images etc. you need to set the proxy for docker deamon too. You can set proxy for daemon in /etc/default/docker in Ubuntu (it does not affect containers setting).


Also, this can happen in case you run your proxy on host (i.e. localhost, 127.0.0.1). Localhost on host differ from localhost in container. In such case, you need to use another IP (like 172.17.42.1) to bind your proxy to or if you bind to 0.0.0.0, you can use 172.17.42.1 instead of 127.0.0.1 for connection from container during docker build.

You can also look for an example here: How to rebuild dockerfile quick by using cache?

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

View is the superclass for all widgets and the OnClickListener interface belongs to this class. All widgets inherit this. View.OnClickListener is the same as OnClickListener. You would have to override the onClick(View view) method from this listener to achieve the action that you want for your button.

To tell Android to listen to click events for a widget, you need to do:

widget.setOnClickListener(this); // If the containing class implements the interface
// Or you can do the following to set it for each widget individually
widget.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something here
    }
});

The 'View' parameter passed in the onClick() method simply lets Android know that a view has been clicked. It can be a Button or a TextView or something else. It is up to you to set an OnClickListener for every widget or to simply make the class containing all these widgets implement the interface. In this case you will have a common onClick() method for all the widgets and all you have to do is to check the id of the view that is passed into the method and then match that against the id for each element that you want and take action for that element.

Java equivalent to C# extension methods

Java does not have such feature. Instead you can either create regular subclass of your list implementation or create anonymous inner class:

List<String> list = new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
};

The problem is to call this method. You can do it "in place":

new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
}.getData();

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

How to retrieve the current value of an oracle sequence without increment it?

I also tried to use CURRVAL, in my case to find out if some process inserted new rows to some table with that sequence as Primary Key. My assumption was that CURRVAL would be the fastest method. But a) CurrVal does not work, it will just get the old value because you are in another Oracle session, until you do a NEXTVAL in your own session. And b) a select max(PK) from TheTable is also very fast, probably because a PK is always indexed. Or select count(*) from TheTable. I am still experimenting, but both SELECTs seem fast.

I don't mind a gap in a sequence, but in my case I was thinking of polling a lot, and I would hate the idea of very large gaps. Especially if a simple SELECT would be just as fast.

Conclusion:

  • CURRVAL is pretty useless, as it does not detect NEXTVAL from another session, it only returns what you already knew from your previous NEXTVAL
  • SELECT MAX(...) FROM ... is a good solution, simple and fast, assuming your sequence is linked to that table

Calling the base constructor in C#

public class Car
{
     public Car(string model)
     {
        Console.WriteLine(model);
     }
}

public class Mercedes : Car
{
     public Mercedes(string model): base(model)
     {

     }
}

Usage:

Mercedes mercedes = new Mercedes("CLA Shooting Brake");

Output: CLA Shooting Brake

Could not commit JPA transaction: Transaction marked as rollbackOnly

As explained @Yaroslav Stavnichiy if a service is marked as transactional spring tries to handle transaction itself. If any exception occurs then a rollback operation performed. If in your scenario ServiceUser.method() is not performing any transactional operation you can use @Transactional.TxType annotation. 'NEVER' option is used to manage that method outside transactional context.

Transactional.TxType reference doc is here.

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

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

Calling a Javascript Function from Console

An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function

//this will fail
$(document).ready(function () {
          myFunction(alert('doing something!'));
          //other stuff
}

To succeed move the function outside the document ready function

//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {

          //other stuff
}

Then in the console window, type the function name with the '()' to execute the function

myFunction()

Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name

function myFunction(alert('doing something!'))

Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.

Jinja2 template variable if None Object set a default value

As addition to other answers, one can write something else if variable is None like this:

{{ variable or '' }}

Java HTTPS client certificate authentication

They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:

  • The client's store will contain the client's private and public key pair. It is called a keystore.
  • The server's store will contain the client's public key. It is called a truststore.

The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.

To set the filesystem locations of the two stores, use the following system properties:

-Djavax.net.ssl.keyStore=clientsidestore.jks

and on the server:

-Djavax.net.ssl.trustStore=serversidestore.jks

To export the client's certificate (public key) to a file, so you can copy it to the server, use

keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks

To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)

keytool -import -file publicclientkey.cer -store serversidestore.jks

Rebase array keys after unsetting elements

Just an additive.

I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."

First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.

Here's my simple, working example:

$array = array(1,2,3,4,5);

for ($i = 0; $i < count($array); $i++) {
    if($array[$i] == 1 || $array[$i] == 2) {
        array_splice($array, $i, 1);
        $i--;
    }
}

Will output:

array(3) {
    [0]=> int(3)
    [1]=> int(4)
    [2]=> int(5)
}

This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:

$files = array(
    array(
        'name' => 'example.zip',
        'size' => '100000000',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '10726556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example.zip',
        'size' => '110726556',
        'type' => 'application/x-zip-compressed',
        'deleteUrl' => 'server/php/?file=example.zip',
        'deleteType' => 'DELETE'
    ),
    array(
        'name' => 'example2.zip',
        'size' => '12356556',
        'type' => 'application/x-zip-compressed',
        'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
        'deleteUrl' => 'server/php/?file=example2.zip',
        'deleteType' => 'DELETE'
    )
);

for ($i = 0; $i < count($files); $i++) {
    if ($i > 0) {
        if (is_array($files[$i-1])) {
            if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
                if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
                $i--;
                array_splice($files, $i, 1);
            }
        }
    }
}

Will output:

array(1) {
    [0]=> array(6) {
            ["name"]=> string(11) "example.zip"
            ["size"]=> string(9) "110726556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
        }
    [1]=> array(6) {
            ["name"]=> string(11) "example2.zip"
            ["size"]=> string(9) "12356556"
            ["type"]=> string(28) "application/x-zip-compressed"
            ["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
            ["deleteType"]=> string(6) "DELETE"
            ["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
        }
}

As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.

Checking if an Android application is running in the background

You should use a shared preference to store the property and act upon it using service binding from your activities. If you use binding only, (that is never use startService), then your service would run only when you bind to it, (bind onResume and unbind onPause) that would make it run on foreground only, and if you do want to work on background you can use the regular start stop service.

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think you are after this:

CONVERT(datetime, date_as_string, 103)

Notice, that datetime hasn't any format. You think about its presentation. To get the data of datetime in an appropriate format you can use

CONVERT(varchar, date_as_datetime, 103)

jquery onclick change css background image

You need to use background-image instead of backgroundImage. For example:

$(function() {
  $('.home').click(function() {
    $(this).css('background-image', 'url(images/tabs3.png)');
  });
}):

How to declare string constants in JavaScript?

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
    Object.defineProperty(Constants , prop, {
      value: value,
      writable: false
   });
};

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

jquery draggable: how to limit the draggable area?

$(function () {
    $( ".droppable-area" ).sortable({
                connectWith: ".connected-sortable",
                containment: ".droppable-area", //(parent div)
                stack: '.connected-sortable div'
            }).disableSelection();
});

Mask for an Input to allow phone numbers?

Angular5 and 6:

angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property

remove host and add @HostListener

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io

Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask

Official documentation link https://angular.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2 and 4:

Plunker >= RC.5

original

One way you could do it is using a directive that injects NgControl and manipulates the value

(for details see inline comments)

@Directive({
  selector: '[ngModel][phone]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMask {
  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    // special handling of backspace necessary otherwise
    // deleting of non-numeric characters is not recognized
    // this laves room for improvement for example if you delete in the 
    // middle of the string
    if (backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    } 

    // don't show braces for empty value
    if (newVal.length == 0) {
      newVal = '';
    } 
    // don't show braces for empty groups at the end
    else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '($1)');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
    } else {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}
@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="form">
    <input type="text" phone [(ngModel)]="data" ngControl="phone"> 
  </form>
  `,
  directives: [PhoneMask]
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      phone: ['']
    })
  }
}

Plunker example <= RC.5

Java compiler level does not match the version of the installed Java project facet

I found @bigleftie's comment above very helpful: "Four things must match

  1. Project->Java Build Path->Libraries->JRE version
  2. Project->Java Compiler-> Compiler Compliance Level
  3. Project->Project Facets->Java->Version
  4. (if using Maven) pom.xml - maven-compiler-plugin artefact source and target".

In my case, in the project properties, Java compiler, the JDK compliance was set to use the workspace settings, which were different from the java version for the project. I clicked on 'Configure Workspace Settings', and changed the workspace Compiler compliance level to what I wanted, and the problem was resolved.

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

Delete all files of specific type (extension) recursively down a directory using a batch file

I don't have enough reputation to add comment, so I posted this as an answer. But for original issue with this command:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

The first For is lacking recursive syntax, it should be:

@echo off
FOR /R %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

You can just do:

FOR %%p IN (C:\Users\0300092544\Downloads\Ces_Sce_600) DO @ECHO %%p

to show the actual output.

Android Studio - Auto complete and other features not working

'The file size (2561270 bytes) exceeds configured limit (2560000 bytes). Code insight features are not available.' 

Had this issue for days with none of these proposed solutions working before eventually getting this message in yellow under the tabs after adding a line of code. Removing the line of code eliminated the message but not the issue. There appears to be a code size window where you lose insight features but don't get this message, at least for me. Once you go over a certain point the message finally pops up. The suggested solution in a different thread for this issue was to edit 'Help/Edit Custom Properties' to increase the configured limit, but just opening this brought up a dialogue asking if I wanted to create an 'idea.properties' folder so I decided not to risk that approach over eventually cutting the file size.

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Code:

private static void RegisterServices(IKernel kernel)
{
    Mock<IProductRepository> mock=new Mock<IProductRepository>();
    mock.Setup(x => x.Products).Returns(new List<Product>
    {
        new Product {Name = "Football", Price = 23},
        new Product {Name = "Surf board", Price = 179},
        new Product {Name = "Running shose", Price = 95}
    });

    kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}        

but see exception.

Changing EditText bottom line color with appcompat v7

This is the easiest and most efficient/reusable/works on all APIs
Create a custom EditText class like so:

public class EditText extends android.widget.EditText {
    public EditText(Context context) {
        super(context);
        init();
    }

    public EditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public EditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        getBackground().mutate().setColorFilter(ContextCompat.getColor(getContext(), R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
    }
}

Then use it like this:

 <company.com.app.EditText
        android:layout_width="200dp"
        android:layout_height="wrap_content"/>

Detecting real time window size changes in Angular 4

@HostListener("window:resize", [])
public onResize() {
  this.detectScreenSize();
}

public ngAfterViewInit() {
    this.detectScreenSize();
}

private detectScreenSize() {
    const height = window.innerHeight;
    const width = window.innerWidth;
}

Is there a minlength validation attribute in HTML5?

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:

autocomplete="off"

<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />

How to make Visual Studio copy a DLL file to the output directory?

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(TargetDir)"

You can also refer to a relative path, the next example will find the DLL in a folder located one level above the project folder. If you have multiple projects that use the DLL in a single solution, this places the source of the DLL in a common area reachable when you set any of them as the Startup Project.

xcopy /y /d  "$(ProjectDir)..\External\*.dll" "$(TargetDir)"

The /y option copies without confirmation. The /d option checks to see if a file exists in the target and if it does only copies if the source has a newer timestamp than the target.

I found that in at least newer versions of Visual Studio, such as VS2109, $(ProjDir) is undefined and had to use $(ProjectDir) instead.

Leaving out a target folder in xcopy should default to the output directory. That is important to understand reason $(OutDir) alone is not helpful.

$(OutDir), at least in recent versions of Visual Studio, is defined as a relative path to the output folder, such as bin/x86/Debug. Using it alone as the target will create a new set of folders starting from the project output folder. Ex: … bin/x86/Debug/bin/x86/Debug.

Combining it with the project folder should get you to the proper place. Ex: $(ProjectDir)$(OutDir).

However $(TargetDir) will provide the output directory in one step.

Microsoft's list of MSBuild macros for current and previous versions of Visual Studio

how do you pass images (bitmaps) between android activities using bundles?

You can pass image in short without using bundle like this This is the code of sender .class file

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher;
Intent intent = new Intent();
Intent.setClass(<Sender_Activity>.this, <Receiver_Activity.class);
Intent.putExtra("Bitmap", bitmap);
startActivity(intent);

and this is receiver class file code.

Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);

No need to compress. that's it

jQuery Find and List all LI elements within a UL within a specific DIV

var column1RelArray = [];
$('#column1 li').each(function(){
    column1RelArray.push($(this).attr('rel'));
});

or fp style

var column1RelArray = $('#column1 li').map(function(){ 
    return $(this).attr('rel'); 
});

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack is a bundler. Like Browserfy it looks in the codebase for module requests (require or import) and resolves them recursively. What is more, you can configure Webpack to resolve not just JavaScript-like modules, but CSS, images, HTML, literally everything. What especially makes me excited about Webpack, you can combine both compiled and dynamically loaded modules in the same app. Thus one get a real performance boost, especially over HTTP/1.x. How exactly you you do it I described with examples here http://dsheiko.com/weblog/state-of-javascript-modules-2017/ As an alternative for bundler one can think of Rollup.js (https://rollupjs.org/), which optimizes the code during compilation, but stripping all the found unused chunks.

For AMD, instead of RequireJS one can go with native ES2016 module system, but loaded with System.js (https://github.com/systemjs/systemjs)

Besides, I would point that npm is often used as an automating tool like grunt or gulp. Check out https://docs.npmjs.com/misc/scripts. I personally go now with npm scripts only avoiding other automation tools, though in past I was very much into grunt. With other tools you have to rely on countless plugins for packages, that often are not good written and not being actively maintained. npm knows its packages, so you call to any of locally installed packages by name like:

{
  "scripts": {
    "start": "npm http-server"
  },
  "devDependencies": {
    "http-server": "^0.10.0"
  }
}

Actually you as a rule do not need any plugin if the package supports CLI.

How to use log levels in java

Logging has different levels such as :
Trace – A fine-grained debug message, typically capturing the flow through the application. Debug- A general debugging event should be logged under this.
ALL – All events could be logged.
INFO- An informational purpose, information written in plain english.
Warn- An event that might possible lead to an error.
Error- An error in the application, possibly recoverable.

Logging captured with debug level is information helpful to developers as well as other personnel, so it captures in broad range. If your code doesn't have exception or errors then you should be alright to use DEBUG level of logging, otherwise you should carefully choose options.

Named parameters in JDBC

You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.

How to avoid Number Format Exception in java?

As always, the Jakarta Commons have at least part of the answer :

NumberUtils.isNumber()

This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...

Bootstrap Datepicker - Months and Years Only

To view the months of the current year, and only the months, use this format - it only takes the months of that year. It can also be restricted so that a certain number of months is displayed.

<input class="form-control" id="txtDateMMyyyy"  autocomplete="off" required readonly/>

<script>
('#txtDateMMyyyy').datetimepicker({
    format: "mm/yyyy",
    startView: "year",
    minView: "year"
}).datetimepicker("setDate", new Date());
</script>

Password must have at least one non-alpha character

I tried Omega's example however it was not working with my C# code. I recommend using this instead:

[RegularExpression(@"^(?=[^\d_].*?\d)\w(\w|[!@#$%]){7,20}", ErrorMessage = @"Error. Password must have one capital, one special character and one numerical character. It can not start with a special character or a digit.")]

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

If you've enabled two factor authentication, then you'll need to generate a personal access token and use that instead of your regular password. More info here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

How can I install Python's pip3 on my Mac?

After upgrading to macOS v10.15 (Catalina), and upgrading all my vEnv modules, pip3 stopped working (gave error: "TypeError: 'module' object is not callable").

I found question 58386953 which led to here and solution.

  1. Exit from the vEnv (I started a fresh shell)
  2. sudo python3 -m pip uninstall pip (this is necessary, but it did not fix problem, because it removed the base Python pip, but it didn't touch my vEnv pip)
  3. sudo easy_install pip (reinstalling pip in base Python, not in vEnv)
  4. cd to your vEnv/bin and type "source activate" to get into vEnv
  5. rm pip pip3 pip3.6 (it seems to be the only way to get rid of the bogus pip's in vEnv)
  6. Now pip is gone from vEnv, and we can use the one in the base Python (I wasn't able to successfully install pip into vEnv after deleting)

Oracle pl-sql escape character (for a " ' ")

Instead of worrying about every single apostrophe in your statement. You can easily use the q' Notation.

Example

SELECT q'(Alex's Tea Factory)' FROM DUAL;

Key Components in this notation are

  • q' which denotes the starting of the notation
  • ( an optional symbol denoting the starting of the statement to be fully escaped.
  • Alex's Tea Factory (Which is the statement itself)
  • )' A closing parenthesis with a apostrophe denoting the end of the notation.

And such that, you can stuff how many apostrophes in the notation without worrying about each single one of them, they're all going to be handled safely.

IMPORTANT NOTE

Since you used ( you must close it with )', and remember it's optional to use any other symbol, for instance, the following code will run exactly as the previous one

SELECT q'[Alex's Tea Factory]' FROM DUAL;

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

What is the difference between "screen" and "only screen" in media queries?

To style for many smartphones with smaller screens, you could write:

@media screen and (max-width:480px) { … } 

To block older browsers from seeing an iPhone or Android phone style sheet, you could write:

@media only screen and (max-width: 480px;) { … } 

Read this article for more http://webdesign.about.com/od/css3/a/css3-media-queries.htm

Eclipse error ... cannot be resolved to a type

Project -> Clean

can at least sometimes be sufficient to resolve the matter.

MySQL - Get row number on select

It's now builtin in MySQL 8.0 and MariaDB 10.2:

SELECT
  itemID, COUNT(*) as ordercount,
  ROW_NUMBER OVER (PARTITION BY itemID ORDER BY rank DESC) as rank
FROM orders
GROUP BY itemID ORDER BY rank DESC

Reading a List from properties file and load with spring annotation @Value

In my case of a list of integers works this:

@Value("#{${my.list.of.integers}}")
private List<Integer> listOfIntegers;

Property file:

my.list.of.integers={100,200,300,400,999}

How can I conditionally require form inputs with AngularJS?

Simple you can use angular validation like :

 <input type='text'
   name='name'
   ng-model='person.name'
   ng-required='!person.lastname'/>

   <input type='text'
   name='lastname'
   ng-model='person.lastname'             
   ng-required='!person.name' /> 

You can now fill the value in only one text field. Either you can fill name or lastname. In this way you can use conditional required fill in AngularJs.

Find specific string in a text file with VBS script

I'd recommend using a regular expressions instead of string operations for this:

Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\VBS\filediprova.txt"

newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"

Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global  = False
re.IgnoreCase = True

text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")

The regular expression will match a line feed (\n) followed by a line containing the string Test Case followed by a number (\d), and the replacement will prepend that with the text you want to insert (variable newtext). Setting re.Global = False makes the replacement stop after the first match.

If the line breaks in your text file are encoded as CR-LF (carriage return + line feed) you'll have to change \n into \r\n and vbLf into vbCrLf.

If you have to modify several text files, you could do it in a loop like this:

For Each f In fso.GetFolder("C:\VBS").Files
  If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
    text = f.OpenAsTextStream.ReadAll
    f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
  End If
Next

BeanFactory vs ApplicationContext

ApplicationContext: It loads spring beans configured in spring configuration file,and manages the life cycle of the spring bean as and WHEN CONTAINER STARTS.It won't wait until getBean("springbeanref") is called.

BeanFactory It loads spring beans configured in spring configuration file,manages the life cycle of the spring bean when we call the getBean("springbeanref").So when we call the getBean("springbeanref") at the time of spring bean life cycle starts.

How to remove underline from a name on hover

Remove the text decoration for the anchor tag

<a name="Section 1" style="text-decoration : none">Section</a>

Xcode Debugger: view value of variable

I agree with other posters that Xcode as a developing environment should include an easy way to debug variables. Well, good news, there IS one!

After searching and not finding a simple answer/tutorial on how to debug variables in Xcode I went to explore with Xcode itself and found this (at least for me) very useful discovery.

How to easily debug your variables in Xcode 4.6.3

In the main screen of Xcode make sure to see the bottom Debug Area by clicking the upper-right corner button showed in the screenshot.

Debug Area button

Debug Area in Xcode 4.6.3

Now set a Breakpoint – the line in your code where you want your program to pause, by clicking the border of your Code Area.

Breakpoint

Now in the Debug Area look for this buttons and click the one in the middle. You will notice your area is now divided in two.

Split Debug Area

Should look like this

Now run your application.

When the first Breakpoint is reached during the execution of your program you will see on the left side all your variables available at that breakpoint.

Search Field

You can expand the left arrows on the variable for a greater detail. And even use the search field to isolate that variable you want and see it change on real time as you "Step into" the scope of the Breakpoint.

Step Into

On the right side of your Debug Area you can send to print the variables as you desire using the mouse's right-button click over the desired variable.

Contextual Menu

As you can see, that contextual menu is full of very interesting debugging options. Such as Watch that has been already suggested with typed commands or even Edit Value… that changes the runtime value of your variable!

How to find foreign key dependencies in SQL Server?

You can Use INFORMATION_SCHEMA.KEY_COLUMN_USAGE and sys.foreign_key_columns in order to get the foreign key metadata for a table i.e. Constraint name, Reference table and Reference column etc.

Below is the query:

SELECT  CONSTRAINT_NAME, COLUMN_NAME, ParentTableName, RefTableName,RefColName FROM 
    (SELECT CONSTRAINT_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = '<tableName>') constraint_details
    INNER JOIN  
    (SELECT ParentTableName, RefTableName,name ,COL_NAME(fc.referenced_object_id,fc.referenced_column_id) RefColName  FROM (SELECT object_name(parent_object_id) ParentTableName,object_name(referenced_object_id) RefTableName,name,OBJECT_ID  FROM sys.foreign_keys WHERE parent_object_id = object_id('<tableName>') ) f 
    INNER JOIN   
    sys.foreign_key_columns AS fc  ON  f.OBJECT_ID = fc.constraint_object_id ) foreign_key_detail 
    on foreign_key_detail.name = constraint_details.CONSTRAINT_NAME

C/C++ include header file order

I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:

#include <set>
#include <vector>
#include <algorithm>
#include <functional>

I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:

Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.

m2e error in MavenArchiver.getManifest()

I encountered the same issue after updating the maven-jar-plugin to its latest version (at the time of writing), 3.0.2.
Eclipse 4.5.2 started flagging the pom.xml file with the org.apache.maven.archiver.MavenArchiver.getManifest error and a Maven > Update Project.. would not fix it.

Easy solution: downgrade to 2.6 version
Indeed a possible solution is to get back to version 2.6, a further update of the project would then remove any error. However, that's not the ideal scenario and a better solution is possible: update the m2e extensions (Eclipse Maven integration).

Better solution: update Eclipse m2e extensions
From Help > Install New Software.., add a new repository (via the Add.. option), pointing to the following URL:

  • https://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/

Then follow the update wizard as usual. Eclipse would then require a restart. Afterwards, a further Update Project.. on the concerned Maven project would remove any error and your Maven build could then enjoy the benefit of the latest maven-jar-plugin version.


Additonal notes
The reason for this issue is that from version 3.0.0 on, the concerned component, the maven-archiver and the related plexus-archiver has been upgraded to newer versions, breaking internal usages (via reflections) of the m2e integration in Eclipse. The only solution is then to properly update Eclipse, as described above.
Also note: while Eclipse would initially report errors, the Maven build (e.g. from command line) would keep on working perfectly, this issue is only related to the Eclipse-Maven integration, that is, to the IDE.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Go back from classpath 'com.android.tools.build:gradle:3.3.0-alpha13' to classpath 'com.android.tools.build:gradle:3.2.0'

this worked for me

How to add custom method to Spring Data JPA

Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.

public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {

    private BrandRepository myRepository;

    public MyBean findOne(int first, int second) {
        return myRepository.findOne(new Id(first, second));
    }

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        myRepository = beanFactory.getBean(MyRepository.class);
    }
}

Nested routes with react router v4 / v5

React Router v6

allows to use both nested routes (like in v3) and separate, splitted routes (v4, v5).

Nested Routes

Keep all routes in one place for small/medium size apps:

<Routes>
  <Route path="/" element={<Home />} >
    <Route path="user" element={<User />} /> 
    <Route path="dash" element={<Dashboard />} /> 
  </Route>
</Routes>

_x000D_
_x000D_
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        // /js is start path of stack snippet
        <Route path="/js" element={<Home />} >
          <Route path="user" element={<User />} />
          <Route path="dash" element={<Dashboard />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

const Home = () => {
  const location = useLocation()
  return (
    <div>
      <p>URL path: {location.pathname}</p>
      <Outlet />
      <p>
        <Link to="user" style={{paddingRight: "10px"}}>user</Link>
        <Link to="dash">dashboard</Link>
      </p>
    </div>
  )
}

const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<div id="root"></div>
    <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/history.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router-dom.production.min.js"></script>
    <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
_x000D_
_x000D_
_x000D_

Alternative: Define your routes as plain JavaScript objects via useRoutes.

Separate Routes

You can use separates routes to meet requirements of larger apps like code splitting:

// inside App.jsx:
<Routes>
  <Route path="/*" element={<Home />} />
</Routes>

// inside Home.jsx:
<Routes>
  <Route path="user" element={<User />} />
  <Route path="dash" element={<Dashboard />} />
</Routes>

_x000D_
_x000D_
const App = () => {
  return (
    <BrowserRouter>
      <Routes>
        // /js is start path of stack snippet
        <Route path="/js/*" element={<Home />} />
      </Routes>
    </BrowserRouter>
  );
}

const Home = () => {
  const location = useLocation()
  return (
    <div>
      <p>URL path: {location.pathname}</p>
      <Routes>
        <Route path="user" element={<User />} />
        <Route path="dash" element={<Dashboard />} />
      </Routes>
      <p>
        <Link to="user" style={{paddingRight: "5px"}}>user</Link>
        <Link to="dash">dashboard</Link>
      </p>
    </div>
  )
}

const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<div id="root"></div>
    <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/history.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router.production.min.js"></script>
    <script src="https://unpkg.com/[email protected]/umd/react-router-dom.production.min.js"></script>
    <script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
_x000D_
_x000D_
_x000D_

How to delete large data of table in SQL without log?

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

How can I reload .emacs after changing it?

The following should do it...

M-x load-file

Angular 1 - get current URL parameters

You could inject $routeParams to your controller and access all the params that where used when the route was resolved.

E.g.:

// route was: app.dev/backend/:type/:id

function MyCtrl($scope, $routeParams, $log) {
    // use the params
    $log.info($routeParams.type, $routeParams.id);
};

See angular $routeParams documentation for further information.

Why does Node.js' fs.readFile() return a buffer instead of string?

It is returning a Buffer object.

If you want it in a string, you can convert it with data.toString():

var fs = require("fs");

fs.readFile("test.txt", function (err, data) {
    if (err) throw err;
    console.log(data.toString());
});

Select data from date range between two dates

SELECT * FROM Product_sales 
WHERE From_date between '2013-01-03'
AND '2013-01-09'

What does the percentage sign mean in Python

The modulus operator. The remainder when you divide two number.

For Example:

>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3

Executing command line programs from within python

This whole setup seems a little unstable to me.

Talk to the ffmpegx folks about having a GUI front-end over a command-line backend. It doesn't seem to bother them.

Indeed, I submit that a GUI (or web) front-end over a command-line backend is actually more stable, since you have a very, very clean interface between GUI and command. The command can evolve at a different pace from the web, as long as the command-line options are compatible, you have no possibility of breakage.

How do I make the first letter of a string uppercase in JavaScript?

CSS only

If the transformation is needed only for displaying on a web page:

p::first-letter {
  text-transform: uppercase;
}
  • Despite being called "::first-letter", it applies to the first character, i.e. in case of string %a, this selector would apply to % and as such a would not be capitalized.
  • In IE9+ or IE5.5+ it's supported in legacy notation with only one colon (:first-letter).

ES2015 one-liner

const capitalizeFirstChar = str => str.charAt(0).toUpperCase() + str.substring(1);

Remarks

  • In the benchmark I performed, there was no significant difference between string.charAt(0) and string[0]. Note however, that string[0] would be undefined for an empty string, so the function would have to be rewritten to use "string && string[0]", which is way too verbose, compared to the alternative.
  • string.substring(1) is faster than string.slice(1).

Benchmark between substring() and slice()

The difference is rather minuscule nowadays (run the test yourself):

  • 21,580,613.15 ops/s ±1.6% for substring(),
  • 21,096,394.34 ops/s ±1.8% (2.24% slower) for slice().

Solutions' comparison

WP -- Get posts by category?

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

Could not install packages due to an EnvironmentError: [Errno 13]

I already tried all suggestion posted in here, yet I'm still getting the errno 13,

I'm using Windows and my python version is 3.7.3

After 5 hours of trying to solve it, this step worked for me:

I try to open the command prompt by run as administrator

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Google Maps API v3: How to remove all markers?

Most voted answer at top is correct but in case if you have only one marker at a time (like I had in my situation) and every time you need to kill the previous location of that marker and add a new one then you don't need to create whole array of markers and manage it on every push and pop, you can simply just create a variable to store your marker's previous location and can set that to null on creation of new one.

// Global variable to hold marker location.

var previousMarker;

//while adding a new marker

    if(previousMarker != null)
previousMarker.setMap(null);

var marker = new google.maps.Marker({map: resultsMap, position: new google.maps.LatLng(lat_, lang_)});
previousMarker = marker;

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

How to achieve function overloading in C?

Leushenko's answer is really cool - solely: the foo example does not compile with GCC, which fails at foo(7), stumbling over the FIRST macro and the actual function call ((_1, __VA_ARGS__), remaining with a surplus comma. Additionally, we are in trouble if we want to provide additional overloads, such as foo(double).

So I decided to elaborate the answer a little further, including to allow a void overload (foo(void) – which caused quite some trouble...).

Idea now is: Define more than one generic in different macros and let select the correct one according to the number of arguments!

Number of arguments is quite easy, based on this answer:

#define foo(...) SELECT(__VA_ARGS__)(__VA_ARGS__)

#define SELECT(...) CONCAT(SELECT_, NARG(__VA_ARGS__))(__VA_ARGS__)
#define CONCAT(X, Y) CONCAT_(X, Y)
#define CONCAT_(X, Y) X ## Y

That's nice, we resolve to either SELECT_1 or SELECT_2 (or more arguments, if you want/need them), so we simply need appropriate defines:

#define SELECT_0() foo_void
#define SELECT_1(_1) _Generic ((_1),    \
        int: foo_int,                   \
        char: foo_char,                 \
        double: foo_double              \
)
#define SELECT_2(_1, _2) _Generic((_1), \
        double: _Generic((_2),          \
                int: foo_double_int     \
        )                               \
)

OK, I added the void overload already – however, this one actually is not covered by the C standard, which does not allow empty variadic arguments, i. e. we then rely on compiler extensions!

At very first, an empty macro call (foo()) still produces a token, but an empty one. So the counting macro actually returns 1 instead of 0 even on empty macro call. We can "easily" eliminate this problem, if we place the comma after __VA_ARGS__ conditionally, depending on the list being empty or not:

#define NARG(...) ARG4_(__VA_ARGS__ COMMA(__VA_ARGS__) 4, 3, 2, 1, 0)

That looked easy, but the COMMA macro is quite a heavy one; fortunately, the topic is already covered in a blog of Jens Gustedt (thanks, Jens). Basic trick is that function macros are not expanded if not followed by parentheses, for further explanations, have a look at Jens' blog... We just have to modify the macros a little to our needs (I'm going to use shorter names and less arguments for brevity).

#define ARGN(...) ARGN_(__VA_ARGS__)
#define ARGN_(_0, _1, _2, _3, N, ...) N
#define HAS_COMMA(...) ARGN(__VA_ARGS__, 1, 1, 1, 0)

#define SET_COMMA(...) ,

#define COMMA(...) SELECT_COMMA             \
(                                           \
        HAS_COMMA(__VA_ARGS__),             \
        HAS_COMMA(__VA_ARGS__ ()),          \
        HAS_COMMA(SET_COMMA __VA_ARGS__),   \
        HAS_COMMA(SET_COMMA __VA_ARGS__ ()) \
)

#define SELECT_COMMA(_0, _1, _2, _3) SELECT_COMMA_(_0, _1, _2, _3)
#define SELECT_COMMA_(_0, _1, _2, _3) COMMA_ ## _0 ## _1 ## _2 ## _3

#define COMMA_0000 ,
#define COMMA_0001
#define COMMA_0010 ,
// ... (all others with comma)
#define COMMA_1111 ,

And now we are fine...

The complete code in one block:

/*
 * demo.c
 *
 *  Created on: 2017-09-14
 *      Author: sboehler
 */

#include <stdio.h>

void foo_void(void)
{
    puts("void");
}
void foo_int(int c)
{
    printf("int: %d\n", c);
}
void foo_char(char c)
{
    printf("char: %c\n", c);
}
void foo_double(double c)
{
    printf("double: %.2f\n", c);
}
void foo_double_int(double c, int d)
{
    printf("double: %.2f, int: %d\n", c, d);
}

#define foo(...) SELECT(__VA_ARGS__)(__VA_ARGS__)

#define SELECT(...) CONCAT(SELECT_, NARG(__VA_ARGS__))(__VA_ARGS__)
#define CONCAT(X, Y) CONCAT_(X, Y)
#define CONCAT_(X, Y) X ## Y

#define SELECT_0() foo_void
#define SELECT_1(_1) _Generic ((_1), \
        int: foo_int,                \
        char: foo_char,              \
        double: foo_double           \
)
#define SELECT_2(_1, _2) _Generic((_1), \
        double: _Generic((_2),          \
                int: foo_double_int     \
        )                               \
)

#define ARGN(...) ARGN_(__VA_ARGS__)
#define ARGN_(_0, _1, _2, N, ...) N

#define NARG(...) ARGN(__VA_ARGS__ COMMA(__VA_ARGS__) 3, 2, 1, 0)
#define HAS_COMMA(...) ARGN(__VA_ARGS__, 1, 1, 0)

#define SET_COMMA(...) ,

#define COMMA(...) SELECT_COMMA             \
(                                           \
        HAS_COMMA(__VA_ARGS__),             \
        HAS_COMMA(__VA_ARGS__ ()),          \
        HAS_COMMA(SET_COMMA __VA_ARGS__),   \
        HAS_COMMA(SET_COMMA __VA_ARGS__ ()) \
)

#define SELECT_COMMA(_0, _1, _2, _3) SELECT_COMMA_(_0, _1, _2, _3)
#define SELECT_COMMA_(_0, _1, _2, _3) COMMA_ ## _0 ## _1 ## _2 ## _3

#define COMMA_0000 ,
#define COMMA_0001
#define COMMA_0010 ,
#define COMMA_0011 ,
#define COMMA_0100 ,
#define COMMA_0101 ,
#define COMMA_0110 ,
#define COMMA_0111 ,
#define COMMA_1000 ,
#define COMMA_1001 ,
#define COMMA_1010 ,
#define COMMA_1011 ,
#define COMMA_1100 ,
#define COMMA_1101 ,
#define COMMA_1110 ,
#define COMMA_1111 ,

int main(int argc, char** argv)
{
    foo();
    foo(7);
    foo(10.12);
    foo(12.10, 7);
    foo((char)'s');

    return 0;
}

How to make <a href=""> link look like a button?

Something like this would resemble a button:

a.LinkButton {
  border-style: solid;
  border-width : 1px 1px 1px 1px;
  text-decoration : none;
  padding : 4px;
  border-color : #000000
}

See http://jsfiddle.net/r7v5c/1/ for an example.

TimePicker Dialog from clicking EditText

I extended the nice reusable solution of @Sumoanand to support both focus change and click listeners when changing the time multiple times. Also updating the picker calendar to remember the last selected time + formatting HH:mm

public class TimeSetter implements View.OnFocusChangeListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener {

    private EditText mEditText;
    private Calendar mCalendar;
    private SimpleDateFormat mFormat;

    public TimeSetter(EditText editText){
       this.mEditText = editText;
       mEditText.setOnFocusChangeListener(this);
       mEditText.setOnClickListener(this);
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus){
            showPicker(view);
        }
    }

    @Override
    public void onClick(View view) {
        showPicker(view);
    }

    private void showPicker(View view) {
        if (mCalendar == null)
            mCalendar = Calendar.getInstance();

        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);

        new TimePickerDialog(view.getContext(), this, hour, minute, true).show();
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        mCalendar.set(Calendar.MINUTE, minute);

        if (mFormat == null)
            mFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

        this.mEditText.setText(mFormat.format(mCalendar.getTime()));
    }

}

Usage from onCreate:

EditText timeEditText = (EditText) rootView.findViewById(R.id.timeText);
new TimeSetter(timeEditText);

How to add a TextView to a LinearLayout dynamically in Android?

Here is a more general answer for future viewers of this question. The layout we will make is below:

enter image description here

Method 1: Add TextView to existing LinearLayout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamic_linearlayout);

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

    // Add textview 1
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    // Add textview 2
    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);
}

Note that for LayoutParams you must specify the kind of layout for the import, as in

import android.widget.LinearLayout.LayoutParams;

Otherwise you need to use LinearLayout.LayoutParams in the code.

Here is the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff99ccff"
    android:orientation="vertical" >

</LinearLayout>

Method 2: Create both LinearLayout and TextView programmatically

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // NOTE: setContentView is below, not here

    // Create new LinearLayout
    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setBackgroundColor(0xff99ccff);

    // Add textviews
    TextView textView1 = new TextView(this);
    textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    textView1.setText("programmatically created TextView1");
    textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
    textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
    linearLayout.addView(textView1);

    TextView textView2 = new TextView(this);
    LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layoutParams.gravity = Gravity.RIGHT;
    layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
    textView2.setLayoutParams(layoutParams);
    textView2.setText("programmatically created TextView2");
    textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
    linearLayout.addView(textView2);

    // Set context view
    setContentView(linearLayout);
}

Method 3: Programmatically add one xml layout to another xml layout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamic_linearlayout);

    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
            Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
    FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
    container.addView(view);
}

Here is dynamic_linearlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

And here is the dynamic_linearlayout_item.xml to add:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff99ccff"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff66ff66"
        android:padding="20px"
        android:text="programmatically created TextView1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ffffdbdb"
        android:layout_gravity="right"
        android:layout_margin="10px"
        android:textSize="18sp"
        android:text="programmatically created TextView2" />

</LinearLayout>

How does Java deal with multiple conditions inside a single IF statement

Yes,that is called short-circuiting.

Please take a look at this wikipedia page on short-circuiting

Representing null in JSON

This is a personal and situational choice. The important thing to remember is that the empty string and the number zero are conceptually distinct from null.

In the case of a count you probably always want some valid number (unless the count is unknown or undefined), but in the case of strings, who knows? The empty string could mean something in your application. Or maybe it doesn't. That's up to you to decide.

Where do I find the bashrc file on Mac?

~/.bashrc is already a path to .bashrc.

If you do echo ~ you'll see that it's a path to your home directory.

Homebrew directory is /usr/local/bin. Homebrew is installed inside it and everything installed by homebrew will be installed there.

For example, if you do brew install python Homebrew will put Python binary in /usr/local/bin.

Finally, to add Homebrew directory to your path you can run echo "export PATH=/usr/local/lib:$PATH" >> ~/.bashrc. It will create .bashrc file if it doesn't exist and then append the needed line to the end.

You can check the result by running tail ~/.bashrc.

Bootstrap 3 Navbar Collapse

The nabvar will collapse on small devices. The point of collapsing is defined by @grid-float-breakpoint in variables. By default this will by before 768px. For screens below the 768 pixels screen width, the navbar will look like:

enter image description here

It's possible to change the @grid-float-breakpoint in variables.less and recompile Bootstrap. When doing this you also will have to change @screen-xs-max in navbar.less. You will have to set this value to your new @grid-float-breakpoint -1. See also: https://github.com/twbs/bootstrap/pull/10465. This is needed to change navbar forms and dropdowns at the @grid-float-breakpoint to their mobile version too.

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

You need the Apache Commons Codec library 1.4 or above in your classpath. This library contains Base64 implementation.

How can I specify the required Node.js version in package.json?

.nvmrc

If you are using NVM like this, which you likely should, then you can indicate the nodejs version required for given project in a git-tracked .nvmrc file:

echo v10.15.1 > .nvmrc

This does not take effect automatically on cd, which is sane: the user must then do a:

nvm use

and now that version of node will be used for the current shell.

You can list the versions of node that you have with:

nvm list

.nvmrc is documented at: https://github.com/creationix/nvm/tree/02997b0753f66c9790c6016ed022ed2072c22603#nvmrc

How to automatically select that node version on cd was asked at: Automatically switch to correct version of Node based on project

Tested with NVM 0.33.11.

Capitalize the first letter of both words in a two word string

From the help page for ?toupper:

.simpleCap <- function(x) {
    s <- strsplit(x, " ")[[1]]
    paste(toupper(substring(s, 1,1)), substring(s, 2),
          sep="", collapse=" ")
}


> sapply(name, .simpleCap)

zip code         state   final count 
"Zip Code"       "State" "Final Count"

How to export/import PuTTy sessions list?

Example:
How to transfer putty configuration and session configuration from one user account to another e.g. when created a new account and want to use the putty sessions/configurations from the old account

Process:
- Export registry key from old account into a file
- Import registry key from file into new account

Export reg key: (from OLD account)

  1. Login into the OLD account e.g. tomold
  2. Open normal 'command prompt' (NOT admin !)
  3. Type 'regedit'
  4. Navigate to registry section where the configuration is being stored e.g. [HKEY_CURRENT_USER\SOFTWARE\SimonTatham] and click on it
  5. Select 'Export' from the file menu or right mouse click (radio ctrl 'selected branch')
  6. Save into file and name it e.g. 'puttyconfig.reg'
  7. Logout again

Import reg key: (into NEW account)

  1. Login into NEW account e.g. tom

  2. Open normal 'command prompt' (NOT admin !)

  3. Type 'regedit'

  4. Select 'Import' from the menu

  5. Select the registry file to import e.g. 'puttyconfig.reg'

  6. Done

Note:
Do not use an 'admin command prompt' as settings are located under '[HKEY_CURRENT_USER...] 'and regedit would run as admin and show that section for the admin-user rather then for the user to transfer from and/or to.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

How to enable PHP short tags?

 short_open_tag = On

in php.ini And restart your Apache Server.

What is so bad about singletons?

I'm not going to comment on the good/evil argument, but I haven't used them since Spring came along. Using dependency injection has pretty much removed my requirements for singleton, servicelocators and factories. I find this a much more productive and clean environment, at least for the type of work I do (Java-based web applications).

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

What is tail recursion?

Here is a quick code snippet comparing two functions. The first is traditional recursion for finding the factorial of a given number. The second uses tail recursion.

Very simple and intuitive to understand.

An easy way to tell if a recursive function is a tail recursive is if it returns a concrete value in the base case. Meaning that it doesn't return 1 or true or anything like that. It will more than likely return some variant of one of the method parameters.

Another way is to tell is if the recursive call is free of any addition, arithmetic, modification, etc... Meaning its nothing but a pure recursive call.

public static int factorial(int mynumber) {
    if (mynumber == 1) {
        return 1;
    } else {            
        return mynumber * factorial(--mynumber);
    }
}

public static int tail_factorial(int mynumber, int sofar) {
    if (mynumber == 1) {
        return sofar;
    } else {
        return tail_factorial(--mynumber, sofar * mynumber);
    }
}

How to increase font size in a plot in R?

Notice that "cex" does change things when the plot is made with text. For example, the plot of an agglomerative hierarchical clustering:

library(cluster)
data(votes.repub)
agn1 <- agnes(votes.repub, metric = "manhattan", stand = TRUE)
plot(agn1, which.plots=2)

will produce a plot with normal sized text:

enter image description here

and plot(agn1, which.plots=2, cex=0.5) will produce this one:

enter image description here

How do I get the last word in each line with bash

Another way of doing this in plain bash is making use of the rev command like this:

cat file | rev | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","

Basically, you reverse the lines of the file, then split them with cut using space as the delimiter, take the first field that cut produces and then you reverse the token again, use tr -d to delete unwanted chars and tr again to replace newline chars with ,

Also, you can avoid the first cat by doing:

rev < file | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","

HTTP Basic: Access denied fatal: Authentication failed

When it asks for username and password. Just add gitlab user name and password for clonning. For the box to pop up asking credentials, do the following:

go to "control panel"-> user accounts-> manage credentials->windows credentials->git:https://[email protected]>click on down arrow-> then click remove.

Hope this helps!

Angular 2 - Redirect to an external URL and open in a new tab

I want to share with you one more solution if you have absolute part in the URL

SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}

HTML:

<button (click)="onNavigate()">Google</button>

TypeScript:

onNavigate()
{
    let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
    window.open(link, "_blank");
}

and url will be opened in new tab.

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

Parsing a JSON string in Ruby

Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
  p shop["id"]
end

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)

This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.

To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off

Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

file_get_contents() how to fix error "Failed to open stream", "No such file"

Why don't you use cURL ?

$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth); 
print_r($json);
}
}

in python how do I convert a single digit number into a double digits string?

Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.

My approach is to leave number as a number until the moment you want to convert it into string:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011

Getting all documents from one collection in Firestore

Try following LOCs

    let query = firestore.collection('events');
    let response = [];
    await query.get().then(querySnapshot => {
          let docs = querySnapshot.docs;
          for (let doc of docs) {
              const selectedEvent = {
                     id: doc.id,
                     item: doc.data().event
                  };
             response.push(selectedEvent);
          }
   return response;

Custom domain for GitHub project pages

I just discovered, after a bit of frustration, that if you're using PairNIC, all you have to do is enable the "Web Forwarding" setting under "Custom DNS" and supply the username.github.io/project address and it will automatically set up both the apex and subdomain records for you. It appears to do exactly what's suggested in the accepted answer. However, it won't let you do the exact same thing by manually adding records. Very strange. Anyway, it took me a while to figure that out, so I thought I'd share to save everyone else the trouble.

Convert Pixels to Points

Height lines converted into points and pixel (my own formula). Here is an example with a manual entry of 213.67 points in the Row Height field:

213.67  Manual Entry    
  0.45  Add 0.45    
214.12  Subtotal    
213.75  Round to a multiple of 0.75 
213.00  Subtract 0.75 provides manual entry converted by Excel  
284.00  Divide by 0.75 gives the number of pixels of height

Here the manual entry of 213.67 points gives 284 pixels.
Here the manual entry of 213.68 points gives 285 pixels.

(Why 0.45? I do not know but it works.)

Rename multiple files by replacing a particular pattern in the filenames using a shell script

You can use rename utility to rename multiple files by a pattern. For example following command will prepend string MyVacation2011_ to all the files with jpg extension.

rename 's/^/MyVacation2011_/g' *.jpg

or

rename <pattern> <replacement> <file-list>

Remove menubar from Electron app

According to the official documentation @ https://github.com/electron/electron/blob/v8.0.0-beta.1/docs/api/menu.md the proper way to do this now since 7.1.2 and I have tested it on 8.0 as well is to :

const { app, Menu } = require('electron')

Menu.setApplicationMenu(null)

Xcode warning: "Multiple build commands for output file"

In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project. Look in the "Copy Bundle Resources" Build Phase. You should find the offending files in that list twice. Delete the duplicate reference.

Xcode is complaining that you are trying to bundle the same file with your application two times.

Combine Regexp?

Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.

Jquery select this + class

Use find()

$(this).find(".subclass").css("visibility","visible");

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

This is specific for each site. So if you type that once, you will only get through that site and all other sites will need a similar type-through.

It is also remembered for that site and you have to click on the padlock to reset it (so you can type it again):

enter image description here

Needless to say use of this "feature" is a bad idea and is unsafe - hence the name.

You should find out why the site is showing the error and/or stop using it until they fix it. HSTS specifically adds protections for bad certs to prevent you clicking through them. The fact it's needed suggests there is something wrong with the https connection - like the site or your connection to it has been hacked.

The chrome developers also do change this periodically. They changed it recently from badidea to thisisunsafe so everyone using badidea, suddenly stopped being able to use it. You should not depend on it. As Steffen pointed out in the comments below, it is available in the code should it change again though they now base64 encode it to make it more obscure. The last time they changed they put this comment in the commit:

Rotate the interstitial bypass keyword

The security interstitial bypass keyword hasn't changed in two years and awareness of the bypass has been increased in blogs and social media. Rotate the keyword to help prevent misuse.

I think the message from the Chrome team is clear - you should not use it. It would not surprise me if they removed it completely in future.

If you are using this when using a self-signed certificate for local testing then why not just add your self-signed certificate certificate to your computer's certificate store so you get a green padlock and do not have to type this? Note Chrome insists on a SAN field in certificates now so if just using the old subject field then even adding it to the certificate store will not result in a green padlock.

If you leave the certificate untrusted then certain things do not work. Caching for example is completely ignored for untrusted certificates. As is HTTP/2 Push.

HTTPS is here to stay and we need to get used to using it properly - and not bypassing the warnings with a hack that is liable to change and doesn't work the same as a full HTTPS solution.

Label word wrapping

Ironically, turning off AutoSize by setting it to false allowed me to get the label control dimensions to size it both vertically and horizontally which effectively allows word-wrapping to occur.

Add Text on Image using PIL

With Pillow, you can also draw on an image using the ImageDraw module. You can draw lines, points, ellipses, rectangles, arcs, bitmaps, chords, pieslices, polygons, shapes and text.

from PIL import Image, ImageDraw
blank_image = Image.new('RGBA', (400, 300), 'white')
img_draw = ImageDraw.Draw(blank_image)
img_draw.rectangle((70, 50, 270, 200), outline='red', fill='blue')
img_draw.text((70, 250), 'Hello World', fill='green')
blank_image.save('drawn_image.jpg')

we create an Image object with the new() method. This returns an Image object with no loaded image. We then add a rectangle and some text to the image before saving it.

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Support for the experimental syntax 'classProperties' isn't currently enabled

In my work environment root, .babelrc file was not there. However, following entry in package.json solved the issue.

"babel": {
"presets": [
  "@babel/preset-env",
  "@babel/preset-react"
],
"plugins": [
  "@babel/plugin-proposal-class-properties"
]}

Note: Don't forget to exit the console and reopen before executing the npm or yarn commands.

Add timer to a Windows Forms application

Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html

Then add a button or something on the form and inside its event, just open this app ie:

{

Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");

}

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I have found some solution after so much googling. You can also try it if tired to search for a good solution.

For common using SOAP API

You need username and password to make SOAP request on https://www.livedocx.com

Make registration using this https://www.livedocx.com/user/account_registration.aspx and follow the steps accordingly.

Use below code in your .php file.

ini_set ('soap.wsdl_cache_enabled', 0);

// you will get this username and pass while register
define ('USERNAME', 'Username'); 
define ('PASSWORD', 'Password');

// SOAP WSDL endpoint
define ('ENDPOINT', 'https://api.livedocx.com/2.1/mailmerge.asmx?wsdl');
 
// Define timezone
date_default_timezone_set('Europe/Berlin');
$soap = new SoapClient(ENDPOINT);
$soap->LogIn(
    array(
        'username' => USERNAME,
        'password' => PASSWORD
    )
);
$data = file_get_contents('test.doc');
$soap->SetLocalTemplate(
    array(
        'template' => base64_encode($data),
        'format'   => 'doc'
    )
);
$soap->CreateDocument();
$result = $soap->RetrieveDocument(
    array(
        'format' => 'pdf'
    )
);
$data = $result->RetrieveDocumentResult;
file_put_contents('tree.pdf', base64_decode($data));
$soap->LogOut();
unset($soap);

Follow this link for more information http://www.phplivedocx.org/

For Ubuntu

OpenOffice and Unoconv installation Required.

from command prompt

apt-get remove --purge unoconv
git clone https://github.com/dagwieers/unoconv
cd unoconv
sudo make install

Now add below code in your PHP script and make sure file should be executable.

shell_exec('/usr/bin/unoconv -f pdf  folder/test.docx');
shell_exec('/usr/bin/unoconv -f pdf  folder/sachin.png');

Hope this solution help you.

How do I generate a random integer between min and max in Java?

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

Binding ComboBox SelectedItem using MVVM

I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.

<ComboBox ItemsSource="{Binding SalesPeriods}" 
          SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />

Java: how do I check if a Date is within a certain range?

  public class TestDate {

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    String fromDate = "18-FEB-2018";
    String toDate = "20-FEB-2018";

    String requestDate = "19/02/2018";  
    System.out.println(checkBetween(requestDate,fromDate, toDate));
}

public static boolean checkBetween(String dateToCheck, String startDate, String endDate) {
    boolean res = false;
    SimpleDateFormat fmt1 = new SimpleDateFormat("dd-MMM-yyyy"); //22-05-2013
    SimpleDateFormat fmt2 = new SimpleDateFormat("dd/MM/yyyy"); //22-05-2013
    try {
     Date requestDate = fmt2.parse(dateToCheck);
     Date fromDate = fmt1.parse(startDate);
     Date toDate = fmt1.parse(endDate);
     res = requestDate.compareTo(fromDate) >= 0 && requestDate.compareTo(toDate) <=0;
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    return res;
   }
 }

How to make an HTTP request + basic auth in Swift

You provide credentials in a URLRequest instance, like this in Swift 3:

let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

Or in an NSMutableURLRequest in Swift 2:

// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])

// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

Can't import Numpy in Python

Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.

Try find / -iname '*numpy*'