Programs & Examples On #Sorting

Sorting is the process of applying some order to a collection of items.

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

Sort ArrayList of custom Objects by property

Classes that has a natural sort order (a class Number, as an example) should implement the Comparable interface, whilst classes that has no natural sort order (a class Chair, as an example) should be provided with a Comparator (or an anonymous Comparator class).

Two examples:

public class Number implements Comparable<Number> {
    private int value;

    public Number(int value) { this.value = value; }
    public int compareTo(Number anotherInstance) {
        return this.value - anotherInstance.value;
    }
}

public class Chair {
    private int weight;
    private int height;

    public Chair(int weight, int height) {
        this.weight = weight;
        this.height = height;
    }
    /* Omitting getters and setters */
}
class ChairWeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getWeight() - chair2.getWeight();
    }
}
class ChairHeightComparator implements Comparator<Chair> {
    public int compare(Chair chair1, Chair chair2) {
        return chair1.getHeight() - chair2.getHeight();
    }
}

Usage:

List<Number> numbers = new ArrayList<Number>();
...
Collections.sort(numbers);

List<Chair> chairs = new ArrayList<Chair>();
// Sort by weight:
Collections.sort(chairs, new ChairWeightComparator());
// Sort by height:
Collections.sort(chairs, new ChairHeightComparator());

// You can also create anonymous comparators;
// Sort by color:
Collections.sort(chairs, new Comparator<Chair>() {
    public int compare(Chair chair1, Chair chair2) {
        ...
    }
});

Mergesort with Python

from run_time import run_time
from random_arr import make_arr

def merge(arr1: list, arr2: list):
    temp = []
    x, y = 0, 0
    while len(arr1) and len(arr2):
        if arr1[0] < arr2[0]:
            temp.append(arr1[0])
            x += 1
            arr1 = arr1[x:]
        elif arr1[0] > arr2[0]:
            temp.append(arr2[0])
            y += 1
            arr2 = arr2[y:]
        else:
            temp.append(arr1[0])
            temp.append(arr2[0])
            x += 1
            y += 1
            arr1 = arr1[x:]
            arr2 = arr2[y:]

    if len(arr1) > 0:
        temp += arr1
    if len(arr2) > 0:
        temp += arr2
    return temp

@run_time
def merge_sort(arr: list):
    total = len(arr)
    step = 2
    while True:
        for i in range(0, total, step):
            arr[i:i + step] = merge(arr[i:i + step//2], arr[i + step//2:i + step])
        step *= 2
        if step > 2 * total:
            return arr

arr = make_arr(20000)
merge_sort(arr)
# run_time is 0.10300588607788086

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

Swift how to sort array of custom objects by property value

Nearly everyone gives how directly, let me show the evolvement:

you can use the instance methods of Array:

// general form of closure
images.sortInPlace({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })

// types of closure's parameters and return value can be inferred by Swift, so they are omitted along with the return arrow (->)
images.sortInPlace({ image1, image2 in return image1.fileID > image2.fileID })

// Single-expression closures can implicitly return the result of their single expression by omitting the "return" keyword
images.sortInPlace({ image1, image2 in image1.fileID > image2.fileID })

// closure's argument list along with "in" keyword can be omitted, $0, $1, $2, and so on are used to refer the closure's first, second, third arguments and so on
images.sortInPlace({ $0.fileID > $1.fileID })

// the simplification of the closure is the same
images = images.sort({ (image1: imageFile, image2: imageFile) -> Bool in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in return image1.fileID > image2.fileID })
images = images.sort({ image1, image2 in image1.fileID > image2.fileID })
images = images.sort({ $0.fileID > $1.fileID })

For elaborate explanation about the working principle of sort, see The Sorted Function.

sorting a List of Map<String, String>

Bit out of topic
this is a little util for watching sharedpreferences
based on upper answers
may be for someone this will be helpful

@SuppressWarnings("unused")
public void printAll() {
    Map<String, ?> prefAll = PreferenceManager
        .getDefaultSharedPreferences(context).getAll();
    if (prefAll == null) {
        return;
    }
    List<Map.Entry<String, ?>> list = new ArrayList<>();
    list.addAll(prefAll.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, ?>>() {
        public int compare(final Map.Entry<String, ?> entry1, final Map.Entry<String, ?> entry2) {
            return entry1.getKey().compareTo(entry2.getKey());
        }
    });
    Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    Timber.i("Printing all sharedPreferences");
    for(Map.Entry<String, ?> entry : list) {
        Timber.i("%s: %s", entry.getKey(), entry.getValue());
    }
    Timber.i("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}

How to sort two lists (which reference each other) in the exact same way

One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in zip function:

>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2 
('one', 'one2', 'two', 'three', 'four')

These of course are no longer lists, but that's easily remedied, if it matters:

>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']

It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:

>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop

On the other hand, for larger lists, the one-line version could be faster:

>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop

As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the zip routines are!)

I think the zip-based approach is more flexible and is a little more readable, so I prefer it.

How to sort a HashSet?

You can use Java 8 collectors and TreeSet

list.stream().collect(Collectors.toCollection(TreeSet::new))

How to use Collections.sort() in Java?

Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement

public class RecipeComparator implements Comparator<Recipe> {

public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;

private int compare_mode = COMPARE_BY_NAME;

public RecipeComparator() {
}

public RecipeComparator(int compare_mode) {
    this.compare_mode = compare_mode;
}

@Override
public int compare(Recipe o1, Recipe o2) {
    switch (compare_mode) {
    case COMPARE_BY_ID:
        return o1.getId().compareTo(o2.getId());
    default:
        return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
    }
}

}

Actually for numbers you need to handle them separately check below

public static void main(String[] args) {
    String string1 = "1";
    String string2 = "2";
    String string11 = "11";

    System.out.println(string1.compareTo(string2)); 
    System.out.println(string2.compareTo(string11));// expected -1 returns 1
   // to compare numbers you actually need to do something like this

    int number2 = Integer.valueOf(string1);
    int number11 = Integer.valueOf(string11);

    int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
    System.out.println(compareTo);// prints -1
}

Combining two sorted lists in Python

in O(m+n) complexity

def merge_sorted_list(nums1: list, nums2:list) -> list:
        m = len(nums1)
        n = len(nums2)
        
        nums1 = nums1.copy()
        nums2 = nums2.copy()
        nums1.extend([0 for i in range(n)])
        while m > 0 and n > 0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[m+n-1] = nums1[m-1]
                m -= 1
            else:
                nums1[m+n-1] = nums2[n-1]
                n -= 1
        if n > 0:
            nums1[:n] = nums2[:n]
        return nums1

l1 = [1, 3, 4, 7]    
l2 =  [0, 2, 5, 6, 8, 9]    
print(merge_sorted_list(l1, l2))

output

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

Sorting options elements alphabetically using jQuery

Malakgeorge answer is nice an can be easily wrapped into a jQuery function:

$.fn.sortSelectByText = function(){
    this.each(function(){
        var selected = $(this).val(); 
        var opts_list = $(this).find('option');
        opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
        $(this).html('').append(opts_list);
        $(this).val(selected); 
    })
    return this;        
}

C++ String array sorting

Example using std::vector

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

int main()
{
    /// Initilaize vector using intitializer list ( requires C++11 )
    std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};

    // Sort names using std::sort
    std::sort(names.begin(), names.end() );

    // Print using range-based and const auto& for ( both requires C++11 )
    for(const auto& currentName : names)
    {
        std::cout << currentName << std::endl;
    }

    //... or by using your orignal for loop ( vector support [] the same way as plain arrays )
    for(int y = 0; y < names.size(); y++)
    {
       std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
    }
    return 0;

}

http://ideone.com/Q9Ew2l

This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...} You can instead add them by using vector.push_back("name")

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

Efficiently sorting a numpy array in descending order?

Unfortunately when you have a complex array, only np.sort(temp)[::-1] works properly. The two other methods mentioned here are not effective.

Syntax behind sorted(key=lambda: ...)

Simple and not time consuming answer with an example relevant to the question asked Follow this example:

 user = [{"name": "Dough", "age": 55}, 
            {"name": "Ben", "age": 44}, 
            {"name": "Citrus", "age": 33},
            {"name": "Abdullah", "age":22},
            ]
    print(sorted(user, key=lambda el: el["name"]))
    print(sorted(user, key= lambda y: y["age"]))

Look at the names in the list, they starts with D, B, C and A. And if you notice the ages, they are 55, 44, 33 and 22. The first print code

print(sorted(user, key=lambda el: el["name"]))

Results to:

[{'name': 'Abdullah', 'age': 22}, 
{'name': 'Ben', 'age': 44}, 
{'name': 'Citrus', 'age': 33}, 
{'name': 'Dough', 'age': 55}]

sorts the name, because by key=lambda el: el["name"] we are sorting the names and the names return in alphabetical order.

The second print code

print(sorted(user, key= lambda y: y["age"]))

Result:

[{'name': 'Abdullah', 'age': 22},
 {'name': 'Citrus', 'age': 33},
 {'name': 'Ben', 'age': 44}, 
 {'name': 'Dough', 'age': 55}]

sorts by age, and hence the list returns by ascending order of age.

Try this code for better understanding.

sorting integers in order lowest to highest java

Take Inputs from User and Insertion Sort. Here is how it works:

package com.learning.constructor;

import java.util.Scanner;



public class InsertionSortArray {

public static void main(String[] args) {    

Scanner s=new Scanner(System.in);

System.out.println("enter number of elements");

int n=s.nextInt();


int arr[]=new int[n];

System.out.println("enter elements");

for(int i=0;i<n;i++){//for reading array
    arr[i]=s.nextInt();

}

System.out.print("Your Array Is: ");
//for(int i: arr){ //for printing array
for (int i = 0; i < arr.length; i++){
    System.out.print(arr[i] + ",");

}
System.out.println("\n");        

    int[] input = arr;
    insertionSort(input);
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}

public static void insertionSort(int array[]) {
    int n = array.length;
    for (int j = 1; j < n; j++) {
        int key = array[j];
        int i = j-1;
        while ( (i > -1) && ( array [i] > key ) ) {
            array [i+1] = array [i];
            i--;
        }
        array[i+1] = key;
        printNumbers(array);
    }
}

}

Sorting an array of objects by property values

Descending order of price:

homes.sort((x,y) => {return y.price - x.price})

Ascending order of price:

homes.sort((x,y) => {return x.price - y.price})

Python 3 sort a dict by its values

To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDict from the standard library.

If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?

unix sort descending order

The presence of the n option attached to the -k5 causes the global -r option to be ignored for that field. You have to specify both n and r at the same level (globally or locally).

sort -t $'\t' -k5,5rn

or

sort -rn -t $'\t' -k5,5

C# List<> Sort by x then y

For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

Sort a List of objects by multiple fields

If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply. Imagine you have a program dealing with cities:



    protected Set<City> cities;
    (...)
    Field temperatureField = City.class.getDeclaredField("temperature");
    Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
    Field rainfallField = City.class.getDeclaredField("rainfall");
    program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
    (...)
    public void showCitiesSortBy(Field... fields) {
        List<City> sortedCities = new ArrayList<City>(cities);
        Collections.sort(sortedCities, new City.CityMultiComparator(fields));
        for (City city : sortedCities) {
            System.out.println(city.toString());
        }
    }

where you can replace hard-coded field names by field names deduced from a user request in your program.

In this example, City.CityMultiComparator<City> is a static nested class of class City implementing Comparator:



    public static class CityMultiComparator implements Comparator<City> {
        protected List<Field> fields;

        public CityMultiComparator(Field... orderedFields) {
            fields = new ArrayList<Field>();
            for (Field field : orderedFields) {
                fields.add(field);
            }
        }

        @Override
        public int compare(City cityA, City cityB) {
            Integer score = 0;
            Boolean continueComparison = true;
            Iterator itFields = fields.iterator();

            while (itFields.hasNext() && continueComparison) {
                Field field = itFields.next();
                Integer currentScore = 0;
                if (field.getName().equalsIgnoreCase("temperature")) {
                    currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
                } else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
                    currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
                } else if (field.getName().equalsIgnoreCase("rainfall")) {
                    currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
                }
                if (currentScore != 0) {
                    continueComparison = false;
                }
                score = currentScore;
            }

            return score;
        }
    }


You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field objects by objects of a class you could call SortedField, containing a Field object, plus another field meaning ascendant or descendant.

Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

Is there a way to 'uniq' by column?

If you want to retain the last one of the duplicates you could use

 tac a.csv | sort -u -t, -r -k1,1 |tac

Which was my requirement

here

tac will reverse the file line by line

Sort Array of object by object field in Angular 6

Not tested but should work

 products.sort((a,b)=>a.title.rendered > b.title.rendered)

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

Try this function

getQuantileGroupNum <- function(vec, group_num, decreasing=FALSE) {
  if(decreasing) {
    abs(cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T) - group_num - 1)
  } else {
    cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T)
  }
}
> t1 <- runif(7)
> t1
[1] 0.4336094 0.2842928 0.5578876 0.2678694 0.6495285 0.3706474 0.5976223
> getQuantileGroupNum(t1, 4)
[1] 2 1 3 1 4 2 4
> getQuantileGroupNum(t1, 4, decreasing=T)
[1] 3 4 2 4 1 3 1

Javascript Array.sort implementation?

I think that would depend on what browser implementation you are refering to.

Every browser type has it's own javascript engine implementation, so it depends. You could check the sourcecode repos for Mozilla and Webkit/Khtml for different implementations.

IE is closed source however, so you may have to ask somebody at microsoft.

Why does my sorting loop seem to append an element where it shouldn't?

Apart from the alternative solutions that were posted here (which are correct), no one has actually answered your question by addressing what was wrong with your code.

It seems as though you were trying to implement a selection sort algorithm. I will not go into the details of how sorting works here, but I have included a few links for your reference =)

Your code was syntactically correct, but logically wrong. You were partially sorting your strings by only comparing each string with the strings that came after it. Here is a corrected version (I retained as much of your original code to illustrate what was "wrong" with it):

static  String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String  temp;

//Keeps track of the smallest string's index
int  shortestStringIndex; 

public static void main(String[] args)  
{              

 //I reduced the upper bound from Array.length to (Array.length - 1)
 for(int j=0; j < Array.length - 1;j++)
 {
     shortestStringIndex = j;

     for (int i=j+1 ; i<Array.length; i++)
     {
         //We keep track of the index to the smallest string
         if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
         {
             shortestStringIndex = i;  
         }
     }
     //We only swap with the smallest string
     if(shortestStringIndex != j)
     {
         String temp = Array[j];
         Array[j] = Array[shortestStringIndex]; 
         Array[shortestStringIndex] = temp;
     }
 }
}

Further Reading

The problem with this approach is that its asymptotic complexity is O(n^2). In simplified words, it gets very slow as the size of the array grows (approaches infinity). You may want to read about better ways to sort data, such as quicksort.

How to sort an ArrayList?

Using lambdas (Java8), and stripping it down to the barest of syntax (the JVM will infer plenty in this case), you get:

Collections.sort(testList, (a, b) -> b.compareTo(a));

A more verbose version:

// Implement a reverse-order Comparator by lambda function
Comparator<Double> comp = (Double a, Double b) -> {
    return b.compareTo(a);
};

Collections.sort(testList, comp);

The use of a lambda is possible because the Comparator interface has only a single method to implement, so the VM can infer which method is implementing. Since the types of the params can be inferred, they don't need to be stated (i.e. (a, b) instead of (Double a, Double b). And since the lambda body has only a single line, and the method is expected to return a value, the return is inferred and the braces aren't necessary.

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

I would recommend looking at Selection sort or Insertion sort if you aren't too worried about performance. Maybe that will give you some ideas.

Disable sorting for a particular column in jQuery DataTables

Here is what you can use to disable certain column to be disabled:

 $('#tableId').dataTable({           
            "columns": [
                { "data": "id"},
                { "data": "sampleSortableColumn" },
                { "data": "otherSortableColumn" },
                { "data": "unsortableColumn", "orderable": false}
           ]
});

So all you have to do is add the "orderable": false to the column you don't want to be sortable.

How do operator.itemgetter() and sort() work?

Looks like you're a little bit confused about all that stuff.

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

So, you can't use key=a[x][1] there, because python has no idea what x is. Instead, you could use a lambda function (elem is just a variable name, no magic there):

a.sort(key=lambda elem: elem[1])

Or just an ordinary function:

def get_second_elem(iterable):
    return iterable[1]

a.sort(key=get_second_elem)

So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.

Other questions:

  1. Yes, you can reverse sort, just add reverse=True: a.sort(key=..., reverse=True)
  2. To sort by more than one column you can use itemgetter with multiple indices: operator.itemgetter(1,2), or with lambda: lambda elem: (elem[1], elem[2]). This way, iterables are constructed on the fly for each item in list, which are than compared against each other in lexicographic(?) order (first elements compared, if equal - second elements compared, etc)
  3. You can fetch value at [3,2] using a[2,1] (indices are zero-based). Using operator... It's possible, but not as clean as just indexing.

Refer to the documentation for details:

  1. operator.itemgetter explained
  2. Sorting list by custom key in Python

How to sort an array of associative arrays by value of a given key in PHP?

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

Find unique lines

uniq -u < file will do the job.

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

Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

sort() doesn't return any value.

The sort() method just sorts the elements of a given list in a specific order - Ascending or Descending without returning any value.

The syntax of sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted function return sorted list

 list=sorted(list, key=..., reverse=...)

How to sort a HashMap in Java

Sorting by key:

public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();

    map.put("b", "dd");
    map.put("c", "cc");
    map.put("a", "aa");

    map = new TreeMap<>(map);

    for (String key : map.keySet()) {
        System.out.println(key+"="+map.get(key));
    }
}

Quicksort with Python

The algorithm contains two boundaries, one having elements less than the pivot (tracked by index "j") and the other having elements greater than the pivot (tracked by index "i").

In each iteration, a new element is processed by incrementing j.

Invariant:-

  1. all elements between pivot and i are less than the pivot, and
  2. all elements between i and j are greater than the pivot.

If the invariant is violated, ith and jth elements are swapped, and i is incremented.

After all elements have been processed, and everything after the pivot has been partitioned, the pivot element is swapped with the last element smaller than it.

The pivot element will now be in its correct place in the sequence. The elements before it will be less than it and the ones after it will be greater than it, and they will be unsorted.

def quicksort(sequence, low, high):
    if low < high:    
        pivot = partition(sequence, low, high)
        quicksort(sequence, low, pivot - 1)
        quicksort(sequence, pivot + 1, high)

def partition(sequence, low, high):
    pivot = sequence[low]
    i = low + 1
    for j in range(low + 1, high + 1):
        if sequence[j] < pivot:
            sequence[j], sequence[i] = sequence[i], sequence[j]
            i += 1
    sequence[i-1], sequence[low] = sequence[low], sequence[i-1]
    return i - 1

def main(sequence):
    quicksort(sequence, 0, len(sequence) - 1)
    return sequence

if __name__ == '__main__':
    sequence = [-2, 0, 32, 1, 56, 99, -4]
    print(main(sequence))

Selecting a pivot

A "good" pivot will result in two sub-sequences of roughly the same size. Deterministically, a pivot element can either be selected in a naive manner or by computing the median of the sequence.

A naive implementation of selecting a pivot will be the first or last element. The worst-case runtime in this case will be when the input sequence is already sorted or reverse sorted, as one of the subsequences will be empty which will cause only one element to be removed per recursive call.

A perfectly balanced split is achieved when the pivot is the median element of the sequence. There are an equal number of elements greater than it and less than it. This approach guarantees a better overall running time, but is much more time-consuming.

A non-deterministic/random way of selecting the pivot would be to pick an element uniformly at random. This is a simple and lightweight approach that will minimize worst-case scenario and also lead to a roughly balanced split. This will also provide a balance between the naive approach and the median approach of selecting the pivot.

Sorting Characters Of A C++ String

You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;


        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors

implementing merge sort in C++

To answer the question: Creating dynamically sized arrays at run-time is done using std::vector<T>. Ideally, you'd get your input using one of these. If not, it is easy to convert them. For example, you could create two arrays like this:

template <typename T>
void merge_sort(std::vector<T>& array) {
    if (1 < array.size()) {
        std::vector<T> array1(array.begin(), array.begin() + array.size() / 2);
        merge_sort(array1);
        std::vector<T> array2(array.begin() + array.size() / 2, array.end());
        merge_sort(array2);
        merge(array, array1, array2);
    }
}

However, allocating dynamic arrays is relatively slow and generally should be avoided when possible. For merge sort you can just sort subsequences of the original array and in-place merge them. It seems, std::inplace_merge() asks for bidirectional iterators.

How to sort with lambda in Python

lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)

It will print as following:

[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]

Collections.sort with multiple fields

Sorting with multiple fields in Java8

package com.java8.chapter1;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;



 public class Example1 {

    public static void main(String[] args) {
        List<Employee> empList = getEmpList();


        // Before Java 8 
        empList.sort(new Comparator<Employee>() {

            @Override
            public int compare(Employee o1, Employee o2) {
                int res = o1.getDesignation().compareTo(o2.getDesignation());
                if (res == 0) {
                    return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
                } else {
                    return res;
                }

            }
        });
        for (Employee emp : empList) {
            System.out.println(emp);
        }
        System.out.println("---------------------------------------------------------------------------");

        // In Java 8

        empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
        empList.stream().forEach(System.out::println);

    }
    private static List<Employee> getEmpList() {
        return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
                new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
                new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
                new Employee("Jaishree", "Opearations HR", 350000));
    }
}

class Employee {
    private String fullName;
    private String designation;
    private double salary;

    public Employee(String fullName, String designation, double salary) {
        super();
        this.fullName = fullName;
        this.designation = designation;
        this.salary = salary;
    }

    public String getFullName() {
        return fullName;
    }

    public String getDesignation() {
        return designation;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
    }

}

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.

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

A good Sorted List for Java

Depending on how you're using the list, it may be worth it to use a TreeSet and then use the toArray() method at the end. I had a case where I needed a sorted list, and I found that the TreeSet + toArray() was much faster than adding to an array and merge sorting at the end.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

When is each sorting algorithm used?

First, a definition, since it's pretty important: A stable sort is one that's guaranteed not to reorder elements with identical keys.

Recommendations:

Quick sort: When you don't need a stable sort and average case performance matters more than worst case performance. A quick sort is O(N log N) on average, O(N^2) in the worst case. A good implementation uses O(log N) auxiliary storage in the form of stack space for recursion.

Merge sort: When you need a stable, O(N log N) sort, this is about your only option. The only downsides to it are that it uses O(N) auxiliary space and has a slightly larger constant than a quick sort. There are some in-place merge sorts, but AFAIK they are all either not stable or worse than O(N log N). Even the O(N log N) in place sorts have so much larger a constant than the plain old merge sort that they're more theoretical curiosities than useful algorithms.

Heap sort: When you don't need a stable sort and you care more about worst case performance than average case performance. It's guaranteed to be O(N log N), and uses O(1) auxiliary space, meaning that you won't unexpectedly run out of heap or stack space on very large inputs.

Introsort: This is a quick sort that switches to a heap sort after a certain recursion depth to get around quick sort's O(N^2) worst case. It's almost always better than a plain old quick sort, since you get the average case of a quick sort, with guaranteed O(N log N) performance. Probably the only reason to use a heap sort instead of this is in severely memory constrained systems where O(log N) stack space is practically significant.

Insertion sort: When N is guaranteed to be small, including as the base case of a quick sort or merge sort. While this is O(N^2), it has a very small constant and is a stable sort.

Bubble sort, selection sort: When you're doing something quick and dirty and for some reason you can't just use the standard library's sorting algorithm. The only advantage these have over insertion sort is being slightly easier to implement.


Non-comparison sorts: Under some fairly limited conditions it's possible to break the O(N log N) barrier and sort in O(N). Here are some cases where that's worth a try:

Counting sort: When you are sorting integers with a limited range.

Radix sort: When log(N) is significantly larger than K, where K is the number of radix digits.

Bucket sort: When you can guarantee that your input is approximately uniformly distributed.

Finding median of list in Python

Here what I came up with during this exercise in Codecademy:

def median(data):
    new_list = sorted(data)
    if len(new_list)%2 > 0:
        return new_list[len(new_list)/2]
    elif len(new_list)%2 == 0:
        return (new_list[(len(new_list)/2)] + new_list[(len(new_list)/2)-1]) /2.0

print median([1,2,3,4,5,9])

How do I sort a dictionary by value?

Iterate through a dict and sort it by its values in descending order:

$ python --version
Python 3.2.2

$ cat sort_dict_by_val_desc.py 
dictionary = dict(siis = 1, sana = 2, joka = 3, tuli = 4, aina = 5)
for word in sorted(dictionary, key=dictionary.get, reverse=True):
  print(word, dictionary[word])

$ python sort_dict_by_val_desc.py 
aina 5
tuli 4
joka 3
sana 2
siis 1

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

How to sort an array of objects by multiple fields?

How about this simple solution:

const sortCompareByCityPrice = (a, b) => {
    let comparison = 0
    // sort by first criteria
    if (a.city > b.city) {
        comparison = 1
    }
    else if (a.city < b.city) {
        comparison = -1
    }
    // If still 0 then sort by second criteria descending
    if (comparison === 0) {
        if (parseInt(a.price) > parseInt(b.price)) {
            comparison = -1
        }
        else if (parseInt(a.price) < parseInt(b.price)) {
            comparison = 1
        }
    }
    return comparison 
}

Based on this question javascript sort array by multiple (number) fields

Sorting objects by property values

With ES6 arrow functions it will be like this:

//Let's say we have these cars
let cars = [ { brand: 'Porsche', top_speed: 260 },
  { brand: 'Benz', top_speed: 110 },
  { brand: 'Fiat', top_speed: 90 },
  { brand: 'Aston Martin', top_speed: 70 } ]

Array.prototype.sort() can accept a comparator function (here I used arrow notation, but ordinary functions work the same):

let sortedByBrand = [...cars].sort((first, second) => first.brand > second.brand)

// [ { brand: 'Aston Martin', top_speed: 70 },
//   { brand: 'Benz', top_speed: 110 },
//   { brand: 'Fiat', top_speed: 90 },
//   { brand: 'Porsche', top_speed: 260 } ]

The above approach copies the contents of cars array into a new one and sorts it alphabetically based on brand names. Similarly, you can pass a different function:

let sortedBySpeed =[...cars].sort((first, second) => first.top_speed > second.top_speed)

//[ { brand: 'Aston Martin', top_speed: 70 },
//  { brand: 'Fiat', top_speed: 90 },
//  { brand: 'Benz', top_speed: 110 },
//  { brand: 'Porsche', top_speed: 260 } ]

If you don't mind mutating the orginal array cars.sort(comparatorFunction) will do the trick.

Reordering arrays

Reorder its work This Way

 var tmpOrder = playlist[oldIndex];
    playlist.splice(oldIndex, 1);
    playlist.splice(newIndex, 0, tmpOrder);

I hope this will work

How do I sort a two-dimensional (rectangular) array in C#?

If you could get the data as a generic tuple when you read it in or retrieved it, it would be a lot easier; then you would just have to write a Sort function that compares the desired column of the tuple, and you have a single dimension array of tuples.

How do I sort arrays using vbscript?

If you are going to output the lines anyway, you could run the output through the sort command. Not elegant, but it does not require much work:

cscript.exe //nologo YOUR-SCRIPT | Sort

Note //nologo omits the logo lines (Microsoft (R) Windows Script Host Version... blah blah blah) from appearing in the middle of your sorted output. (I guess MS does not know what stderr is for.)

See http://ss64.com/nt/sort.html for details on sort.

/+n is the most useful option if your sort key does not start in the first column.

Compares are always case-insensitive, which is lame.

Pythonic way to check if a list is sorted or not

Although I don't think there is a guarantee for that the sorted built-in calls its cmp function with i+1, i, it does seem to do so for CPython.

So you could do something like:

def my_cmp(x, y):
   cmpval = cmp(x, y)
   if cmpval < 0:
      raise ValueError
   return cmpval

def is_sorted(lst):
   try:
      sorted(lst, cmp=my_cmp)
      return True
   except ValueError:
      return False

print is_sorted([1,2,3,5,6,7])
print is_sorted([1,2,5,3,6,7])

Or this way (without if statements -> EAFP gone wrong? ;-) ):

def my_cmp(x, y):
   assert(x >= y)
   return -1

def is_sorted(lst):
   try:
      sorted(lst, cmp=my_cmp)
      return True
   except AssertionError:
      return False

How can I pair socks from a pile efficiently?

My proposed solution assumes that all socks are identical in details, except by color. If there are more details to defer between socks, these details can be used to define different types of socks instead of colors in my example ..

Given that we have a pile of socks, a sock can come in three colors: Blue, red, or green.

Then we can create a parallel worker for each color; it has its own list to fill corresponding colors.

At time i:

Blue  read  Pile[i]    : If Blue  then Blue.Count++  ; B=TRUE  ; sync

Red   read  Pile[i+1]  : If Red   then Red.Count++   ; R=TRUE  ; sync

Green read  Pile [i+2] : If Green then Green.Count++ ; G=TRUE  ; sync

With synchronization process:

Sync i:

i++

If R is TRUE:
    i++
    If G is TRUE:
        i++

This requires an initialization:

Init:

If Pile[0] != Blue:
    If      Pile[0] = Red   : Red.Count++
    Else if Pile[0] = Green : Green.Count++

If Pile[1] != Red:
    If Pile[0] = Green : Green.Count++

Where

Best Case: B, R, G, B, R, G, .., B, R, G

Worst Case: B, B, B, .., B

Time(Worst-Case) = C * n ~ O(n)

Time(Best-Case) = C * (n/k) ~ O(n/k)

n: number of sock pairs
k: number of colors
C: sync overhead

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

Best way to randomize an array with .NET

Generate an array of random floats or ints of the same length. Sort that array, and do corresponding swaps on your target array.

This yields a truly independent sort.

Java Array Sort descending?

For discussions above, here is an easy example to sort the primitive arrays in descending order.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
        Arrays.sort(nums);

        // reverse the array, just like dumping the array!
        // swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
        // swap(2nd, 2nd-last) <= 2nd: i++,  2nd-last: j--
        // swap(3rd, 3rd-last) <= 3rd: i++,  3rd-last: j--
        //
        for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        // dump the array (for Java 4/5/6/7/8/9)
        for (int i = 0; i < nums.length; i++) {
            System.out.println("nums[" + i + "] = " + nums[i]);
        }
    }
}

Output:

nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0

How to sort an array in descending order in Ruby

You could do:

a.sort{|a,b| b[:bar] <=> a[:bar]}

Sorting a vector in descending order

TL;DR

Use any. They are almost the same.

Boring answer

As usual, there are pros and cons.

Use std::reverse_iterator:

  • When you are sorting custom types and you don't want to implement operator>()
  • When you are too lazy to type std::greater<int>()

Use std::greater when:

  • When you want to have more explicit code
  • When you want to avoid using obscure reverse iterators

As for performance, both methods are equally efficient. I tried the following benchmark:

#include <algorithm>
#include <chrono>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std::chrono;

/* 64 Megabytes. */
#define VECTOR_SIZE (((1 << 20) * 64) / sizeof(int))
/* Number of elements to sort. */
#define SORT_SIZE 100000

int main(int argc, char **argv) {
    std::vector<int> vec;
    vec.resize(VECTOR_SIZE);

    /* We generate more data here, so the first SORT_SIZE elements are evicted
       from the cache. */
    std::ifstream urandom("/dev/urandom", std::ios::in | std::ifstream::binary);
    urandom.read((char*)vec.data(), vec.size() * sizeof(int));
    urandom.close();

    auto start = steady_clock::now();
#if USE_REVERSE_ITER
    auto it_rbegin = vec.rend() - SORT_SIZE;
    std::sort(it_rbegin, vec.rend());
#else
    auto it_end = vec.begin() + SORT_SIZE;
    std::sort(vec.begin(), it_end, std::greater<int>());
#endif
    auto stop = steady_clock::now();

    std::cout << "Sorting time: "
          << duration_cast<microseconds>(stop - start).count()
          << "us" << std::endl;
    return 0;
}

With this command line:

g++ -g -DUSE_REVERSE_ITER=0 -std=c++11 -O3 main.cpp \
    && valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
    && cg_annotate cachegrind.out
g++ -g -DUSE_REVERSE_ITER=1 -std=c++11 -O3 main.cpp \
    && valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
    && cg_annotate cachegrind.out

std::greater demo std::reverse_iterator demo

Timings are same. Valgrind reports the same number of cache misses.

Sort a two dimensional array based on one column

Assuming your array contains strings, you can use the following:

String[] data = new String[] { 
    "2009.07.25 20:24 Message A",
    "2009.07.25 20:17 Message G",
    "2009.07.25 20:25 Message B",
    "2009.07.25 20:30 Message D",
    "2009.07.25 20:01 Message F",
    "2009.07.25 21:08 Message E",
    "2009.07.25 19:54 Message R"
};

Arrays.sort(data, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String t1 = s1.substring(0, 16); // date/time of s1
        String t2 = s2.substring(0, 16); // date/time of s2
        return t1.compareTo(t2);
    }
});

If you have a two-dimensional array, the solution is also very similar:

String[][] data = new String[][] { 
        { "2009.07.25 20:17", "Message G" },
        { "2009.07.25 20:25", "Message B" },
        { "2009.07.25 20:30", "Message D" },
        { "2009.07.25 20:01", "Message F" },
        { "2009.07.25 21:08", "Message E" },
        { "2009.07.25 19:54", "Message R" }
};

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] s1, String[] s2) {
        String t1 = s1[0];
        String t2 = s2[0];
        return t1.compareTo(t2);
    }
});

Find the unique values in a column and then sort them

You can also use the drop_duplicates() instead of unique()

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a

python: order a list of numbers without built-in sort, min, max function

How do I keep looping through until the len(new_list) = len(data_list)

while len(new_list) != len(data_list):
    # ...

Maybe like this?

And no, it’s not necessary to create a new list; most sorting algorithms work by changing the list in place.

What you probably trying to do is Selection sort with a separate list. See the Wikipedia article for more information about that sorting algorithm and you’ll see how it works with a single list, and how efficient it is (spoiler: it isn’t).

Quicksort: Choosing the pivot

Ideally the pivot should be the middle value in the entire array. This will reduce the chances of getting worst case performance.

Sorting a tab delimited file

I was having this problem with sort in cygwin in a bash shell when using 'general-numeric-sort'. If I specified -t$'\t' -kFg, where F is the field number, it didn't work, but when I specified both -t$'\t' and -kF,Fg (e.g -k7,7g for the 7th field) it did work. -kF,Fg without the -t$'\t' did not work.

Sorting a vector of custom objects

Below is the code using lambdas

#include "stdafx.h"
#include <vector>
#include <algorithm>

using namespace std;

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

int main()
{
    std::vector < MyStruct > vec;

    vec.push_back(MyStruct(4, "test"));
    vec.push_back(MyStruct(3, "a"));
    vec.push_back(MyStruct(2, "is"));
    vec.push_back(MyStruct(1, "this"));

    std::sort(vec.begin(), vec.end(), 
        [] (const MyStruct& struct1, const MyStruct& struct2)
        {
            return (struct1.key < struct2.key);
        }
    );
    return 0;
}

Sort array of objects by string property value

underscore.js

use underscore, its small and awesome...

sortBy_.sortBy(list, iterator, [context]) Returns a sorted copy of list, ranked in ascending order by the results of running each value through iterator. Iterator may also be the string name of the property to sort by (eg. length).

var objs = [ 
  { first_nom: 'Lazslo',last_nom: 'Jamf' },
  { first_nom: 'Pig', last_nom: 'Bodine'  },
  { first_nom: 'Pirate', last_nom: 'Prentice' }
];

var sortedObjs = _.sortBy( objs, 'first_nom' );

How to sort an array of objects in Java?

Update for Java 8 constructs

Assuming a Book class with a name field getter, you can use Arrays.sort method by passing an additional Comparator specified using Java 8 constructs - Comparator default method & method references.

Arrays.sort(bookArray, Comparator.comparing(Book::getName));

Also, it's possible to compare on multiple fields using thenComparing methods.

Arrays.sort(bookArray, Comparator.comparing(Book::getName)
      .thenComparing(Book::getAuthor))
      .thenComparingInt(Book::getId));

How to perform case-insensitive sorting in JavaScript?

Normalize the case in the .sort() with .toLowerCase().

How do you sort a dictionary by value?

You can sort a Dictionary by value and save it back to itself (so that when you foreach over it the values come out in order):

dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

Sure, it may not be correct, but it works.

How do I sort an observable collection?

I would like to Add to NeilW's answer. To incorporate a method that resembles the orderby. Add this method as an extension:

public static void Sort<T>(this ObservableCollection<T> collection, Func<T,T> keySelector) where T : IComparable
{
    List<T> sorted = collection.OrderBy(keySelector).ToList();
    for (int i = 0; i < sorted.Count(); i++)
        collection.Move(collection.IndexOf(sorted[i]), i);
}

And use like:

myCollection = new ObservableCollection<MyObject>();

//Sorts in place, on a specific Func<T,T>
myCollection.Sort(x => x.ID);

java Arrays.sort 2d array

for decreasing order for integer array of 2 dimension you can use

Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order

Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]);//decreasing order

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

How to order a data frame by one descending and one ascending column?

The correct way is:

rum[order(rum$T1, rum$T2, decreasing=c(T,F)), ]

How to convert a Collection to List?

Here is a sub-optimal solution as a one-liner:

Collections.list(Collections.enumeration(coll));

How to sort List<Integer>?

Use Collections class API to sort.

Collections.sort(list);

How to sort an array in Bash

try this:

echo ${array[@]} | awk 'BEGIN{RS=" ";} {print $1}' | sort

Output will be:

3
5
a
b
c
f

Problem solved.

Sorting a Python list by two fields

list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )

Disable automatic sorting on the first column when using jQuery DataTables

Add

"aaSorting": []

And check if default value is not null only set sortable column then

if ($('#table').DataTable().order().length == 1) {
    d.SortColumn = $('#table').DataTable().order()[0][0];
    d.SortOrder = $('#table').DataTable().order()[0][1];
}

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If the numbers are evenly distributed we can use Counting sort. We should keep the number of times that each number is repeated in an array. Available space is: 1 MB - 3 KB = 1045504 B or 8364032 bits Number of bits per number= 8364032/1000000 = 8 Therefore, we can store the number of times each number is repeated to the maximum of 2^8-1=255. Using this approach we have an extra 364032 bits unused that can be used to handle cases where a number is repeated more than 255 times. For example we can say a number 255 indicates a repetition greater than or equal to 255. In this case we should store a sequence of numbers+repetitions. We can handle 7745 special cases as shown bellow:

364032/ (bits need to represent each number + bits needed to represent 1 million)= 364032 / (27+20)=7745

C++ sorting and keeping track of indexes

I wrote generic version of index sort.

template <class RAIter, class Compare>
void argsort(RAIter iterBegin, RAIter iterEnd, Compare comp, 
    std::vector<size_t>& indexes) {

    std::vector< std::pair<size_t,RAIter> > pv ;
    pv.reserve(iterEnd - iterBegin) ;

    RAIter iter ;
    size_t k ;
    for (iter = iterBegin, k = 0 ; iter != iterEnd ; iter++, k++) {
        pv.push_back( std::pair<int,RAIter>(k,iter) ) ;
    }

    std::sort(pv.begin(), pv.end(), 
        [&comp](const std::pair<size_t,RAIter>& a, const std::pair<size_t,RAIter>& b) -> bool 
        { return comp(*a.second, *b.second) ; }) ;

    indexes.resize(pv.size()) ;
    std::transform(pv.begin(), pv.end(), indexes.begin(), 
        [](const std::pair<size_t,RAIter>& a) -> size_t { return a.first ; }) ;
}

Usage is the same as that of std::sort except for an index container to receive sorted indexes. testing:

int a[] = { 3, 1, 0, 4 } ;
std::vector<size_t> indexes ;
argsort(a, a + sizeof(a) / sizeof(a[0]), std::less<int>(), indexes) ;
for (size_t i : indexes) printf("%d\n", int(i)) ;

you should get 2 1 0 3. for the compilers without c++0x support, replace the lamba expression as a class template:

template <class RAIter, class Compare> 
class PairComp {
public:
  Compare comp ;
  PairComp(Compare comp_) : comp(comp_) {}
  bool operator() (const std::pair<size_t,RAIter>& a, 
    const std::pair<size_t,RAIter>& b) const { return comp(*a.second, *b.second) ; }        
} ;

and rewrite std::sort as

std::sort(pv.begin(), pv.end(), PairComp(comp)()) ;

C# Sort and OrderBy comparison

I think it's important to note another difference between Sort and OrderBy:

Suppose there exists a Person.CalculateSalary() method, which takes a lot of time; possibly more than even the operation of sorting a large list.

Compare

// Option 1
persons.Sort((p1, p2) => Compare(p1.CalculateSalary(), p2.CalculateSalary()));
// Option 2
var query = persons.OrderBy(p => p.CalculateSalary()); 

Option 2 may have superior performance, because it only calls the CalculateSalary method n times, whereas the Sort option might call CalculateSalary up to 2n log(n) times, depending on the sort algorithm's success.

How to sort an array of integers correctly

The question has already been answered, the shortest way is to use sort() method. But if you're searching for more ways to sort your array of numbers, and you also love cycles, check the following

Insertion sort

Ascending:

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
for (var i = 0; i < numArray.length; i++) {_x000D_
    var target = numArray[i];_x000D_
    for (var j = i - 1; j >= 0 && (numArray[j] > target); j--) {_x000D_
        numArray[j+1] = numArray[j];_x000D_
    }_x000D_
    numArray[j+1] = target_x000D_
}_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

Descending:

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
for (var i = 0; i < numArray.length; i++) {_x000D_
    var target = numArray[i];_x000D_
    for (var j = i - 1; j >= 0 && (numArray[j] < target); j--) {_x000D_
        numArray[j+1] = numArray[j];_x000D_
    }_x000D_
    numArray[j+1] = target_x000D_
}_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

Selection sort:

Ascending:

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
for (var i = 0; i < numArray.length - 1; i++) {_x000D_
    var min = i;_x000D_
    for (var j = i + 1; j < numArray.length; j++) {_x000D_
        if (numArray[j] < numArray[min]) {_x000D_
            min = j;_x000D_
        }_x000D_
    }_x000D_
    if (min != i) {_x000D_
        var target = numArray[i];_x000D_
        numArray[i] = numArray[min];_x000D_
        numArray[min] = target;_x000D_
    }_x000D_
}_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

Descending:

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
for (var i = 0; i < numArray.length - 1; i++) {_x000D_
    var min = i;_x000D_
    for (var j = i + 1; j < numArray.length; j++) {_x000D_
        if (numArray[j] > numArray[min]) {_x000D_
            min = j;_x000D_
        }_x000D_
    }_x000D_
    if (min != i) {_x000D_
        var target = numArray[i];_x000D_
        numArray[i] = numArray[min];_x000D_
        numArray[min] = target;_x000D_
    }_x000D_
}_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

Have fun

Quick Sort Vs Merge Sort

Quick sort is typically faster than merge sort when the data is stored in memory. However, when the data set is huge and is stored on external devices such as a hard drive, merge sort is the clear winner in terms of speed. It minimizes the expensive reads of the external drive and also lends itself well to parallel computing.

How to sort a list of lists by a specific index of the inner list?

Like this:

import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))

orderBy multiple fields in Angular

Created Pipe for sorting. Accepts both string and array of strings, sorting by multiple values. Works for Angular (not AngularJS). Supports both sort for string and numbers.

@Pipe({name: 'orderBy'})
export class OrderBy implements PipeTransform {
    transform(array: any[], filter: any): any[] {
        if(typeof filter === 'string') {
            return this.sortAray(array, filter)
        } else {
            for (var i = filter.length -1; i >= 0; i--) {
                array = this.sortAray(array, filter[i]);
            }

            return array;
        }
    }

    private sortAray(array, field) {
        return array.sort((a, b) => {
            if(typeof a[field] !== 'string') {
                a[field] !== b[field] ? a[field] < b[field] ? -1 : 1 : 0
            } else {
                a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0
            }
        });
    }
}

Sort Java Collection

As of Java 8 you now can do it with a stream using a lambda:

list.stream().sorted(Comparator.comparing(customObject::getId))
             .foreach(object -> System.out.println(object));

jQuery table sort

I came across this, and thought I'd throw in my 2 cents. Click on the column headers to sort ascending, and again to sort descending.

  • Works in Chrome, Firefox, Opera AND IE(8)
  • Only uses JQuery
  • Does alpha and numeric sorting - ascending and descending

_x000D_
_x000D_
$('th').click(function(){_x000D_
    var table = $(this).parents('table').eq(0)_x000D_
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))_x000D_
    this.asc = !this.asc_x000D_
    if (!this.asc){rows = rows.reverse()}_x000D_
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}_x000D_
})_x000D_
function comparer(index) {_x000D_
    return function(a, b) {_x000D_
        var valA = getCellValue(a, index), valB = getCellValue(b, index)_x000D_
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)_x000D_
    }_x000D_
}_x000D_
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
th {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>_x000D_
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>_x000D_
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>_x000D_
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>_x000D_
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
    <tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

** Update: 2018

Sorting A ListView By Column

I can see that this question was originally posted 5 yrs ago when programmers had to work harder to get their desired results. With Visual Studio 2012 and beyond, a lazy programmer can go the Design View for the Listview properties settings, and click on Properties->Sorting, choose Ascending. There are plenty of other properties features to obtain the various results a lazy (aka smart) programmer can leverage.

LINQ order by null column where order is ascending and nulls should be last

Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

Otherwise each orderby is a separate operation on the collection re-ordering it each time.

This should order the ones with a value first, "then" the order of the value.

Sort an Array by keys based on another Array?

Without magic...

$array=array(28=>c,4=>b,5=>a);
$seq=array(5,4,28);    
SortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);

function sortByKeyList($array,$seq){
    $ret=array();
    if(empty($array) || empty($seq)) return false;
    foreach($seq as $key){$ret[$key]=$dataset[$key];}
    return $ret;
}

Sorting a list with stream.sorted() in Java

Java 8 provides different utility api methods to help us sort the streams better.

If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.

List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);

Creating comparator on fly:

integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);

With default comparator provided by java 8 when no argument passed to sorted():

integerList.stream().sorted().forEach(System.out::println); //Natural order

If you want to sort the same list in reverse order:

 integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order

If your list is a list of user defined objects, then:

List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
        new Person(2000, "Second", 30, 45000),
        new Person(3000, "Third", 35, 25000));

Creating comparator on fly:

personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
        .forEach(person -> System.out.println(person.getName()));

Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):

personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

Using Comparator.comparing() method(Generic method which compares based on the getter method provided):

personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

We can do chaining too using thenComparing() method:

personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.

Person class

public class Person {
    private long personId;
    private String name;
    private int age;
    private double salary;

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }

    public Person(long personId, String name, int age, double salary) {
        this.personId = personId;
        this.name = name;
        this.age = age;

        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

You can only use - on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:

DT[order(x,-v,decreasing=TRUE),]
      x y v
 [1,] c 1 7
 [2,] c 3 8
 [3,] c 6 9
 [4,] b 1 1
 [5,] b 3 2
 [6,] b 6 3
 [7,] a 1 4
 [8,] a 3 5
 [9,] a 6 6

Why is there no SortedList in Java?

For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView. Here's the blog post about it.

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

We can do this using ES6 sets:

_x000D_
_x000D_
var duplicatedArray = [1, 2, 3, 4, 5, 1, 1, 1, 2, 3, 4];_x000D_
var uniqueArray = Array.from(new Set(duplicatedArray));_x000D_
_x000D_
console.log(uniqueArray);
_x000D_
_x000D_
_x000D_

//The output will be

uniqueArray = [1,2,3,4,5];

Bootstrap table striped: How do I change the stripe background colour?

Don't customize your bootstrap CSS by directly editing bootstrap CSS file.Instead, I suggest to copy paste bootstrap CSS and save them in a different CSS folder and there you can customize or edit stylings suitable to your needs.

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

T-SQL substring - separating first and last name

Assuming the FirstName is all of the characters up to the first space:

SELECT
  SUBSTRING(username, 1, CHARINDEX(' ', username) - 1) AS FirstName,
  SUBSTRING(username, CHARINDEX(' ', username) + 1, LEN(username)) AS LastName
FROM
  whereever

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

Android Firebase, simply get one child object's data

I store my data this way:

accountsTable ->
  key1 -> account1
  key2 -> account2

in order to get object data:

accountsDb = mDatabase.child("accountsTable");

accountsDb.child("some   key").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot snapshot) {

                    try{

                        Account account  = snapshot.getChildren().iterator().next()
                                  .getValue(Account.class);


                    } catch (Throwable e) {
                        MyLogger.error(this, "onCreate eror", e);
                    }
                }
                @Override public void onCancelled(DatabaseError error) { }
            });

How to extract one column of a csv file

You can't do it without a full CSV parser.

.htaccess - how to force "www." in a generic way?

The following should prefix 'www' to any request that doesn't have one, and redirect the edited request to the new URI.

RewriteCond "%{HTTP_HOST}" "!^www\."         [NC]
RewriteCond "%{HTTP_HOST}" "(.*)"
RewriteRule "(.*)"         "http://www.%1$1" [R=301,L]

Is it safe to use Project Lombok?

It sounds like you've already decided that Project Lombok gives you significant technical advantages for your proposed new project. (To be clear from the start, I have no particular views on Project Lombok, one way or the other.)

Before you use Project Lombok (or any other game-changing technology) in some project (open source or other wise), you need to make sure that the project stake holders agree to this. This includes the developers, and any important users (e.g. formal or informal sponsors).

You mention these potential issues:

Flamewars will erupt in the ##Java Freenode channel when I mention it,

Easy. Ignore / don't participate in the flamewars, or simply refrain from mentioning Lombok.

providing code snippets will confuse possible helpers,

If the project strategy is to use Lombok, then the possible helpers will need to get used to it.

people will complain about missing JavaDoc,

That is their problem. Nobody in their right mind tries to rigidly apply their organization's source code / documentation rules to third-party open source software. The project team should be free to set project source code / documentation standards that are appropriate to the technology being used.

(FOLLOWUP - The Lombok developers recognize that not generating javadoc comments for synthesized getter and setter methods is an issue. If this is a major problem for your project(s), then one alternative is to create and submit a Lombok patch to address this.)

and future commiters might just remove it all anyway.

That's not on! If the agreed project strategy is to use Lombok, then commiters who gratuitously de-Lombok the code should be chastised, and if necessary have their commit rights withdrawn.

Of course, this assumes that you've got buy-in from the stakeholders ... including the developers. And it assumes that you are prepared to argue your cause, and appropriately handle the inevitable dissenting voices.

Counting Line Numbers in Eclipse

Search > File Search

Check the Regular expression box.

Use this expression:

\n[\s]*

Select whatever file types (*.java, *.xml, etc..) and working sets are appropriate for you.

Connect Bluestacks to Android Studio

Steps to connect Blue Stack with Android Studio

  1. Close Android Studio.
  2. Go to adb.exe location (default location: %LocalAppData%\Android\sdk\platform-tools)
  3. Run adb connect localhost:5555 from this location.
  4. Start Android Studio and you will get Blue Stack as emulator when you run your app.

XSLT string replace

You can use the following code when your processor runs on .NET or uses MSXML (as opposed to Java-based or other native processors). It uses msxsl:script.

Make sure to add the namespace xmlns:msxsl="urn:schemas-microsoft-com:xslt" to your root xsl:stylesheet or xsl:transform element.

In addition, bind outlet to any namespace you like, for instance xmlns:outlet = "http://my.functions".

<msxsl:script implements-prefix="outlet" language="javascript">
function replace_str(str_text,str_replace,str_by)
{
     return str_text.replace(str_replace,str_by);
}
</msxsl:script>


<xsl:variable name="newtext" select="outlet:replace_str(string(@oldstring),'me','you')" />

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

How to ensure a <select> form field is submitted when it is disabled?

it dows not work with the :input selector for select fields, use this:

    jQuery(function() {

    jQuery('form').bind('submit', function() {
        jQuery(this).find(':disabled').removeAttr('disabled');
    });

    });

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

Delete all lines starting with # or ; in Notepad++

Find:

^[#;].*

Replace with nothing. The ^ indicates the start of a line, the [#;] is a character class to match either # or ;, and .* matches anything else in the line.

In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:

# foo
; bar
statement;

Will turn into:



statement;

However, the replacement will work in Notepad++ 6.0 if you add \r, \n or \r\n to the end of the pattern, depending on which line ending your file is using, resulting in:

statement;

Validate phone number with JavaScript

try this

/^(\+{0,})(\d{0,})([(]{1}\d{1,3}[)]{0,}){0,}(\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}(\s){0,}$/gm

valid formats

  • (123) 456-7890
  • (123)456-7890
  • 123-456-7890
  • 1234567890
  • +31636363634
  • +3(123) 123-12-12
  • +3(123)123-12-12
  • +3(123)1231212
  • +3(123) 12312123
  • +3(123) 123 12 12
  • 075-63546725
  • +7910 120 54 54
  • 910 120 54 54
  • 8 999 999 99 99

https://regex101.com/r/QXAhGV/1

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

you could try

$('*').not('#div').bind('touchmove', false);

add this if necessary

$('#div').bind('touchmove');

note that everything is fixed except #div

How Best to Compare Two Collections in Java and Act on Them?

I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I'm lazy) solution. I have an assumption that the Foo class is comparable based on it's unique id and not all of the data in it's contents:

Collection<Foo> oldSet = ...;
Collection<Foo> newSet = ...;

private Collection difference(Collection a, Collection b) {
    Collection result = a.clone();
    result.removeAll(b)
    return result;
}

private Collection intersection(Collection a, Collection b) {
    Collection result = a.clone();
    result.retainAll(b)
    return result;
}

public doWork() {
    // if foo is in(*) oldSet but not newSet, call doRemove(foo)
    Collection removed = difference(oldSet, newSet);
    if (!removed.isEmpty()) {
        loop removed {
            Foo foo = removedIter.next();
            doRemove(foo);
        }
    }
    //else if foo is not in oldSet but in newSet, call doAdd(foo)
    Collection added = difference(newSet, oldSet);
    if (!added.isEmpty()) {
        loop added  {
            Foo foo = addedIter.next();
            doAdd(foo);
        }
    }

    // else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
    Collection matched = intersection(oldSet, newSet);
    Comparator comp = new Comparator() {
        int compare(Object o1, Object o2) {
            Foo f1, f2;
            if (o1 instanceof Foo) f1 = (Foo)o1;
            if (o2 instanceof Foo) f2 = (Foo)o2;
            return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;
        }

        boolean equals(Object o) {
             // equal to this Comparator..not used
        }
    }
    loop matched {
        Foo foo = matchedIter.next();
        Foo oldFoo = oldSet.get(foo);
        Foo newFoo = newSet.get(foo);
        if (comp.compareTo(oldFoo, newFoo ) != 0) {
            doUpdate(oldFoo, newFoo);
        } else {
            //else if !foo.activated && foo.startDate >= now, call doStart(foo)
            if (!foo.activated && foo.startDate >= now) doStart(foo);

            // else if foo.activated && foo.endDate <= now, call doEnd(foo)
            if (foo.activated && foo.endDate <= now) doEnd(foo);
        }
    }
}

As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT...you would probably use more memory and time during the conversion.

Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek 's advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.

How to fix libeay32.dll was not found error

I've encountered this kind of problem before. I was using the Windows x64 operating system, so I was getting an error in openssl. Later I realized that the path to the OpenSSL installation file was "C: \ OpenSSL win32". Finally, I deleted the OpenSSL program and installed it to "C: \ Program Files (x86)" and used it smoothly.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

Aren't Python strings immutable? Then why does a + " " + b work?

This image gives the answer. Please read it.

enter image description here

sendmail: how to configure sendmail on ubuntu?

I got the top answer working (can't reply yet) after one small edit

This did not work for me:

FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl

The first single quote for each string should be changed to a backtick (`) like this:

FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl

After the change I run:

sudo sendmailconfig

And I'm in business :)

How to split a string with any whitespace chars as delimiters

String str = "Hello   World";
String res[] = str.split("\\s+");

GROUP BY without aggregate function

That's how GROUP BY works. It takes several rows and turns them into one row. Because of this, it has to know what to do with all the combined rows where there have different values for some columns (fields). This is why you have two options for every field you want to SELECT : Either include it in the GROUP BY clause, or use it in an aggregate function so the system knows how you want to combine the field.

For example, let's say you have this table:

Name | OrderNumber
------------------
John | 1
John | 2

If you say GROUP BY Name, how will it know which OrderNumber to show in the result? So you either include OrderNumber in group by, which will result in these two rows. Or, you use an aggregate function to show how to handle the OrderNumbers. For example, MAX(OrderNumber), which means the result is John | 2 or SUM(OrderNumber) which means the result is John | 3.

Using Pip to install packages to Anaconda Environment

If you ONLY want to have a conda installation. Just remove all of the other python paths from your PATH variable.

Leaving only:

C:\ProgramData\Anaconda3
C:\ProgramData\Anaconda3\Scripts
C:\ProgramData\Anaconda3\Library\bin

This allows you to just use pip install * and it will install straight into your conda installation.

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

Best way to get hostname with php

You could also use...

$hostname = getenv('HTTP_HOST');

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

How do I load a file from resource folder?

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
    // Process line
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.

Where does application data file actually stored on android device?

Application Private Data files are stored within <internal_storage>/data/data/<package>

Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()

When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

try this

provider = new CultureInfo("en-US");
DateTime.ParseExact("9/1/2009", "M/d/yyyy", provider);

Bye.

How to check if an environment variable exists and get its value?

All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:

sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"

A Windows equivalent of the Unix tail command

I'd suggest installing something like GNU Utilities for Win32. It has most favourites, including tail.

How do I update a Mongo document after inserting it?

mycollection.find_one_and_update({"_id": mongo_id}, 
                                 {"$set": {"newfield": "abc"}})

should work splendidly for you. If there is no document of id mongo_id, it will fail, unless you also use upsert=True. This returns the old document by default. To get the new one, pass return_document=ReturnDocument.AFTER. All parameters are described in the API.

The method was introduced for MongoDB 3.0. It was extended for 3.2, 3.4, and 3.6.

'str' object does not support item assignment in Python

The other answers are correct, but you can, of course, do something like:

>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>

if you really want to.

To delay JavaScript function call using jQuery

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

setTimeout(sample,2000)

How to remove a newline from a string in Bash

Clean your variable by removing all the carriage returns:

COMMAND=$(echo $COMMAND|tr -d '\n')

How to tell bash that the line continues on the next line

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat
foo

# && and ||
$ echo foo &&
> echo bar
foo
bar
$ false ||
> echo bar
bar

Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.

$ x="foo
> bar"
$ echo "$x"
foo
bar

With a backslash, you are again splitting the logical line into multiple logical lines.

$ x="foo\
> bar"
$ echo "$x"
foobar

jquery $(window).height() is returning the document height

With no doctype tag, Chrome reports the same value for both calls.

Adding a strict doctype like <!DOCTYPE html> causes the values to work as advertised.

The doctype tag must be the very first thing in your document. E.g., you can't have any text before it, even if it doesn't render anything.

How do I remove a submodule?

I had to take John Douthat's steps one step further and cd into the submodule's directory, and then remove the Git repository:

cd submodule
rm -fr .git

Then I could commit the files as a part of the parent Git repository without the old reference to a submodule.

Best Regular Expression for Email Validation in C#

First option (bad because of throw-catch, but MS will do work for you):

bool IsValidEmail(string email)
{
    try {
        var mail = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

How to use Servlets and Ajax?

Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:

Jsp page java script function to submit data to servlet with two variable firstName and lastName:

function onChangeSubmitCallWebServiceAJAX()
    {
      createXmlHttpRequest();
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
      +firstName+"&lastName="+lastName,true)
      xmlHttp.onreadystatechange=handleStateChange;
      xmlHttp.send(null);

    }

Servlet to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>"+firstName+"</firstName>");
    response.getWriter().write("<lastName>"+lastName+"</lastName>");
    response.getWriter().write("</details>");
}

Reading a binary file with python

Read the binary file content like this:

with open(fileName, mode='rb') as file: # b is important -> binary
    fileContent = file.read()

then "unpack" binary data using struct.unpack:

The start bytes: struct.unpack("iiiii", fileContent[:20])

The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i' to create the correct format for the unpack method:

struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])

The end byte: struct.unpack("i", fileContent[-4:])

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

HTTP Error 500.30 - ANCM In-Process Start Failure

I had an issue in my Program.cs file. I was trying to connect with AddAzureKeyVault that had been deleted long time ago.

Conclusion:

This error could come to due to any silly error in the application. Debug step by step your application startup process.

C#: How to access an Excel cell?

Try:

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));

oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();

oSheet.Cells[3, 9] = "Some Text"

Java, Calculate the number of days between two dates

This function is good for me:

public static int getDaysCount(Date begin, Date end) {
    Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin);
    start.set(Calendar.MILLISECOND, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.HOUR_OF_DAY, 0);

    Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end);
    finish.set(Calendar.MILLISECOND, 999);
    finish.set(Calendar.SECOND, 59);
    finish.set(Calendar.MINUTE, 59);
    finish.set(Calendar.HOUR_OF_DAY, 23);

    long delta = finish.getTimeInMillis() - start.getTimeInMillis();
    return (int) Math.ceil(delta / (1000.0 * 60 * 60 * 24));
}

How can I grep for a string that begins with a dash/hyphen?

The correct way would be to use "--" to stop processing arguments, as already mentioned. This is due to the usage of getopt_long (GNU C-function from getopt.h) in the source of the tool.

This is why you notice the same phenomena on other command-line tools; since most of them are GNU tools, and use this call,they exhibit the same behavior.

As a side note - getopt_long is what gives us the cool choice between -rlo and --really_long_option and the combination of arguments in the interpreter.

Parse string to date with moment.js

I always seem to find myself landing here only to realize that the title and question are not quite aligned.

If you want a moment date from a string:

const myMomentObject = moment(str, 'YYYY-MM-DD')

From moment documentation:

Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object.

If you instead want a javascript Date object from a string:

const myDate = moment(str, 'YYYY-MM-DD').toDate();

cannot load such file -- bundler/setup (LoadError)

I had almost precisely the same error, and was able to completely fix it simply by running:

gem install bundler

It's possible your bundler installation is corrupt or missing - that's what happened in my case. Note that if the above fails you can try:

sudo gem install bundler

...but generally you can do it without sudo.

Getting date format m-d-Y H:i:s.u from milliseconds

Based on @ArchCodeMonkey answer.

If you have declare(strict_types=1) you must cast second argument to string

enter image description here

What is a good game engine that uses Lua?

Heroes of Might and Magic V used modified Silent Storm engine. I think you can find many good engines listed in wikipedia: Lua-scriptable game engines

Remove padding from columns in Bootstrap 3

<style>
.col-md-12{
 padding-left:0px !important;
padding-right:0px !important;
}
.col-md-8{
padding-left:0px !important;
padding-right:0px !important;
}
.col-md-4{
padding-left:0px !important;
padding-right:0px !important;
}
</style>

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

How do I parse JSON with Objective-C?

Don't reinvent the wheel. Use json-framework or something similar.

If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];

// now you can grab data out of the dictionary using objectForKey or another dictionary method

display:inline vs display:block

Add a background-color to the element and you will nicely see the difference of inline vs. block, as explained by the other posters.

Tooltips for cells in HTML table (no Javascript)

Yes. You can use the title attribute on cell elements, with poor usability, or you can use CSS tooltips (several existing questions, possibly duplicates of this one).

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

Cannot call getSupportFragmentManager() from activity

This worked for me. Running android API 19 and above.

FragmentManager fragMan = getFragmentManager();

CSS background image URL failing to load

Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:

background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");

Alternatively, you can try to use file:/// protocol prefix.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

What is float in Java?

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.

How do I put hint in a asp:textbox

Just write like this:

<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>

If Else in LINQ

This might work...

from p in db.products
    select new
    {
        Owner = (p.price > 0 ?
            from q in db.Users select q.Name :
            from r in db.ExternalUsers select r.Name)
    }

How do I escape a reserved word in Oracle?

Oracle normally requires double-quotes to delimit the name of identifiers in SQL statements, e.g.

SELECT "MyColumn" AS "MyColAlias"
FROM "MyTable" "Alias"
WHERE "ThisCol" = 'That Value';

However, it graciously allows omitting the double-quotes, in which case it quietly converts the identifier to uppercase:

SELECT MyColumn AS MyColAlias
FROM MyTable Alias
WHERE ThisCol = 'That Value';

gets internally converted to something like:

SELECT "ALIAS" . "MYCOLUMN" AS "MYCOLALIAS"
FROM "THEUSER" . "MYTABLE" "ALIAS"
WHERE "ALIAS" . "THISCOL" = 'That Value';

Pass values of checkBox to controller action in asp.net mvc4

<form action="Save" method="post">
 IsActive <input type="checkbox" id="IsActive" checked="checked" value="true" name="IsActive"  />

 </form>

 public ActionResult Save(Director director)
        {
                   // IsValid is my Director prop same name give    
            if(ModelState.IsValid)
            {
                DirectorVM ODirectorVM = new DirectorVM();
                ODirectorVM.SaveData(director);
                return RedirectToAction("Display");
            }
            return RedirectToAction("Add");
        }

MySQL stored procedure return value

Add:

  • DELIMITER at the beginning and end of the SP.
  • DROP PROCEDURE IF EXISTS validar_egreso; at the beginning
  • When calling the SP, use @variableName.

This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).

DROP PROCEDURE IF EXISTS `validar_egreso`;

DELIMITER $$

CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
    IN codigo_producto VARCHAR(100),
    IN cantidad INT,
    OUT valido INT(11)
)
BEGIN

    DECLARE resta INT;
    SET resta = 0;

    SELECT (codigo_producto - cantidad) INTO resta;

    IF(resta > 1) THEN
       SET valido = 1;
    ELSE
       SET valido = -1;
    END IF;

    SELECT valido;
END $$

DELIMITER ;

-- execute the stored procedure
CALL validar_egreso(4, 1, @val);

-- display the result
select @val;

Any way to make a WPF textblock selectable?

According to Windows Dev Center:

TextBlock.IsTextSelectionEnabled property

[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see the archive ]

Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API.

How to show all shared libraries used by executables in Linux?

Check shared library dependencies of a program executable

To find out what libraries a particular executable depends on, you can use ldd command. This command invokes dynamic linker to find out library dependencies of an executable.

> $ ldd /path/to/program

Note that it is NOT recommended to run ldd with any untrusted third-party executable because some versions of ldd may directly invoke the executable to identify its library dependencies, which can be security risk.

Instead, a safer way to show library dependencies of an unknown application binary is to use the following command.

$ objdump -p /path/to/program | grep NEEDED

for more info

Android emulator shows nothing except black screen and adb devices shows "device offline"

Make sure that you've installed the latest HAXM revision. I had the same blank screen problem with version 1.0.1 while 1.0.8 was already available. The installer can be downloaded via the SDK tools, to actually install the module you would have to execute

android-sdk-directory\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

iOS 7 - Failing to instantiate default view controller

This warning is also reported if you have some code like:

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.rootViewController = myAwesomeRootViewController
    window?.makeKeyAndVisible()

In this case, go to the first page of target settings and set Main Interface to empty, since you don't need a storyboard entry for your app.

No connection could be made because the target machine actively refused it?

I would like to share this answer I found because the cause of the problem was not the firewall or the process not listening correctly, it was the code sample provided from Microsoft that I used.

https://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx

I implemented this function almost exactly as written, but what happened is I got this error:

2016-01-05 12:00:48,075 [10] ERROR - The error is: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it [fe80::caa:745:a1da:e6f1%11]:4080

This code would say the socket is connected, but not under the correct IP address actually needed for proper communication. (Provided by Microsoft)

private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        // Get host related information.
        hostEntry = Dns.GetHostEntry(server);

        // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
        // an exception that occurs when the host IP Address is not compatible with the address family
        // (typical in the IPv6 case).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

I re-wrote the code to just use the first valid IP it finds. I am only concerned with IPV4 using this, but it works with localhost, 127.0.0.1, and the actually IP address of you network card, where the example provided by Microsoft failed!

    private Socket ConnectSocket(string server, int port)
    {
        Socket s = null;

        try
        {
            // Get host related information.
            IPAddress[] ips;
            ips = Dns.GetHostAddresses(server);

            Socket tempSocket = null;
            IPEndPoint ipe = null;

            ipe = new IPEndPoint((IPAddress)ips.GetValue(0), port);
            tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Platform.Log(LogLevel.Info, "Attempting socket connection to " + ips.GetValue(0).ToString() + " on port " + port.ToString());
            tempSocket.Connect(ipe);

            if (tempSocket.Connected)
            {
                s = tempSocket;
                s.SendTimeout = Coordinate.HL7SendTimeout;
                s.ReceiveTimeout = Coordinate.HL7ReceiveTimeout;
            }
            else
            {
                return null;
            }

            return s;
        }
        catch (Exception e)
        {
            Platform.Log(LogLevel.Error, "Error creating socket connection to " + server + " on port " + port.ToString());
            Platform.Log(LogLevel.Error, "The error is: " + e.ToString());
            if (g_NoOutputForThreading == false)
                rtbResponse.AppendText("Error creating socket connection to " + server + " on port " + port.ToString());
            return null;
        }
    }

is there a post render callback for Angular JS directive?

Following the fact that the load order cannot be anticipated, a simple solution can be used.

Let's look at the directive-'user of directive' relationship. Usually the user of the directive will supply some data to the directive or use some functionality ( functions ) the directive supplies. The directive on the other hand expects some variables to be defined on its scope.

If we can make sure that all players have all their action requirements fulfilled before they attempt to execute those actions - everything should be well.

And now the directive:

app.directive('aDirective', function () {
    return {
        scope: {
            input: '=',
            control: '='
        },
        link: function (scope, element) {
            function functionThatNeedsInput(){
                //use scope.input here
            }
            if ( scope.input){ //We already have input 
                functionThatNeedsInput();
            } else {
                scope.control.init = functionThatNeedsInput;
            }
          }

        };
})

and now the user of the directive html

<a-directive control="control" input="input"></a-directive>

and somewhere in the controller of the component that uses the directive:

$scope.control = {};
...
$scope.input = 'some data could be async';
if ( $scope.control.functionThatNeedsInput){
    $scope.control.functionThatNeedsInput();
}

That's about it. There is a lot of overhead but you can lose the $timeout. We also assume that the component that uses the directive is instantiated before the directive because we depend on the control variable to exist when the directive is instantiated.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

I think your issue may be in the url pattern. Changing

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

and

<form action="/Register" method="post">

may fix your problem

Prevent Sequelize from outputting SQL to the console on execution of query?

As in other answers, you can just set logging:false, but I think better than completely disabling logging, you can just embrace log levels in your app. Sometimes you may want to take a look at the executed queries so it may be better to configure Sequelize to log at level verbose or debug. for example (I'm using winston here as a logging framework but you can use any other framework) :

var sequelize = new Sequelize('database', 'username', 'password', {
  logging: winston.debug
});

This will output SQL statements only if winston log level is set to debug or lower debugging levels. If log level is warn or info for example SQL will not be logged

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

how to call a function from another function in Jquery

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

Test if object implements interface

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Passing Arrays to Function in C++

I just wanna add this, when you access the position of the array like

arg[n]

is the same as

*(arg + n) than means an offset of n starting from de arg address.

so arg[0] will be *arg

Check if an element contains a class in JavaScript?

in which element is currently the class '.bar' ? Here is another solution but it's up to you.

var reg = /Image/g, // regexp for an image element
query = document.querySelector('.bar'); // returns [object HTMLImageElement]
query += this.toString(); // turns object into a string

if (query.match(reg)) { // checks if it matches
  alert('the class .bar is attached to the following Element:\n' + query);
}

jsfiddle demo

Of course this is only a lookup for 1 simple element <img>(/Image/g) but you can put all in an array like <li> is /LI/g, <ul> = /UL/g etc.

How can I compare a date and a datetime in Python?

Create and similar object for comparison works too ex:

from datetime import datetime, date

now = datetime.now()
today = date.today()

# compare now with today
two_month_earlier = date(now.year, now.month - 2, now.day)
if two_month_earlier > today:
    print(True)

two_month_earlier = datetime(now.year, now.month - 2, now.day)
if two_month_earlier > now:
   print("this will work with datetime too")

send checkbox value in PHP form

If the checkbox is checked you will get a value for it in your $_POST array. If it isn't the element will be omitted from the array altogether.

The easiest way to test it is like this:

if (isset($_POST['myCheckbox'])) {
  $checkBoxValue = "yes";
} else {
  $checkBoxValue = "no";
}

For your code, add it immediately below the other preprocessing:

$name = $_POST['name']; 
$email_address = $_POST['email']; 
$message = $_POST['tel']; 

if (isset($_POST['newsletter'])) {
  $newsletter = "yes";
} else {
  $newsletter = "no";
}

You'll also need to change the HTML slightly. Change this line:

<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>

to this:

<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up   for newsletter<br>
                                      ^^^ remove square brackets here.

How to make rpm auto install dependencies

For dnf users just use dnf install *.rpm, localinstall is no longer needed.

Print out the values of a (Mat) matrix in OpenCV C++

See the first answer to Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
Then just loop over all the elements in cout << M.at<double>(0,0); rather than just 0,0

Or better still with the C++ interface:

cv::Mat M;
cout << "M = " << endl << " "  << M << endl << endl;

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

Simple if else onclick then do?

You may use jQuery in it like

$('#yesh').click(function(){
     *****HERE GOES THE FUNCTION*****
});

Besides jQuery is easy to use.

You can make changes in colors etc using simple jQUery or Javascript.

How to specify legend position in matplotlib in graph coordinates

According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.

get UTC timestamp in python with datetime

I think the correct way to phrase your question is Is there a way to get the timestamp by specifying the date in UTC?, because timestamp is just a number which is absolute, not relative. The relative (or timezone aware) piece is the date.

I find pandas very convenient for timestamps, so:

import pandas as pd
dt1 = datetime(2008, 1, 1, 0, 0, 0, 0)
ts1 = pd.Timestamp(dt1, tz='utc').timestamp()
# make sure you get back dt1
datetime.utcfromtimestamp(ts1)  

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

From IEEE floating-point exceptions in C++ :

This page will answer the following questions.

  • My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
  • How can I tell if a number is really a number and not a NaN or an infinity?
  • How can I find out more details at runtime about kinds of NaNs and infinities?
  • Do you have any sample code to show how this works?
  • Where can I learn more?

These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.

Removing fields from struct or hiding them in JSON Response

Here is how I defined my structure.

type User struct {
    Username string  `json:"username" bson:"username"`
    Email    string  `json:"email" bson:"email"`
    Password *string `json:"password,omitempty" bson:"password"`
    FullName string  `json:"fullname" bson:"fullname"`
}

And inside my function set user.Password = nil for not to be Marshalled.

Sequence contains no elements?

I had a similar situation on a function that calculates the average.

Example:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();

Case Solved:

ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

Displaying unicode symbols in HTML

You should ensure the HTTP server headers are correct.

In particular, the header:

Content-Type: text/html; charset=utf-8

should be present.

The meta tag is ignored by browsers if the HTTP header is present.

Also ensure that your file is actually encoded as UTF-8 before serving it, check/try the following:

  • Ensure your editor save it as UTF-8.
  • Ensure your FTP or any file transfer program does not mess with the file.
  • Try with HTML encoded entities, like &#uuu;.
  • To be really sure, hexdump the file and look as the character, for the ?, it should be E2 9C 94 .

Note: If you use an unicode character for which your system can't find a glyph (no font with that character), your browser should display a question mark or some block like symbol. But if you see multiple roman characters like you do, this denotes an encoding problem.

What is object slicing?

I see all the answers mention when object slicing happens when data members are sliced. Here I give an example that the methods are not overridden:

class A{
public:
    virtual void Say(){
        std::cout<<"I am A"<<std::endl;
    }
};

class B: public A{
public:
    void Say() override{
        std::cout<<"I am B"<<std::endl;
    }
};

int main(){
   B b;
   A a1;
   A a2=b;

   b.Say(); // I am B
   a1.Say(); // I am A
   a2.Say(); // I am A   why???
}

B (object b) is derived from A (object a1 and a2). b and a1, as we expect, call their member function. But from polymorphism viewpoint we don’t expect a2, which is assigned by b, to not be overridden. Basically, a2 only saves A-class part of b and that is object slicing in C++.

To solve this problem, a reference or pointer should be used

 A& a2=b;
 a2.Say(); // I am B

or

A* a2 = &b;
a2->Say(); // I am B

For more details see my post

How do I compile a Visual Studio project from the command-line?

Using msbuild as pointed out by others worked for me but I needed to do a bit more than just that. First of all, msbuild needs to have access to the compiler. This can be done by running:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"

Then msbuild was not in my $PATH so I had to run it via its explicit path:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" myproj.sln

Lastly, my project was making use of some variables like $(VisualStudioDir). It seems those do not get set by msbuild so I had to set them manually via the /property option:

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" /property:VisualStudioDir="C:\Users\Administrator\Documents\Visual Studio 2013" myproj.sln

That line then finally allowed me to compile my project.

Bonus: it seems that the command line tools do not require a registration after 30 days of using them like the "free" GUI-based Visual Studio Community edition does. With the Microsoft registration requirement in place, that version is hardly free. Free-as-in-facebook if anything...

How to programmatically round corners and set random background colors

Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( R.id.my_view );
 view.setBackground(shape);

Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius because ShapeDrawable DOES NOT provide any such method.

What is the worst programming language you ever worked with?

I find myself avoid having to use VBScript/Visual Basic 6 the most.

I use primarily C++, javascript, Java for most tasks and dabble in ruby, scala, erlang, python, assembler, perl when the need arises.

I, like most other reasonably minded polyglots/programmers, strongly feel that you have to use the right tool for the job - this requires you to understand your domain and to understand your tools.

My issue with VBscript and VB6 is when I use them to script windows or office applications (the right domain for them) - i find myself struggling with the language (they fall short of being the right tool).

VBScript's lack of easy to use native data structures (such as associative containers/maps) and other quirks (such as set for assignment to objects) is a needless and frustrating annoyance, especially for a scripting language. Contrast it with Javascript (which i now use to program wscript/cscript windows and do activex automation scripts) which is far more expressive. While there are certain things that work better with vbscript (such as passing arrays back and forth from COM objects is slightly easier, although it is easier to pass event handlers into COM components with jscript), I am still surprised by the amount of coders that still use vbscript to script windows - I bet if they wrote the same program in both languages they would find that jscript works with you much more than vbscript, because of jscript's native hash data types and closures.

Vb6/VBA, though a little better than vbscript in general, still has many similar issues where (for their domain) they require much more boiler plate to do simple tasks than what I would like and have seen in other scripting languages.

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

sort files by date in PHP

An example that uses RecursiveDirectoryIterator class, it's a convenient way to iterate recursively over filesystem.

$output = array();
foreach( new RecursiveIteratorIterator( 
    new RecursiveDirectoryIterator( 'path', FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS ) ) as $value ) {      
        if ( $value->isFile() ) {
            $output[] = array( $value->getMTime(), $value->getRealPath() );
        }
}

usort ( $output, function( $a, $b ) {
    return $a[0] > $b[0];
});

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

static constructors in C++? I need to initialize private static objects

To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class.

class StaticStuff
{
     std::vector<char> letters_;

public:
     StaticStuff()
     {
         for (char c = 'a'; c <= 'z'; c++)
             letters_.push_back(c);
     }

     // provide some way to get at letters_
};

class Elsewhere
{
    static StaticStuff staticStuff; // constructor runs once, single instance

};

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

This combination of the above answers solved the problem for me:

  • performed the Java update:

    sudo apt-get install default-jdk

  • then killed the Arduino IDE and restarted it

  • my correct board now showed up (Arduino Mega 2560, where before Mega 1280 was only option)

  • for the drivers, I did this:

    sudo chmod a+rw /dev/serial/by-id/usb-Arduino__www.arduino.cc__(a bunch of numbers)

After that, my Arduino IDE shows /dev/ttyACM0 in the tools/serial port menu.

Now, everything works great!

TypeError: Router.use() requires middleware function but got a Object

In my case i wasn't exporting the module. module.exports = router;

How to change the default docker registry from docker.io to my private registry?

There is the use case of a mirror of Docker Hub (such as Artifactory or a custom one), which I haven't seen mentioned here. This is one of the most valid cases where changing the default registry is needed.

Luckily, Docker (at least version 19.03.3) allows you to set a mirror (tested in Docker CE). I don't know if this will work with additional images pushed to that mirror that aren't on Docker Hub, but I do know it will use the mirror instead. Docker documentation: https://docs.docker.com/registry/recipes/mirror/#configure-the-docker-daemon.

Essentially, you need to add "registry-mirrors": [] to the /etc/docker/daemon.json configuration file. So if you have a mirror hosted at https://my-docker-repo.my.company.com, your /etc/docker/daemon.json should contain:

{
  "registry-mirrors": ["https://my-docker-repo-mirror.my.company.com"]
}

Afterwards, restart the Docker daemon. Now if you do a docker pull postgres:12, Docker should fetch the image from the mirror instead of directly from Docker Hub. This is much better than prepending all images with my-docker-repo.my.company.com

Taking multiple inputs from user in python

You could use the below to take multiple inputs separated by a keyword

a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')

dyld: Library not loaded ... Reason: Image not found

Making the Frameworks in the Build Phases optional worked for me.

In Xcode -> Target -> Build Phases -> Link Binary with Libraries -> Make sure the newly added frameworks if any are marked as Optional

Editing an item in a list<T>

After adding an item to a list, you can replace it by writing

list[someIndex] = new MyClass();

You can modify an existing item in the list by writing

list[someIndex].SomeProperty = someValue;

EDIT: You can write

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);

How to use custom packages

For this kind of folder structure:

main.go
mylib/
  mylib.go

The simplest way is to use this:

import (
    "./mylib"
)

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Play audio with Python

For those who use Linux and the other packages haven't worked on MP3 files, audioplayer worked fine for me:

https://pypi.org/project/audioplayer/

from audioplayer import AudioPlayer<br>
AudioPlayer("path/to/somemusic.mp3").play(block=True)

Hibernate: get entity by id

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...

Mysql password expired. Can't connect

i have faced this issue few days ago. For best solution for 5.7 version of MySQL; login your mysql console and alter your password with the following command:

ALTER USER `root`@`localhost` IDENTIFIED BY 'new_password', `root`@`localhost` PASSWORD EXPIRE NEVER;

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

My docker container has no internet

Fixed by following this advice:

[...] can you try to reset everything?

pkill docker
iptables -t nat -F
ifconfig docker0 down
brctl delbr docker0
docker -d

It will force docker to recreate the bridge and reinit all the network rules

https://github.com/dotcloud/docker/issues/866#issuecomment-19218300

Seems the interface was 'hung' somehow.

Update for more recent versions of docker:

The above answer might still get the job done for you but it has been quite a long time since this answer was posted and docker is more polished now so make sure you try these first before going into mangling with iptables and all.

sudo service docker restart or (if you are in a linux distro that does not use upstart) sudo systemctl restart docker

How to paste into a terminal?

Mostly likely middle click your mouse.

Or try Shift + Insert.

It all depends on terminal used and X11-config for mouse.

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Printing list elements on separated lines in Python

sys.path returns the list of paths

ref

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

import sys
dirs=sys.path
for path in dirs:
   print(path)

or you can print only first path by

print(dir[0])

HTTP vs HTTPS performance

Since I am investigating same problem for my project, I found these slides. Older but interesting:

http://www.cs.nyu.edu/artg/research/comparison/comparison_slides/sld001.htm

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

how to remove new lines and returns from php string?

You have to wrap \n or \r in "", not ''. When using single quotes escape sequences will not be interpreted (except \' and \\).

The manual states:

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

  • \n linefeed (LF or 0x0A (10) in ASCII)

  • \r carriage return (CR or 0x0D (13) in ASCII)\

  • (...)

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

Copy filtered data to another sheet using VBA

When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).

Example:

Sub copy()
     'source worksheet
     dim ws as Worksheet
     set ws = Application.Worksheets("Data")' set you source worksheet here
     dim data_end_row_number as Integer
     data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
    'enable filter
    ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
    ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
    Application.Worksheets("Hoky").Range("B3").Paste
    'You have to add headers to Hoky worksheet
end sub

Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

Java String array: is there a size of method?

If you want a function to do this

Object array = new String[10];
int size = Array.getlength(array);

This can be useful if you don't know what type of array you have e.g. int[], byte[] or Object[].

T-SQL stored procedure that accepts multiple Id values

One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.

This way, you're only parsing once.

It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)

This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.

IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
BEGIN
    DROP TABLE #tmpDept
END

SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')

CREATE TABLE #tmpDept (DeptID INT)
DECLARE @DeptID INT
IF IsNumeric(@DepartmentIDs)=1
BEGIN
    SET @DeptID=@DepartmentIDs
    INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
ELSE
BEGIN
        WHILE CHARINDEX(',',@DepartmentIDs)>0
        BEGIN
            SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
            SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
            INSERT INTO #tmpDept (DeptID) SELECT @DeptID
        END
END

This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.

So if you did something like:

SELECT Dept.Name 
FROM Departments 
JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
ORDER BY Dept.Name

You would see the names of all of the department IDs that you passed in...

Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P

-- Kevin Fairchild

Angular2, what is the correct way to disable an anchor element?

   .disabled{ pointer-events: none }

will disable the click event, but not the tab event. To disable the tab event, you can set the tabindex to -1 if the disable flag is true.

<li [routerLinkActive]="['active']" [class.disabled]="isDisabled">
     <a [routerLink]="['link']" tabindex="{{isDisabled?-1:0}}" > Menu Item</a>
</li>

Viewing full version tree in git

if you happen to not have a graphical interface available you can also print out the commit graph on the command line:

git log --oneline --graph --decorate --all

if this command complains with an invalid option --oneline, use:

git log --pretty=oneline --graph --decorate --all

Typescript export vs. default export

Named export

In TS you can export with the export keyword. It then can be imported via import {name} from "./mydir";. This is called a named export. A file can export multiple named exports. Also the names of the imports have to match the exports. For example:

// foo.js file
export class foo{}
export class bar{}

// main.js file in same dir
import {foo, bar} from "./foo";

The following alternative syntax is also valid:

// foo.js file
function foo() {};
function bar() {};
export {foo, bar};

// main.js file in same dir
import {foo, bar} from './foo'

Default export

We can also use a default export. There can only be one default export per file. When importing a default export we omit the square brackets in the import statement. We can also choose our own name for our import.

// foo.js file
export default class foo{}

// main.js file in same directory
import abc from "./foo";

It's just JavaScript

Modules and their associated keyword like import, export, and export default are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.

How to center text vertically with a large font-awesome icon?

Simply define vertical-align property for the icon element:

div .icon {
   vertical-align: middle;
}

Using Image control in WPF to display System.Drawing.Bitmap

I wrote a program with wpf and used Database for showing images and this is my code:

SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
                                      Initial Catalog=Payam;
                                      Integrated Security=True");

SqlDataAdapter da = new SqlDataAdapter("select * from news", con);

DataTable dt = new DataTable();
da.Fill(dt);

string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;

A reference to the dll could not be added

I had this error while writing a Windows Service. I was running Visual Studio as Administrator so that my post build commands would automatically install my service. I noticed that when I closed everything and ran VS normally (Not as Administrator) it let me add the references just fine with no error.

Hope this solution works for you.

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

Typescript Type 'string' is not assignable to type

Typescript 3.4 introduces the new 'const' assertion

You can now prevent literal types (eg. 'orange' or 'red') being 'widened' to type string with a so-called const assertion.

You will be able to do:

let fruit = 'orange' as const;  // or...
let fruit = <const> 'orange';

And then it won't turn itself into a string anymore - which is the root of the problem in the question.

How to set the text color of TextView in code?

You can use textView.setTextColor(Color.BLACK) to use any of the in-built colors of the Color class.

You can also use textView.setTextColor(Color.parseColor(hexRGBvalue)) to define custom colors.

Anonymous method in Invoke call

I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):

    // Create delegates for the different return types needed.
    private delegate void VoidDelegate();
    private delegate Boolean ReturnBooleanDelegate();
    private delegate Hashtable ReturnHashtableDelegate();

    // Now use the delegates and the delegate() keyword to create 
    // an anonymous method as required

    // Here a case where there's no value returned:
    public void SetTitle(string title)
    {
        myWindow.Invoke(new VoidDelegate(delegate()
        {
            myWindow.Text = title;
        }));
    }

    // Here's an example of a value being returned
    public Hashtable CurrentlyLoadedDocs()
    {
        return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()
        {
            return myWindow.CurrentlyLoadedDocs;
        }));
    }

How to list imported modules?

let say you've imported math and re:

>>import math,re

now to see the same use

>>print(dir())

If you run it before the import and after the import, one can see the difference.

What is getattr() exactly and how do I use it?

I have tried in Python2.7.17

Some of the fellow folks already answered. However I have tried to call getattr(obj, 'set_value') and this didn't execute the set_value method, So i changed to getattr(obj, 'set_value')() --> This helps to invoke the same.

Example Code:

Example 1:

    class GETATT_VERIFY():
       name = "siva"
       def __init__(self):
           print "Ok"
       def set_value(self):
           self.value = "myself"
           print "oooh"
    obj = GETATT_VERIFY()
    print getattr(GETATT_VERIFY, 'name')
    getattr(obj, 'set_value')()
    print obj.value

Variable length (Dynamic) Arrays in Java

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

But your best option is to use IntList from jacarta commons. (here)

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

JBoss debugging in Eclipse

What @VonC says is correct, but you can put the commands to set debug directly into VM arguments on jBoss Launch.

To do that, open jBoss server inside Eclipse, go to Open launch configuration and put this in VM arguments textbox: vm args

How can I determine if an image has loaded, using Javascript/jQuery?

You want to do what Allain said, however be aware that sometimes the image loads before dom ready, which means your load handler won't fire. The best way is to do as Allain says, but set the src of the image with javascript after attaching the load hander. This way you can guarantee that it fires.

In terms of accessibility, will your site still work for people without javascript? You may want to give the img tag the correct src, attach you dom ready handler to run your js: clear the image src (give it a fixed with and height with css to prevent the page flickering), then set your img load handler, then reset the src to the correct file. This way you cover all bases :)

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

How to check what user php is running as?

exec('whoami') will do this

<?php
echo exec('whoami');
?>

Refresh Fragment at reload

This will refresh current fragment :

FragmentTransaction ft = getFragmentManager().beginTransaction();
if (Build.VERSION.SDK_INT >= 26) {
   ft.setReorderingAllowed(false);
}
ft.detach(this).attach(this).commit();

Android Overriding onBackPressed()

Just use the following code with initializing a field

private int count = 0;
    @Override
public void onBackPressed() {
    count++;
    if (count >=1) {
        /* If count is greater than 1 ,you can either move to the next 
        activity or just quit. */
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition
        (R.anim.push_left_in, R.anim.push_left_out);
        /* Quitting */
        finishAffinity();
    } else {
        Toast.makeText(this, "Press back again to Leave!", Toast.LENGTH_SHORT).show();

        // resetting the counter in 2s
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                count = 0;
            }
        }, 2000);
    }
    super.onBackPressed();
}

Iterator over HashMap in Java

Iterator through keySet will give you keys. You should use entrySet if you want to iterate entries.

HashMap hm = new HashMap();

hm.put(0, "zero");
hm.put(1, "one");

Iterator iter = (Iterator) hm.entrySet().iterator();

while(iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();
    System.out.println(entry.getKey() + " - " + entry.getValue());

}

Django: multiple models in one template using forms

I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.

Am I missing something here ?

class UserProfileForm(ModelForm):
    def __init__(self, instance=None, *args, **kwargs):
        # Add these fields from the user object
        _fields = ('first_name', 'last_name', 'email',)
        # Retrieve initial (current) data from the user object
        _initial = model_to_dict(instance.user, _fields) if instance is not None else {}
        # Pass the initial data to the base
        super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
        # Retrieve the fields from the user model and update the fields with it
        self.fields.update(fields_for_model(User, _fields))

    class Meta:
        model = UserProfile
        exclude = ('user',)

    def save(self, *args, **kwargs):
        u = self.instance.user
        u.first_name = self.cleaned_data['first_name']
        u.last_name = self.cleaned_data['last_name']
        u.email = self.cleaned_data['email']
        u.save()
        profile = super(UserProfileForm, self).save(*args,**kwargs)
        return profile

Making text background transparent but not text itself

Don't use opacity for this, set the background to an RGBA-value instead to only make the background semi-transparent. In your case it would be like this.

.content {
    padding:20px;
    width:710px;
    position:relative;
    background: rgb(204, 204, 204); /* Fallback for older browsers without RGBA-support */
    background: rgba(204, 204, 204, 0.5);
}

See http://css-tricks.com/rgba-browser-support/ for more info and samples of rgba-values in css.

Set order of columns in pandas dataframe

Try indexing (so you want a generic solution not only for this, so index order can be just what you want):

l=[0,2,1] # index order
frame=frame[[frame.columns[i] for i in l]]

Now:

print(frame)

Is:

   one thing second thing  other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           2.0           o

How to check variable type at runtime in Go language

It seems that Go have special form of switch dedicate to this (it is called type switch):

func (e *Easy)SetOption(option Option, param interface{}) {

    switch v := param.(type) { 
    default:
        fmt.Printf("unexpected type %T", v)
    case uint64:
        e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
    case string:
        e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
    } 
}

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

How to resolve 'unrecognized selector sent to instance'?

A lot of people have given some very technical answers for this and similar questions, but I think it's simpler than that. Sometimes if you're not paying attention a selector that you don't intend to use can be attached to something in the interface. You might be getting this error because the selector's there but you haven't written any code for it.

The easiest way to double-check that this is not the case is to control-click the item so you can see all of the selectors that are associated with it. If there's anything in there that you don't want to be, get rid of it! Hope this helps...

What is the "-->" operator in C/C++?

It's

#include <stdio.h>

int main(void) {
  int x = 10;
  while (x-- > 0) { // x goes to 0
    printf("%d ", x);
  }
  return 0;
}

Just the space makes the things look funny, -- decrements and > compares.

How to delete a specific file from folder using asp.net

Delete any or specific file type(for example ".bak") from a path. See demo code below -

class Program
        {
        static void Main(string[] args)
            {

            // Specify the starting folder on the command line, or in 
            TraverseTree(ConfigurationManager.AppSettings["folderPath"]);

            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            //TraverseTree(args[0]);

            Console.WriteLine("Press any key");
            Console.ReadKey();
            }

        public static void TraverseTree(string root)
            {

            if (string.IsNullOrWhiteSpace(root))
                return;

            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!System.IO.Directory.Exists(root))
                {
                return;
                }

            dirs.Push(root);

            while (dirs.Count > 0)
                {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                    {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                    }

                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                IEnumerable<FileInfo> files = null;
                try
                    {
                    //get only .bak file
                    var directory = new DirectoryInfo(currentDir);
                    DateTime date = DateTime.Now.AddDays(-15);
                    files = directory.GetFiles("*.bak").Where(file => file.CreationTime <= date);
                    }
                catch (UnauthorizedAccessException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }
                catch (System.IO.DirectoryNotFoundException e)
                    {
                    Console.WriteLine(e.Message);
                    continue;
                    }

                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (FileInfo file in files)
                    {
                    try
                        {
                        // Perform whatever action is required in your scenario.
                        file.Delete();
                        Console.WriteLine("{0}: {1}, {2} was successfully deleted.", file.Name, file.Length, file.CreationTime);
                        }
                    catch (System.IO.FileNotFoundException e)
                        {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                        }
                    }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
                }
            }
        }

for more reference - https://msdn.microsoft.com/en-us/library/bb513869.aspx

VBScript - How to make program wait until process has finished?

This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"

strProcess = "EXCEL.EXE"    
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
    Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
    Wscript.Sleep(1000) 'Sleep 1 second
   'msgbox colProcesses.count 'optional to show the loop works
Loop

Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/

UIScrollView not scrolling

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.

Position buttons next to each other in the center of page

your code will look something like this ...

<!doctype html>
<html lang="en">

<head>
<style>
#button1{
width: 300px;
height: 40px;

}
#button2{
width: 300px;
height: 40px;
}
display:inline-block;
</style>

<meta charset="utf-8">
<meta name="Homepage" content="Starting page for the survey website ">

 <title> Survey HomePage</title>
</head>
<body>
<center>
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
 <button type="button home-button" id="button1" >Home</button>
 <button type="button contact-button" id="button2">Contact Us</button>
</center>
</body>
 </html>

Removing all empty elements from a hash / YAML?

This one would delete empty hashes too:

swoop = Proc.new { |k, v| v.delete_if(&swoop) if v.kind_of?(Hash);  v.empty? }
hsh.delete_if &swoop

How to replace unicode characters in string with something else python?

Funny the answer is hidden in among the answers.

str.replace("•", "something") 

would work if you use the right semantics.

str.replace(u"\u2022","something") 

works wonders ;) , thnx to RParadox for the hint.

How do I pass a URL with multiple parameters into a URL?

In your example parts of your passed-in URL are not URL encoded (for example the colon should be %3A, the forward slashes should be %2F). It looks like you have encoded the parameters to your parameter URL, but not the parameter URL itself. Try encoding it as well. You can use encodeURIComponent.

How to add "active" class to wp_nav_menu() current menu item (simple way)

Just paste this code into functions.php file:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
  if (in_array('current-menu-item', $classes) ){
    $classes[] = 'active ';
  }
  return $classes;
}

More on wordpress.org:

How to sum up elements of a C++ vector?

The easiest way is to use std:accumulate of a vector<int> A:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

ValueError: not enough values to unpack (expected 11, got 1)

For the line

line.split()

What are you splitting on? Looks like a CSV, so try

line.split(',')

Example:

"one,two,three".split()  # returns one element ["one,two,three"]
"one,two,three".split(',')  # returns three elements ["one", "two", "three"]

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

ReadFile in Base64 Nodejs

Latest and greatest way to do this:

Node supports file and buffer operations with the base64 encoding:

const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

Or using the new promises API:

const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});

IE8 issue with Twitter Bootstrap 3

I also had to set the following META tag:

<meta http-equiv="X-UA-Compatible" content="IE=edge"> 

jQuery UI DatePicker to show month year only

@Ben Koehler, that's prefect! I made a minor modification so that using a single instance of the date picker more than once works as expected. Without this modification the date is parsed incorrectly and the previously selected date is not highlighted.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
    <script type="text/javascript">
    $(function() {
        $('.date-picker').datepicker( {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            onClose: function(dateText, inst) { 
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            },
            beforeShow : function(input, inst) {
                var datestr;
                if ((datestr = $(this).val()).length > 0) {
                    year = datestr.substring(datestr.length-4, datestr.length);
                    month = jQuery.inArray(datestr.substring(0, datestr.length-5), $(this).datepicker('option', 'monthNamesShort'));
                    $(this).datepicker('option', 'defaultDate', new Date(year, month, 1));
                    $(this).datepicker('setDate', new Date(year, month, 1));
                }
            }
        });
    });
    </script>
    <style>
    .ui-datepicker-calendar {
        display: none;
        }
    </style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

Size of Matrix OpenCV

A complete C++ code example, may be helpful for the beginners

#include <iostream>
#include <string>
#include "opencv/highgui.h"

using namespace std;
using namespace cv;

int main()
{
    cv:Mat M(102,201,CV_8UC1);
    int rows = M.rows;
    int cols = M.cols;

    cout<<rows<<" "<<cols<<endl;

    cv::Size sz = M.size();
    rows = sz.height;
    cols = sz.width;

    cout<<rows<<" "<<cols<<endl;
    cout<<sz<<endl;
    return 0;
}

MySQL SELECT WHERE datetime matches day (and not necessarily time)

... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26' may potentially work better(if you have an index on date_column) than DATE.

How to configure Glassfish Server in Eclipse manually

This questions seems a little bit outdated but here is my solution.

I assume that you have already downloaded GlassFish on your hard drive and unzipped the files on a directory.

A - Eclipse MarketPlace / Installing GlassFish Tools

The first thing as it is said on previous answers, you have to downloaded GlassFish Tools from eclipse marketplace;

Help -> EclipseMarket Place

enter image description here

And install GlassFish on the screen below;

enter image description here

B - Adding GlassFish Server

Open Server View, if it is not visible on the bottom of the eclipse, then;

Window -> Show View -> Servers

enter image description here

As the server view is visible, simply click "No servers are available. Click this link to create a new server..." as shown below;

enter image description here

C - Adding GlassFish Server

On the New Server window, select GlassFish as shown below. On my experience, there is only one GlassFish option that I can select, instead of several GlassFish options with versions as you can see down below;

enter image description here

D - Configuring GlassFish & Java Locations

Enter the exact GlassFish location and also Java location as you can see below;

enter image description here

E - Last Step

On the last step of this configuration, just leave everything as it is. For simplicity, I don't define an admin password;

enter image description here

Now everything is all set, hope that this helps!

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

How to make an ng-click event conditional?

We can add ng-click event conditionally without using disabled class.

HTML:

<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>

Right pad a string with variable number of spaces

The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.

SELECT CAST('Test' AS CHAR(20))

This returns the value 'Test '.

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

Oracle listener not running and won't start

I managed to resolve the issue that caused the configuration to fail on a docker container running the Hortonworks HDP 2.6 Sandbox.

If the initial configuration fails the listener will be running and will have to be killed first:

ps -aux | grep tnslsnr
kill {process id identified above}

Then next step is then to fix the shared memory issue which makes the configuration process fail.

Oracle XE requires 1 Gb of shared memory and fails otherwise (I didn't try 512 mb) according to https://blogs.oracle.com/oraclewebcentersuite/implement-oracle-database-xe-as-docker-containers.

vi /etc/fstab

change/add the line to:

tmpfs    /dev/shm     tmpfs   defaults,size=1024m 0 0

Then reload the configuration by:

mount -a

Keep in mind that the next time you restart the docker container you might have to do 'mount -a'.

Determine the type of an object?

Determine the type of a Python object

Determine the type of an object with type

>>> obj = object()
>>> type(obj)
<class 'object'>

Although it works, avoid double underscore attributes like __class__ - they're not semantically public, and, while perhaps not in this case, the builtin functions usually have better behavior.

>>> obj.__class__ # avoid this!
<class 'object'>

type checking

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.

Well that's a different question, don't use type - use isinstance:

def foo(obj):
    """given a string with items separated by spaces, 
    or a list or tuple, 
    do something sensible
    """
    if isinstance(obj, str):
        obj = str.split()
    return _foo_handles_only_lists_or_tuples(obj)

This covers the case where your user might be doing something clever or sensible by subclassing str - according to the principle of Liskov Substitution, you want to be able to use subclass instances without breaking your code - and isinstance supports this.

Use Abstractions

Even better, you might look for a specific Abstract Base Class from collections or numbers:

from collections import Iterable
from numbers import Number

def bar(obj):
    """does something sensible with an iterable of numbers, 
    or just one number
    """
    if isinstance(obj, Number): # make it a 1-tuple
        obj = (obj,)
    if not isinstance(obj, Iterable):
        raise TypeError('obj must be either a number or iterable of numbers')
    return _bar_sensible_with_iterable(obj)

Or Just Don't explicitly Type-check

Or, perhaps best of all, use duck-typing, and don't explicitly type-check your code. Duck-typing supports Liskov Substitution with more elegance and less verbosity.

def baz(obj):
    """given an obj, a dict (or anything with an .items method) 
    do something sensible with each key-value pair
    """
    for key, value in obj.items():
        _baz_something_sensible(key, value)

Conclusion

  • Use type to actually get an instance's class.
  • Use isinstance to explicitly check for actual subclasses or registered abstractions.
  • And just avoid type-checking where it makes sense.

Getting a list of values from a list of dicts

I think as simple as below would give you what you are looking for.

In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']

You can do this with a combination of map and lambda as well but list comprehension looks more elegant and pythonic.

For a smaller input list comprehension is way to go but if the input is really big then i guess generators are the ideal way.

In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'

Here is a comparison of all possible solutions for bigger input

 In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
  ...:     for i in l:
  ...:         yield i.get('value', None)
  ...: 
In[4]: def list_comp_verison():
  ...:     return [i.get('value', None) for i in l]
  ...: 
In[5]: def list_verison():
  ...:     ll = []
  ...:     for i in l:
  ...:         ll.append(i.get('value', None))
  ...:     return ll
In[10]: def map_lambda_version():
   ...:      m = map(lambda i:i.get('value', None), l)
   ...:      return m
   ...: 
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As you can see, generators are a better solution in comparison to the others, map is also slower compared to generator for reason I will leave up to OP to figure out.

Using Thymeleaf when the value is null

I use

<div th:text ="${variable != null} ? (${variable != ''} ? ${variable} : 'empty string message') : 'null message' "></div>

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

echo key and value of an array without and with loop

You can try following code:

foreach ($arry as $key => $value) 
{
      echo $key;
      foreach ($value as  $val) 
      {
         echo $val; 
      }
}

Link to "pin it" on pinterest without generating a button

So you want the code to the pin it button without installing the button? If so just paste this code in the place of the url of the page you're pinning from. It should function as a pin it button without the button.

javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)})());

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

How to fetch all Git branches

You can fetch all branches from all remotes like this:

git fetch --all

It's basically a power move.

fetch updates local copies of remote branches so this is always safe for your local branches BUT:

  1. fetch will not update local branches (which track remote branches); if you want to update your local branches you still need to pull every branch.

  2. fetch will not create local branches (which track remote branches), you have to do this manually. If you want to list all remote branches: git branch -a

To update local branches which track remote branches:

git pull --all

However, this can be still insufficient. It will work only for your local branches which track remote branches. To track all remote branches execute this oneliner BEFORE git pull --all:

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done

TL;DR version

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

(It seems that pull fetches all branches from all remotes, but I always fetch first just to be sure.)

Run the first command only if there are remote branches on the server that aren't tracked by your local branches.

P.S. AFAIK git fetch --all and git remote update are equivalent.



Kamil Szot's comment, which folks have found useful.

I had to use:

for remote in `git branch -r`; do git branch --track ${remote#origin/} $remote; done

because your code created local branches named origin/branchname and I was getting "refname 'origin/branchname' is ambiguous whenever I referred to it.

Is there any way to configure multiple registries in a single npmrc file

I use Strongloop's cli tools for that; see https://strongloop.com/strongblog/switch-between-configure-public-and-private-npm-registry/ for more information

Switching between repositories is as easy as : slc registry use <name>

How to dump a dict to a json file?

Combine the answer of @mgilson and @gnibbler, I found what I need was this:


d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
j = json.dumps(d, indent=4)
f = open('sample.json', 'w')
print >> f, j
f.close()

It this way, I got a pretty-print json file. The tricks print >> f, j is found from here: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/