Programs & Examples On #Comparison

Questions about data comparison and efficient ways to accomplish it. Please avoid using this tag for generic (meta) comparison of two issues or concepts.

Differences in string compare methods in C#

with .Equals, you also gain the StringComparison options. very handy for ignoring case and other things.

btw, this will evaluate to false

string a = "myString";
string b = "myString";

return a==b

Since == compares the values of a and b (which are pointers) this will only evaluate to true if the pointers point to the same object in memory. .Equals dereferences the pointers and compares the values stored at the pointers. a.Equals(b) would be true here.

and if you change b to:

b = "MYSTRING";

then a.Equals(b) is false, but

a.Equals(b, StringComparison.OrdinalIgnoreCase) 

would be true

a.CompareTo(b) calls the string's CompareTo function which compares the values at the pointers and returns <0 if the value stored at a is less than the value stored at b, returns 0 if a.Equals(b) is true, and >0 otherwise. However, this is case sensitive, I think there are possibly options for CompareTo to ignore case and such, but don't have time to look now. As others have already stated, this would be done for sorting. Comparing for equality in this manner would result in unecessary overhead.

I'm sure I'm leaving stuff out, but I think this should be enough info to start experimenting if you need more details.

Java Embedded Databases Comparison

I am a big fan of DB4O for both .Net and Java.

Performance has become much better since the early releases. The licensing model isnt too bad, either. I particularly like the options available for querying your objects. Query by example is very powerful and easy to get used to.

Comparing two .jar files

If you select two files in IntellijIdea and press Ctrl + Dthen it will show you the diff. I use Ultimate and don't know if it will work with Community edition.

How to compare two floating point numbers in Bash?

beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES

I solved such problem with such shell/awk function:

# get version of GNU tool
toolversion() {
    local prog="$1" operator="$2" value="$3" version

    version=$($prog --version | awk '{print $NF; exit}')

    awk -vv1="$version" -vv2="$value" 'BEGIN {
        split(v1, a, /\./); split(v2, b, /\./);
        if (a[1] == b[1]) {
            exit (a[2] '$operator' b[2]) ? 0 : 1
        }
        else {
            exit (a[1] '$operator' b[1]) ? 0 : 1
        }
    }'
}

if toolversion grep '>=' 2.6; then
   # do something awesome
fi

extract the date part from DateTime in C#

When comparing only the date of the datatimes, use the Date property. So this should work fine for you

datetime1.Date == datetime2.Date

Compare two List<T> objects for equality, ignoring order

As written, this question is ambigous. The statement:

... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.

does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.

If you want to ensure to collections have exactly the same set of members regardless of order, you can use:

// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();

If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:

// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();

Using the set operations (Intersect, Union, Except) is more efficient than using methods like Contains. In my opinion, it also better expresses the expectations of your query.

EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:

var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };

// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any(); 

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

Comparing date part only without comparing time in JavaScript

After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:

I have used something like this:

var currentDate= new Date().setHours(0,0,0,0);

var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);

In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

The == operator tests value equivalence. The is operator tests object identity, and Python tests whether the two are really the same object (i.e., live at the same address in memory).

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True

In this example, Python only created one string object, and both a and b refers to it. The reason is that Python internally caches and reuses some strings as an optimization. There really is just a string 'banana' in memory, shared by a and b. To trigger the normal behavior, you need to use longer strings:

>>> a = 'a longer banana'
>>> b = 'a longer banana'
>>> a == b, a is b
(True, False)

When you create two lists, you get two objects:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical.

If a refers to an object and you assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

How to compare times in Python?

Inspired by Roger Pate:

import datetime
def todayAt (hr, min=0, sec=0, micros=0):
   now = datetime.datetime.now()
   return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)    

# Usage demo1:
print todayAt (17), todayAt (17, 15)

# Usage demo2:    
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
   print "Too Early"

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

Compare two files in Visual Studio

In Visual Studio the Diff can be called using Command Window and then Tools.DiffFiles command

  1. Open Command Window by hotkeys Ctrl + W, A or by menu View -> Other Windows -> Command Window
  2. Enter command Tools.DiffFiles "FirstFile.cs" "SecondFile.cs"

How do you compare two version Strings in Java?

For someone who is going to show Force Update Alert based on version number I have a following Idea. This may be used when comparing the versions between Android Current App version and firebase remote config version. This is not exactly the answer for the question asked but this will help someone definitely.

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
  static String firebaseVersion = "2.1.3"; // or 2.1
  static String appVersion = "2.1.4";
  static List<String> firebaseVersionArray;
  static List<String> appVersionArray;
  static boolean isNeedToShowAlert = false;
  public static void main (String[]args)
  {
    System.out.println ("Hello World");
    firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split ("\\.")));
    appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split ("\\.")));
    if(appVersionArray.size() < firebaseVersionArray.size()) {
        appVersionArray.add("0");
    }
    if(firebaseVersionArray.size() < appVersionArray.size()) {
        firebaseVersionArray.add("0");
    }
    isNeedToShowAlert = needToShowAlert(); //Returns false
    System.out.println (isNeedToShowAlert);

  }
  static boolean needToShowAlert() {
      boolean result = false;
      for(int i = 0 ; i < appVersionArray.size() ; i++) {
          if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {
              continue;
          } else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){
             result = false;
             break;
          } else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {
             result = true;
             break;  
          }
      }
      return result;
  }
}

You can run this code by copy pasting in https://www.onlinegdb.com/online_java_compiler

How is __eq__ handled in Python and in what order?

When Python2.x sees a == b, it tries the following.

  • If type(b) is a new-style class, and type(b) is a subclass of type(a), and type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If type(a) has overridden __eq__ (that is, type(a).__eq__ isn't object.__eq__), then the result is a.__eq__(b).
  • If type(b) has overridden __eq__, then the result is b.__eq__(a).
  • If none of the above are the case, Python repeats the process looking for __cmp__. If it exists, the objects are equal iff it returns zero.
  • As a final fallback, Python calls object.__eq__(a, b), which is True iff a and b are the same object.

If any of the special methods return NotImplemented, Python acts as though the method didn't exist.

Note that last step carefully: if neither a nor b overloads ==, then a == b is the same as a is b.


From https://eev.ee/blog/2012/03/24/python-faq-equality/

How does tuple comparison work in Python?

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

See Common Sequence Operations:

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

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

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

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

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

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

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

How to test multiple variables against a value?

Your problem is more easily addressed with a dictionary structure like:

x = 0
y = 1
z = 3
d = {0: 'c', 1:'d', 2:'e', 3:'f'}
mylist = [d[k] for k in [x, y, z]]

Comparing chars in Java

If you know all your 21 characters in advance you can write them all as one String and then check it like this:

char wanted = 'x';
String candidates = "abcdefghij...";
boolean hit = candidates.indexOf(wanted) >= 0;

I think this is the shortest way.

Difference between | and || or & and && for comparison

The instance in which you're using a single character (i.e. | or &) is a bitwise comparison of the results. As long as your language evaluates these expressions to a binary value they should return the same results. As a best practice, however, you should use the logical operator as that's what you mean (I think).

Java Compare Two Lists

public static boolean compareList(List ls1, List ls2){
    return ls1.containsAll(ls2) && ls1.size() == ls2.size() ? true :false;
     }

public static void main(String[] args) {

    ArrayList<String> one = new ArrayList<String>();
    one.add("one");
    one.add("two");
    one.add("six");

    ArrayList<String> two = new ArrayList<String>();
    two.add("one");
    two.add("six");
    two.add("two");

    System.out.println("Output1 :: " + compareList(one, two));

    two.add("ten");

    System.out.println("Output2 :: " + compareList(one, two));
  }

In Bash, how can I check if a string begins with some value?

While I find most answers here quite correct, many of them contain unnecessary Bashisms. POSIX parameter expansion gives you all you need:

[ "${host#user}" != "${host}" ]

and

[ "${host#node}" != "${host}" ]

${var#expr} strips the smallest prefix matching expr from ${var} and returns that. Hence if ${host} does not start with user (node), ${host#user} (${host#node}) is the same as ${host}.

expr allows fnmatch() wildcards, thus ${host#node??} and friends also work.

How do I make my string comparison case insensitive?

In the default Java API you have:

String.CASE_INSENSITIVE_ORDER

So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.

String s = "some text here";
s.equalsIgnoreCase("Some text here");

Is what you want for pure equality checks in your own code.

Just to further informations about anything pertaining to equality of Strings in Java. The hashCode() function of the java.lang.String class "is case sensitive":

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

So if you want to use an Hashtable/HashMap with Strings as keys, and have keys like "SomeKey", "SOMEKEY" and "somekey" be seen as equal, then you will have to wrap your string in another class (you cannot extend String since it is a final class). For example :

private static class HashWrap {
    private final String value;
    private final int hash;

    public String get() {
        return value;
    }

    private HashWrap(String value) {
        this.value = value;
        String lc = value.toLowerCase();
        this.hash = lc.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o instanceof HashWrap) {
            HashWrap that = (HashWrap) o;
            return value.equalsIgnoreCase(that.value);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.hash;
    }
}

and then use it as such:

HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();

How do I do a case-insensitive string comparison?

I saw this solution here using regex.

import re
if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
# is True

It works well with accents

In [42]: if re.search("ê","ê", re.IGNORECASE):
....:        print(1)
....:
1

However, it doesn't work with unicode characters case-insensitive. Thank you @Rhymoid for pointing out that as my understanding was that it needs the exact symbol, for the case to be true. The output is as follows:

In [36]: "ß".lower()
Out[36]: 'ß'
In [37]: "ß".upper()
Out[37]: 'SS'
In [38]: "ß".upper().lower()
Out[38]: 'ss'
In [39]: if re.search("ß","ßß", re.IGNORECASE):
....:        print(1)
....:
1
In [40]: if re.search("SS","ßß", re.IGNORECASE):
....:        print(1)
....:
In [41]: if re.search("ß","SS", re.IGNORECASE):
....:        print(1)
....:

Object comparison in JavaScript

Certainly not the only way - you could prototype a method (against Object here but I certainly wouldn't suggest using Object for live code) to replicate C#/Java style comparison methods.

Edit, since a general example seems to be expected:

Object.prototype.equals = function(x)
{
    for(p in this)
    {
        switch(typeof(this[p]))
        {
            case 'object':
                if (!this[p].equals(x[p])) { return false }; break;
            case 'function':
                if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
            default:
                if (this[p] != x[p]) { return false; }
        }
    }

    for(p in x)
    {
        if(typeof(this[p])=='undefined') {return false;}
    }

    return true;
}

Note that testing methods with toString() is absolutely not good enough but a method which would be acceptable is very hard because of the problem of whitespace having meaning or not, never mind synonym methods and methods producing the same result with different implementations. And the problems of prototyping against Object in general.

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

Subtracting the Minimum of the ends of the ranges from the Maximum of the beginning seems to do the trick. If the result is less than or equal to zero, we have an overlap. This visualizes it well:

enter image description here

Comparing two collections for equality irrespective of the order of items in them

If comparing for the purpose of Unit Testing Assertions, it may make sense to throw some efficiency out the window and simply convert each list to a string representation (csv) before doing the comparison. That way, the default test Assertion message will display the differences within the error message.

Usage:

using Microsoft.VisualStudio.TestTools.UnitTesting;

// define collection1, collection2, ...

Assert.Equal(collection1.OrderBy(c=>c).ToCsv(), collection2.OrderBy(c=>c).ToCsv());

Helper Extension Method:

public static string ToCsv<T>(
    this IEnumerable<T> values,
    Func<T, string> selector,
    string joinSeparator = ",")
{
    if (selector == null)
    {
        if (typeof(T) == typeof(Int16) ||
            typeof(T) == typeof(Int32) ||
            typeof(T) == typeof(Int64))
        {
            selector = (v) => Convert.ToInt64(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(decimal))
        {
            selector = (v) => Convert.ToDecimal(v).ToStringInvariant();
        }
        else if (typeof(T) == typeof(float) ||
                typeof(T) == typeof(double))
        {
            selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);
        }
        else
        {
            selector = (v) => v.ToString();
        }
    }

    return String.Join(joinSeparator, values.Select(v => selector(v)));
}

Time comparison

package javaapplication4;

import java.text.*;
import java.util.*;

/**
 *
 * @author Stefan Wendelmann
 */
public class JavaApplication4
{
    private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) throws ParseException
  {
    SimpleDateFormat parser = new SimpleDateFormat("dd.MM.YYYY HH:mm:ss.SSS");
    Date before = parser.parse("01.10.1990 07:00:00.000");
    Date base = parser.parse("01.10.1990 08:00:00.000");
    Date after = parser.parse("01.10.1990 09:00:00.000");

    printCompare(base, base, "==");
    printCompare(base, before, "==");
    printCompare(base, before, "<");
    printCompare(base, after, "<");
    printCompare(base, after, ">");
    printCompare(base, before, ">");
    printCompare(base, before, "<=");
    printCompare(base, base, "<=");
    printCompare(base, after, "<=");
    printCompare(base, after, ">=");
    printCompare(base, base, ">=");
    printCompare(base, before, ">=");

  }

  private static void printCompare (Date a, Date b, String operator){
    System.out.println(sdf.format(b)+"\t"+operator+"\t"+sdf.format(a)+"\t"+compareTime(a, b, operator));
  }

  protected static boolean compareTime(Date a, Date b, String operator)
  {
    if (a == null)
    {
      return false;
    }
    try
    {
      //Zeit aus Datum holen
// The Magic happens here i only get the Time out of the Date Object
      SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss.SSS");
      a = parser.parse(parser.format(a));
      b = parser.parse(parser.format(b));
    }
    catch (ParseException ex)
    {
      System.err.println(ex);
    }
    switch (operator)
    {
      case "==":
        return b.compareTo(a) == 0;
      case "<":
        return b.compareTo(a) < 0;
      case ">":
        return b.compareTo(a) > 0;
      case "<=":
        return b.compareTo(a) <= 0;
      case ">=":
        return b.compareTo(a) >= 0;
      default:
        throw new IllegalArgumentException("Operator " + operator + " wird für Feldart Time nicht unterstützt!");

    }
  }

}



run:
08:00:00.000    ==  08:00:00.000    true
07:00:00.000    ==  08:00:00.000    false
07:00:00.000    <   08:00:00.000    true
09:00:00.000    <   08:00:00.000    false
09:00:00.000    >   08:00:00.000    true
07:00:00.000    >   08:00:00.000    false
07:00:00.000    <=  08:00:00.000    true
08:00:00.000    <=  08:00:00.000    true
09:00:00.000    <=  08:00:00.000    false
09:00:00.000    >=  08:00:00.000    true
08:00:00.000    >=  08:00:00.000    true
07:00:00.000    >=  08:00:00.000    false
BUILD SUCCESSFUL (total time: 0 seconds)

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

Comparing boxed Long values 127 and 128

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127, whichever is bigger.(We can set top level value upto which Integer values should get cached by using java.lang.Integer.IntegerCache.high).

 For example:
    If we set java.lang.Integer.IntegerCache.high=500;
    then values from -128 to 500 will get cached and 

    Integer a=498;
    Integer b=499;
    System.out.println(a==b)

    Output will be "true".

Float and Double objects never gets cached.

Character will get cache from 0 to 127

You are comparing two objects. so == operator will check equality of object references. There are following ways to do it.

1) type cast both objects into primitive values and compare

    (long)val3 == (long)val4

2) read value of object and compare

    val3.longValue() == val4.longValue()

3) Use equals() method on object comparison.

    val3.equals(val4);  

Comparing object properties in c#

I would add the following line to the PublicInstancePropertiesEqual method to avoid copy & paste errors:

Assert.AreNotSame(self, to);

How can I check if a Perl array contains a particular value?

This blog post discusses the best answers to this question.

As a short summary, if you can install CPAN modules then the most readable solutions are:

any(@ingredients) eq 'flour';

or

@ingredients->contains('flour');

However, a more common idiom is:

any { $_ eq 'flour' } @ingredients

But please don't use the first() function! It doesn't express the intent of your code at all. Don't use the ~~ "Smart match" operator: it is broken. And don't use grep() nor the solution with a hash: they iterate through the whole list.

any() will stop as soon as it finds your value.

Check out the blog post for more details.

Switch statement for greater-than/less-than

switch (Math.floor(scrollLeft/1000)) {
  case 0: // (<1000)
   //do stuff
   break;
  case 1: // (>=1000 && <2000)
   //do stuff;
   break;
}

Only works if you have regular steps...

EDIT: since this solution keeps getting upvotes, I must advice that mofolo's solution is a way better

String comparison technique used by Python

A pure Python equivalent for string comparisons would be:

def less(string1, string2):
    # Compare character by character
    for idx in range(min(len(string1), len(string2))):
        # Get the "value" of the character
        ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
        # If the "value" is identical check the next characters
        if ordinal1 == ordinal2:
            continue
        # It's not equal so we're finished at this index and can evaluate which is smaller.
        else:
            return ordinal1 < ordinal2
    # We're out of characters and all were equal, so the result depends on the length
    # of the strings.
    return len(string1) < len(string2)

This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for < comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.

A more general variant would be:

from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))

Comparing two strings, ignoring case in C#

I'd venture that the safest is to use String.Equals to mitigate against the possibility that val is null.

How do I fix this "TypeError: 'str' object is not callable" error?

this part :

"Your new price is: $"(float(price)

asks python to call this string:

"Your new price is: $"

just like you would a function: function( some_args) which will ALWAYS trigger the error:

TypeError: 'str' object is not callable

Javascript: The prettiest way to compare one value against multiple values

What i use to do, is put those multiple values in an array like

var options = [foo, bar];

and then, use indexOf()

if(options.indexOf(foobar) > -1){
   //do something
}

for prettiness:

if([foo, bar].indexOf(foobar) +1){
   //you can't get any more pretty than this :)
}

and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

What is the Difference Between Mercurial and Git?

If you are a Windows developer looking for basic disconnected revision control, go with Hg. I found Git to be incomprehensible while Hg was simple and well integrated with the Windows shell. I downloaded Hg and followed this tutorial (hginit.com) - ten minutes later I had a local repo and was back to work on my project.

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

How to check if an integer is in a given range?

Google's Java Library Guava also implements Range:

import com.google.common.collect.Range;

Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false

Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true

Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true

Image comparison - fast algorithm

If you have a large number of images, look into a Bloom filter, which uses multiple hashes for a probablistic but efficient result. If the number of images is not huge, then a cryptographic hash like md5 should be sufficient.

Compare two files report difference in python

hosts0 = open("C:path\\a.txt","r")
hosts1 = open("C:path\\b.txt","r")

lines1 = hosts0.readlines()

for i,lines2 in enumerate(hosts1):
    if lines2 != lines1[i]:
        print "line ", i, " in hosts1 is different \n"
        print lines2
    else:
        print "same"

The above code is working for me. Can you please indicate what error you are facing?

How to compare dates in Java?

You can use Date.getTime() which:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This means you can compare them just like numbers:

if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
    /*
     * date is between date1 and date2 (both inclusive)
     */
}

/*
 * when date1 = 2015-01-01 and date2 = 2015-01-10 then
 * returns true for:
 * 2015-01-01
 * 2015-01-01 00:00:01
 * 2015-01-02
 * 2015-01-10
 * returns false for:
 * 2014-12-31 23:59:59
 * 2015-01-10 00:00:01
 * 
 * if one or both dates are exclusive then change <= to <
 */

How to compare two JSON objects with the same elements in a different order equal?

For the following two dicts 'dictWithListsInValue' and 'reorderedDictWithReorderedListsInValue' which are simply reordered versions of each other

dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(sorted(a.items()) == sorted(b.items()))  # gives false

gave me wrong result i.e. false .

So I created my own cutstom ObjectComparator like this:

def my_list_cmp(list1, list2):
    if (list1.__len__() != list2.__len__()):
        return False

    for l in list1:
        found = False
        for m in list2:
            res = my_obj_cmp(l, m)
            if (res):
                found = True
                break

        if (not found):
            return False

    return True


def my_obj_cmp(obj1, obj2):
    if isinstance(obj1, list):
        if (not isinstance(obj2, list)):
            return False
        return my_list_cmp(obj1, obj2)
    elif (isinstance(obj1, dict)):
        if (not isinstance(obj2, dict)):
            return False
        exp = set(obj2.keys()) == set(obj1.keys())
        if (not exp):
            # print(obj1.keys(), obj2.keys())
            return False
        for k in obj1.keys():
            val1 = obj1.get(k)
            val2 = obj2.get(k)
            if isinstance(val1, list):
                if (not my_list_cmp(val1, val2)):
                    return False
            elif isinstance(val1, dict):
                if (not my_obj_cmp(val1, val2)):
                    return False
            else:
                if val2 != val1:
                    return False
    else:
        return obj1 == obj2

    return True


dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(my_obj_cmp(a, b))  # gives true

which gave me the correct expected output!

Logic is pretty simple:

If the objects are of type 'list' then compare each item of the first list with the items of the second list until found , and if the item is not found after going through the second list , then 'found' would be = false. 'found' value is returned

Else if the objects to be compared are of type 'dict' then compare the values present for all the respective keys in both the objects. (Recursive comparison is performed)

Else simply call obj1 == obj2 . It by default works fine for the object of strings and numbers and for those eq() is defined appropriately .

(Note that the algorithm can further be improved by removing the items found in object2, so that the next item of object1 would not compare itself with the items already found in the object2)

How to check if a variable is not null?

if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

never use number type like id as

      if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

   if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                
                                                                            } else {

                                                                            }
                                                                            

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

       if (string_type_variable) { }

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Wildcard string comparison in Javascript

I used the answer by @Spenhouet and added more "replacements"-possibilities than "*". For example "?". Just add your needs to the dict in replaceHelper.

/**
 * @param {string} str
 * @param {string} rule
 * checks match a string to a rule
 * Rule allows * as zero to unlimited numbers and ? as zero to one character
 * @returns {boolean}
 */
function matchRule(str, rule) {
  const escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  return new RegExp("^" + replaceHelper(rule, {"*": "\\d*", "?": ".?"}, escapeRegex) + "$").test(str);
}

function replaceHelper(input, replace_dict, last_map) {
  if (Object.keys(replace_dict).length === 0) {
    return last_map(input);
  }
  const split_by = Object.keys(replace_dict)[0];
  const replace_with = replace_dict[split_by];
  delete replace_dict[split_by];
  return input.split(split_by).map((next_input) => replaceHelper(next_input, replace_dict, last_map)).join(replace_with);
}

what is the difference between json and xml

The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.

A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.

To illustrate the point, let me borrow Guffa's example:

{   "persons": [
  {
    "name": "Ford Prefect",
    "gender": "male"
 },
 {
   "name": "Arthur Dent",
   "gender": "male"
  },
  {
    "name": "Tricia McMillan",
    "gender": "female"
  }   ] }

The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.

A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:

<xjson>   
  <object>
    <name>persons</name>
    <value>
      <array>
         <object>
            <value>Ford Prefect</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Arthur Dent</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Tricia McMillan</value>
            <gender>female</gender>
         </object>
      </array>
    </value>   
  </object> 
 </xjson>

Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.

So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.

But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.

If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.

It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.

It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.

Sort array of objects by string property value

Using Ramda,

npm install ramda

import R from 'ramda'
var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];
var ascendingSortedObjs = R.sortBy(R.prop('last_nom'), objs)
var descendingSortedObjs = R.reverse(ascendingSortedObjs)

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

Can't compare naive and aware datetime.now() <= challenge.datetime_end

It is working form me. Here I am geeting the table created datetime and adding 10 minutes on the datetime. later depending on the current time, Expiry Operations are done.

from datetime import datetime, time, timedelta
import pytz

Added 10 minutes on database datetime

table_datetime = '2019-06-13 07:49:02.832969' (example)

# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)

table_expire_datetime = table_datetime + timedelta(minutes=10 )

# Current datetime
current_datetime = datetime.now()


# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)


if expired_on < checked_on:
    print("Time Crossed)
else:
    print("Time not crossed ")

It worked for me.

JQuery string contains check

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

it will return the position of the match, or -1 if it isn't found.

Char Comparison in C

I believe you are trying to compare two strings representing values, the function you are looking for is:

int atoi(const char *nptr);

or

long int strtol(const char *nptr, char **endptr, int base);

these functions will allow you to convert a string to an int/long int:

int val = strtol("555", NULL, 10);

and compare it to another value.

int main (int argc, char *argv[])
{
    long int val = 0;
    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s number\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    val = strtol(argv[1], NULL, 10);
    printf("%d is %s than 555\n", val, val > 555 ? "bigger" : "smaller");

    return 0;
}

Check if two unordered lists are equal

Python has a built-in datatype for an unordered collection of (hashable) things, called a set. If you convert both lists to sets, the comparison will be unordered.

set(x) == set(y)

Documentation on set


EDIT: @mdwhatcott points out that you want to check for duplicates. set ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter:

>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>> 
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>> 

What are the differences between C, C# and C++ in terms of real-world applications?

C - an older programming language that is described as Hands-on. As the programmer you must tell the program to do everything. Also this language will let you do almost anything. It does not support object orriented code. Thus no classes.

C++ - an extention language per se of C. In C code ++ means increment 1. Thus C++ is better than C. It allows for highly controlled object orriented code. Once again a very hands on language that goes into MUCH detail.

C# - Full object orriented code resembling the style of C/C++ code. This is really closer to JAVA. C# is the latest version of the C style languages and is very good for developing web applications.

When to use CouchDB over MongoDB and vice versa

Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.

The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false} just does not work.

The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.

I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.

BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.

Comparing two hashmaps for equal values and same key sets?

Make an equals check on the keySet() of both HashMaps.

NOTE:

If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

Check if all elements in a list are identical

A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list)

x.count(x[0]) == len(x)

some simple benchmarks:

>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*5000', number=10000)
1.4383411407470703
>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*4999+[2]', number=10000)
1.4765670299530029
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*5000', number=10000)
0.26274609565734863
>>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*4999+[2]', number=10000)
0.25654196739196777

bash string compare to multiple correct values

If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi

Have a nice day

Best way to compare 2 XML documents in Java

skaffman seems to be giving a good answer.

another way is probably to format the XML using a commmand line utility like xmlstarlet(http://xmlstar.sourceforge.net/) and then format both the strings and then use any diff utility(library) to diff the resulting output files. I don't know if this is a good solution when issues are with namespaces.

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

How do I compare two Integers?

I would go with x.equals(y) because that's consistent way to check equality for all classes.

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

Comparing arrays for equality in C++

You are comparing the addresses instead of the values.

String comparison in Python: is vs. ==

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

Use '=' or LIKE to compare strings in SQL?

To see the performance difference, try this:

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name

SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name

Comparing strings with '=' is much faster.

Comparing two strings in C?

For comparing 2 strings, either use the built in function strcmp() using header file string.h

if(strcmp(a,b)==0)
    printf("Entered strings are equal");
else
    printf("Entered strings are not equal");

OR you can write your own function like this:

int string_compare(char str1[], char str2[])
{
    int ctr=0;

    while(str1[ctr]==str2[ctr])
    {
        if(str1[ctr]=='\0'||str2[ctr]=='\0')
            break;
        ctr++;
    }
    if(str1[ctr]=='\0' && str2[ctr]=='\0')
        return 0;
    else
        return -1;
}

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE startTime like '2010-04-29%'

You can also use comparison operators on MySQL dates if you want to find something after or before. This is because they are written in such a way (largest value to smallest with leading zeros) that a simple string sort will sort them correctly.

How do I check for null values in JavaScript?

Checking error conditions:

// Typical API response data
let data = {
  status: true,
  user: [],
  total: 0,
  activity: {sports: 1}
}

// A flag that checks whether all conditions were met or not
var passed = true;

// Boolean check
if (data['status'] === undefined || data['status'] == false){
  console.log("Undefined / no `status` data");
  passed = false;
}

// Array/dict check
if (data['user'] === undefined || !data['user'].length){
  console.log("Undefined / no `user` data");
  passed = false;
}

// Checking a key in a dictionary
if (data['activity'] === undefined || data['activity']['time'] === undefined){
   console.log("Undefined / no `time` data");
   passed = false;
}

// Other values check
if (data['total'] === undefined || !data['total']){
  console.log("Undefined / no `total` data");
  passed = false;
}

// Passed all tests?
if (passed){
  console.log("Passed all tests");
}

Checking images for similarity with OpenCV

A little bit off topic but useful is the pythonic numpy approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):

A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by

import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))

After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:

1) If you compare similar pictures the sum will return 1:

In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0

2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):

In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822

Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.

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

As already mentioned by several people, eq is the right operator here.

If you use warnings; in your script, you'll get warnings about this (and many other useful things); I'd recommend use strict; as well.

Advantages of SQL Server 2008 over SQL Server 2005?

Be aware that a lot of the really killer features are only in Enterprise Edition. Data compression and backup compression are among two of my top favorites - they give you free performance improvements right off the bat. Data compression lessens the amount of I/O you have to do, so a lot of queries speed up 20-40%. CPU use goes up, but in today's multi-core environments, we often have more CPU power but not more IO. Anyway, those are only in Enterprise.

If you're only going to use Standard Edition, then most of the improvements require changes to your application code and T-SQL code, so it's not quite as easy of a sell.

What is the best way to compare 2 folder trees on windows?

Did you try: https://www.araxis.com/merge/index.en It allows to visualize changes and selectively merge specific differences in files and folders.

Comparing Arrays of Objects in JavaScript

There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions. Example:

const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];

const arraysCompare = (a1, a2) => {
  if (a1.length !== a2.length) return false;
  const objectIteration = (object) => {
    const result = [];
    const objectReduce = (obj) => {
      for (let i in obj) {
        if (typeof obj[i] !== 'object') {
          result.push(`${i}${obj[i]}`);
        } else {
          objectReduce(obj[i]);
        }
      }
    };
    objectReduce(object);
    return result;
  };
  const reduceArray1 = a1.map(item => {
    if (typeof item !== 'object') return item;
    return objectIteration(item).join('');
  });
  const reduceArray2 = a2.map(item => {
    if (typeof item !== 'object') return item;
    return objectIteration(item).join('');
  });
  const compare =  reduceArray1.map(item => reduceArray2.includes(item));
  return compare.reduce((acc, item) => acc + Number(item)) === a1.length;
};

console.log(arraysCompare(array1, array2));

How to simplify a null-safe compareTo() implementation?

Another Apache ObjectUtils example. Able to sort other types of objects.

@Override
public int compare(Object o1, Object o2) {
    String s1 = ObjectUtils.toString(o1);
    String s2 = ObjectUtils.toString(o2);
    return s1.toLowerCase().compareTo(s2.toLowerCase());
}

How do you auto format code in Visual Studio?

Even though the question is a bit old, someone might find it handy.

You can define new key bindings by going to Tools -> options -> Environment -> keyboard

enter image description here

jQuery check if it is clicked or not

    <script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
var val;
        $(document).ready(function () {
            $("#click").click(function () {
                val = 1;
                get();
                });
                });
          function get(){
            if (val == 1){
                alert(val);
                }

          }
</script>
    <table>
    <tr><td id='click'>ravi</td></tr>
    </table>

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

How do you pass a function as a parameter in C?

This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

typedef void (*functiontype)();

Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

void dosomething() { }

functiontype func = &dosomething;
func();

For a function that returns an int and takes a char you would do

typedef int (*functiontype2)(char);

and to use it

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

boost::function<int (char a)> functiontype2;

is so much nicer than the above.

How to list all databases in the mongo shell?

To list mongodb database on shell

 show databases     //Print a list of all available databases.
 show dbs   // Print a list of all databases on the server.

Few more basic commands

use <db>    // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections    //Print a list of all collections for current database.
show users  //Print a list of users for current database.
show roles  //Print a list of all roles, both user-defined and built-in, for the current database.

Access denied for user 'root'@'localhost' with PHPMyAdmin

Here are few steps that must be followed carefully

  1. First of all make sure that the WAMP server is running if it is not running, start the server.
  2. Enter the URL http://localhost/phpmyadmin/setup in address bar of your browser.
  3. Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1

  4. Return to your browser in phpmyadmin setup tab, and click New server.New server

  5. Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.

  6. Click save save

  7. Again click save in configuration file option.
  8. Now navigate to the config folder. Inside the folder there will be a file named config.inc.php. Copy the file and paste it out of the folder (if the file with same name is already there then override it) and finally delete the folder.
  9. Now you are done. Try to connect the mysql server again and this time you won’t get any error. --credits Bibek Subedi

Making Python loggers output all messages to stdout in addition to log file

Since no one has shared a neat two liner, I will share my own:

logging.basicConfig(filename='logs.log', level=logging.DEBUG, format="%(asctime)s:%(levelname)s: %(message)s")
logging.getLogger().addHandler(logging.StreamHandler())

How to use variables in a command in sed?

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Triggering change detection manually in Angular

I was able to update it with markForCheck()

Import ChangeDetectorRef

import { ChangeDetectorRef } from '@angular/core';

Inject and instantiate it

constructor(private ref: ChangeDetectorRef) { 
}

Finally mark change detection to take place

this.ref.markForCheck();

Here's an example where markForCheck() works and detectChanges() don't.

https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview

EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.

(Press STOP/RUN to run it again)

Get line number while using grep

In order to display the results with the line numbers, you might try this

grep -nr "word to search for" /path/to/file/file 

The result should be something like this:

linenumber: other data "word to search for" other data

How to generate the JPA entity Metamodel?

For eclipselink, only the following dependency is sufficient to generate metamodel. Nothing else is needed.

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>

Is Python strongly typed?

A Python variable stores an untyped reference to the target object that represent the value.

Any assignment operation means assigning the untyped reference to the assigned object -- i.e. the object is shared via the original and the new (counted) references.

The value type is bound to the target object, not to the reference value. The (strong) type checking is done when an operation with the value is performed (run time).

In other words, variables (technically) have no type -- it does not make sense to think in terms of a variable type if one wants to be exact. But references are automatically dereferenced and we actually think in terms of the type of the target object.

SSRS the definition of the report is invalid

I had simply changed the capitalization of ONE character in one of my report parameters and could no longer deploy. Changing the single character back to uppercase allowed me to redeploy. Remarkable.

Good Java graph algorithm library?

JGraph from http://mmengineer.blogspot.com/2009/10/java-graph-floyd-class.html

Provides a powerfull software to work with graphs (direct or undirect). Also generates Graphivz code, you can see graphics representations. You can put your own code algorithms into pakage, for example: backtracking code. The package provide some algorithms: Dijkstra, backtracking minimun path cost, ect..

Pycharm/Python OpenCV and CV2 install error

I had the same problem. Here are the steps for Windows 10 users.

Open CMD: win+r then type cmd. Now,

  1. Type pip install virtualenv
  2. Create a Virtual Environment, Type virtualenv testopencv
  3. Get Inside testopencv, Type cd testopencv
  4. Activate the Virtual Environment, Type .\Scripts\activate
  5. Now Install Opencv, Type pip install opencv-contrib-python --upgrade
  6. Let's test Opencv, Type Python then import cv2 hit enter then type print(cv2.__version__) to check if its installed

Now, open a new cmd, win + r then type cmd, repeat step 6. If it gives you an error.

Go inside the testopencv folder, inside lib. Copy everything, go to your python directory, inside lib folder paste it and skip that are already present.

Again open a new cmd, repeat Step 6.

Hope it helps.

How to convert from Hex to ASCII in JavaScript?

For completeness sake the reverse function:

function a2hex(str) {
  var arr = [];
  for (var i = 0, l = str.length; i < l; i ++) {
    var hex = Number(str.charCodeAt(i)).toString(16);
    arr.push(hex);
  }
  return arr.join('');
}
a2hex('2460'); //returns 32343630

Ignore outliers in ggplot2 boxplot

I had the same problem and precomputed the values for Q1, Q2, median, ymin, ymax using boxplot.stats:

# Load package and generate data
library(ggplot2)
data <- rnorm(100)

# Compute boxplot statistics
stats <- boxplot.stats(data)$stats
df <- data.frame(x="label1", ymin=stats[1], lower=stats[2], middle=stats[3], 
                 upper=stats[4], ymax=stats[5])

# Create plot
p <- ggplot(df, aes(x=x, lower=lower, upper=upper, middle=middle, ymin=ymin, 
                    ymax=ymax)) + 
    geom_boxplot(stat="identity")
p

The result is a boxplot without outliers. enter image description here

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

How to pass value from <option><select> to form action

Like @Shoaib answered, you dont need any jQuery or Javascript. You can to this simply with pure html!

<form method="POST" action="index.php?action=contact_agent">
  <select name="agent_id" required>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <input type="submit" value="Submit">
</form>
  1. Remove &agent_id= from form action since you don't need it there.
  2. Add name="agent_id" to the select
  3. Optionally add word required do indicate that this selection is required.

Since you are using PHP, then by posting the form to index.php you can catch agent_id with $_POST

/** Since you reference action on `form action` then value of $_GET['action'] will be contact_agent */
$action = $_GET['action'];

/** Value of $_POST['agent_id'] will be selected option value */
$agent_id = $_POST['agent_id']; 

As conclusion for such a simple task you should not use any javascript or jQuery. To @FelipeAlvarez that answers your comment

Unsupported major.minor version 52.0 when rendering in Android Studio

Im my case I had to change the dependencies of the build.gradle file to:

dependencies { 
    classpath 'com.android.tools.build:gradle:2.1.0'
}

(originally was 2.2.2) I guess this was generated by get several people working in the same project with different versions of gradle. So check your gradle version and edit this file properly.

Good vibes!

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

For people still getting the issue.

I face same problem and seems some .jar file missing.

so try tar -xf apache-jmeter-5.2.1.tgz in the console rather than just right click unzip. And also, try binary package if source package still has an issue. this solve my issue (I am using ubuntu)

Basic Ajax send/receive with node.js

RESTful API (Route):

rtr.route('/testing')
.get((req, res)=>{
    res.render('test')
})
.post((req, res, next)=>{
       res.render('test')
})

AJAX Code:

$(function(){
$('#anyid').on('click', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'GET',
        contentType: 'application/json',
        success: function(res){
            console.log('GET Request')
        }
    })
})

$('#anyid').on('submit', function(e){
    e.preventDefault()
    $.ajax({
        url: '/testing',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            info: "put data here to pass in JSON format."
        }),
        success: function(res){
            console.log('POST Request')
        }
    })
})
})

CSS: fixed to bottom and centered

revised code by Daniel Kanis:

just change the following lines in CSS

.problem {text-align:center}
.enclose {position:fixed;bottom:0px;width:100%;}

and in html:

<p class="enclose problem">
Your footer text here.
</p>

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

I have had the same issue that I solved this way:

Instead of adding the meta to the current page header that caused the same error as you had:

Page.Header.Controls.Add(meta);

I used this instead:

 Master.FindControl("YourHeadContentPlaceHolder").Controls.Add(meta);

and it works like a charm.

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

Public class is inaccessible due to its protection level

You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Setting java locale settings

For tools like jarsigner which is implemented in Java.

JAVA_TOOL_OPTIONS=-Duser.language=en jarsigner

How do I set the driver's python version in spark?

Setting PYSPARK_PYTHON=python3 and PYSPARK_DRIVER_PYTHON=python3 both to python3 works for me. I did this using export in my .bashrc. In the end, these are the variables I create:

export SPARK_HOME="$HOME/Downloads/spark-1.4.0-bin-hadoop2.4"
export IPYTHON=1
export PYSPARK_PYTHON=/usr/bin/python3
export PYSPARK_DRIVER_PYTHON=ipython3
export PYSPARK_DRIVER_PYTHON_OPTS="notebook"

I also followed this tutorial to make it work from within Ipython3 notebook: http://ramhiser.com/2015/02/01/configuring-ipython-notebook-support-for-pyspark/

What is the OR operator in an IF statement

The conditional or operator is ||:

if (expr1 || expr2) {do stuff}

if (title == "User greeting" || title == "User name") {do stuff}

The conditional (the OR) and it's parts are boolean expressions.

MSDN lists the C# operators in precedence order here http://msdn.microsoft.com/en-us/library/6a71f45d.aspx . And the MSDN page for boolean expressions is http://msdn.microsoft.com/en-us/library/dya2szfk.aspx .

If you are just starting to learn programming, you should read up on Conditional Statements from an introductory text or tutorial. This one seems to cover most of the basics: http://www.functionx.com/csharp/Lesson10.htm .

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

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

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

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

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

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

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

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

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

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

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

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

How to store UTC/GMT time in DB:

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

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

How to make a simple rounded button in Storyboard?

Try this!!

 override func viewDidLoad() {
   super.viewDidLoad()

   var button = UIButton.buttonWithType(.Custom) as UIButton
   button.frame = CGRectMake(160, 100, 200,40)

   button.layer.cornerRadius =5.0
   button.layer.borderColor = UIColor.redColor().CGColor
   button.layer.borderWidth = 2.0

   button.setImage(UIImage(named:"Placeholder.png"), forState: .Normal)
   button.addTarget(self, action: "OnClickroundButton", forControlEvents: .TouchUpInside)
   button.clipsToBounds = true

   view.addSubview(button)
}
    func OnClickroundButton() {
   NSLog(@"roundButton Method Called");
}

How to tell git to use the correct identity (name and email) for a given project?

If you don't use the --global parameter it will set the variables for the current project only.

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

Rewrite all requests to index.php with nginx

1 unless file exists will rewrite to index.php

Add the following to your location ~ \.php$

try_files = $uri @missing;

this will first try to serve the file and if it's not found it will move to the @missing part. so also add the following to your config (outside the location block), this will redirect to your index page

location @missing {
    rewrite ^ $scheme://$host/index.php permanent;
}

2 on the urls you never see the file extension (.php)

to remove the php extension read the following: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension/

and the example configuration from the link:

location / {
    set $page_to_view "/index.php";
    try_files $uri $uri/ @rewrites;
    root   /var/www/site;
    index  index.php index.html index.htm;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}

# rewrites
location @rewrites {
    if ($uri ~* ^/([a-z]+)$) {
        set $page_to_view "/$1.php";
        rewrite ^/([a-z]+)$ /$1.php last;
    }
}

What is <=> (the 'Spaceship' Operator) in PHP 7?

The <=> ("Spaceship") operator will offer combined comparison in that it will :

Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater

The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <, <=, ==, >= and >. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.

   //Comparing Integers

    echo 1 <=> 1; //output  0
    echo 3 <=> 4; //output -1
    echo 4 <=> 3; //output  1

    //String Comparison

    echo "x" <=> "x"; //output  0
    echo "x" <=> "y"; //output -1
    echo "y" <=> "x"; //output  1

Darkening an image with CSS (In any shape)

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

How would I find the second largest salary from the employee table?

select max(Emp_Sal) 
from Employee a
where 1 = ( select count(*) 
         from Employee b
         where b.Emp_Sal > a.Emp_Sal)

Yes running man.

Ways to eliminate switch in code

For C++

If you are referring to ie an AbstractFactory I think that a registerCreatorFunc(..) method usually is better than requiring to add a case for each and every "new" statement that is needed. Then letting all classes create and register a creatorFunction(..) which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.

findViewById in Fragment

Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.findViewById(R.id.yourId).setOnClickListener(this);

    // or
    getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}

Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method. It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.

Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully. i.e.

getView().findViewById("your view id");

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

IBOutlet and IBAction

IBAction and IBOutlets are used to hook up your interface made in Interface Builder with your controller. If you wouldn't use Interface Builder and build your interface completely in code, you could make a program without using them. But in reality most of us use Interface Builder, once you want to get some interactivity going in your interface, you will have to use IBActions and IBoutlets.

Formatting text in a TextBlock

This is my solution....

    <TextBlock TextWrapping="Wrap" Style="{DynamicResource InstructionStyle}"> 
        <Run Text="This wizard will take you through the purge process in the correct order." FontWeight="Bold"></Run>
        <LineBreak></LineBreak>
        <Run Text="To Begin, select" FontStyle="Italic"></Run>
        <Run x:Name="InstructionSection" Text="'REPLACED AT RUNTIME'" FontWeight="Bold"></Run>
        <Run Text="from the menu." FontStyle="Italic"></Run>
    </TextBlock>

I am learning... so if anyone has thaughts on the above solution please share! :)

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

You can create this extension outside class and replace width with whatever borderWidth you want.

Swift 4

extension UITextField
{
    func setBottomBorder(withColor color: UIColor)
    {
        self.borderStyle = UITextBorderStyle.none
        self.backgroundColor = UIColor.clear
        let width: CGFloat = 1.0

        let borderLine = UIView(frame: CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width))
        borderLine.backgroundColor = color
        self.addSubview(borderLine)
    }
}

Original

extension UITextField
{
    func setBottomBorder(borderColor: UIColor)
    {
        self.borderStyle = UITextBorderStyle.None
        self.backgroundColor = UIColor.clearColor()
        let width = 1.0

        let borderLine = UIView(frame: CGRectMake(0, self.frame.height - width, self.frame.width, width))
        borderLine.backgroundColor = borderColor
        self.addSubview(borderLine)
    }
}

and then add this to your viewDidLoad replacing yourTextField with your UITextField variable and with any color you want in the border

yourTextField.setBottomBorder(UIColor.blackColor())

This basically adds a view with that color at the bottom of the text field.

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

dmidecode -t 17 | grep  Size:

Adding all above values displayed after "Size: " will give exact total physical size of all RAM sticks in server.

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

What is the difference between g++ and gcc?

What is the difference between g++ and gcc?

gcc has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term "GNU C Compiler" is still used sometimes in the context of C programming.

The g++ is the C++ compiler for the GNU Compiler Collection. Like gnat is the Ada compiler for gcc. see Using the GNU Compiler Collection (GCC)

For example, the Ubuntu 16.04 and 18.04 man g++ command returns the GCC(1) manual page.

The Ubuntu 16.04 and 18.04 man gcc states that ...

g++ accepts mostly the same options as gcc

and that the default ...

... use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.

Search the gcc man pages for more details on the option variances between gcc and g++.

Which one should be used for general c++ development?

Technically, either gcc or g++ can be used for general C++ development with applicable option settings. However, the g++ default behavior is naturally aligned to a C++ development.

The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph:

The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead.

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

How do I detect if I am in release or debug mode?

The simplest, and best long-term solution, is to use BuildConfig.DEBUG. This is a boolean value that will be true for a debug build, false otherwise:

if (BuildConfig.DEBUG) {
  // do something for a debug build
}

There have been reports that this value is not 100% reliable from Eclipse-based builds, though I personally have not encountered a problem, so I cannot say how much of an issue it really is.

If you are using Android Studio, or if you are using Gradle from the command line, you can add your own stuff to BuildConfig or otherwise tweak the debug and release build types to help distinguish these situations at runtime.

The solution from Illegal Argument is based on the value of the android:debuggable flag in the manifest. If that is how you wish to distinguish a "debug" build from a "release" build, then by definition, that's the best solution. However, bear in mind that going forward, the debuggable flag is really an independent concept from what Gradle/Android Studio consider a "debug" build to be. Any build type can elect to set the debuggable flag to whatever value that makes sense for that developer and for that build type.

Convert a video to MP4 (H.264/AAC) with ffmpeg

You can also try adding the Motumedia PPA to your apt sources and update your ffmpeg packages.

Display A Popup Only Once Per User

You can use removeItem() class of localStorage to destroy that key on browser close with:

window.onbeforeunload = function{
    localStorage.removeItem('your key');
};

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Rather than doing string manipulation, you can use the HOUR, MINUTE, SECOND functions to break apart the time. You can then multiply by 60*60*1000, 60*1000, and 1000 respectively to get milliseconds.

Connecting to a network folder with username/password in Powershell

PowerShell 3 supports this out of the box now.

If you're stuck on PowerShell 2, you basically have to use the legacy net use command (as suggested earlier).

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

delete_all vs destroy_all?

I’ve made a small gem that can alleviate the need to manually delete associated records in some circumstances.

This gem adds a new option for ActiveRecord associations:

dependent: :delete_recursively

When you destroy a record, all records that are associated using this option will be deleted recursively (i.e. across models), without instantiating any of them.

Note that, just like dependent: :delete or dependent: :delete_all, this new option does not trigger the around/before/after_destroy callbacks of the dependent records.

However, it is possible to have dependent: :destroy associations anywhere within a chain of models that are otherwise associated with dependent: :delete_recursively. The :destroy option will work normally anywhere up or down the line, instantiating and destroying all relevant records and thus also triggering their callbacks.

How can we redirect a Java program console output to multiple files?

Go to run as and choose Run Configurations -> Common and in the Standard Input and Output you can choose a File also.

File size exceeds configured limit (2560000), code insight features not available

Windows default install location for Webstorm:

C:\Program Files\JetBrains\WebStorm 2019.1.3\bin\idea.properties

I went x4 default for intellisense and x5 for file size

(my business workstation is a beast though: 8th gen i7, 32Gb RAM, NVMe PCIE3.0x4 SDD, gloat, etc, gloat, etc)

#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#--------------------------------------------------------------------- 
idea.max.intellisense.filesize=10000

    #---------------------------------------------------------------------
    # Maximum file size (kilobytes) IDE is able to open.
    #--------------------------------------------------------------------- 

idea.max.content.load.filesize=100000

How to refresh activity after changing language (Locale) inside application

I solved my problem with this code

public void setLocale(String lang) {

        myLocale = new Locale(lang);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

        onConfigurationChanged(conf);
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) 
    {
        iv.setImageDrawable(getResources().getDrawable(R.drawable.keyboard));
        greet.setText(R.string.greet);
        textView1.setText(R.string.langselection);

        super.onConfigurationChanged(newConfig);

    }

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size. To make this happen, the compiler pads structure members so the following member or following struct will be aligned.

struct pixel {
    unsigned char red;   // 0
    unsigned char green; // 1
    unsigned int alpha;  // 4 (gotta skip to an aligned offset)
    unsigned char blue;  // 8 (then skip 9 10 11)
};

// next offset: 12

The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.

Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those. (They ignored the low-order bits.)

Finally, note that cache lines can be arbitrarily large, and the compiler doesn't attempt to guess at those or make a space-vs-speed tradeoff. Instead, the alignment decisions are part of the ABI and represent the minimum alignment that will eventually evenly fill up a cache line.

TL;DR: alignment is important.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

How do I check if there are duplicates in a flat list?

def check_duplicates(my_list):
    seen = {}
    for item in my_list:
        if seen.get(item):
            return True
        seen[item] = True
    return False

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

How do I perform a Perl substitution on a string while keeping the original?

The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.

In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.

Frame Buster Buster ... buster code needed

If you add an alert right after the buster code, then the alert will stall the javascript thread, and it will let the page load. This is what StackOverflow does, and it busts out of my iframes, even when I use the frame busting buster. It also worked with my simple test page. This has only been tested in Firefox 3.5 and IE7 on windows.

Code:

<script type="text/javascript">
if (top != self){
  top.location.replace(self.location.href);
  alert("for security reasons bla bla bla");
}
</script>

Basic text editor in command prompt?

I made a simple VIM clone from batch to satisfy your needs.

@echo off
title WinVim
color a
cls
echo WinVim 1.02
echo.
echo To save press CTRL+Z then press enter
echo.
echo Make sure to include extension in file name
set /p name=File Name:
copy con %name%
if exist %name% copy %name% + con

Hope this helps :)

How to calculate Date difference in Hive

yes datediff is implemented; see: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF

By the way I found this by Google-searching "hive datediff", it was the first result ;)

How to get column values in one comma separated value

SELECT name, GROUP_CONCAT( section ) 
FROM  `tmp` 
GROUP BY name

How to create cron job using PHP?

Better use the project Cron in combination with the Linux cronjob for this task. It allows you to configure run times in your PHP Code, support background jobs and is easy to use.

First step call a PHP Script every minute:

* * * * * /usr/local/bin/run.php &> /dev/null

Second Step use the cron/cron Package to configure run times directly in PHP.

$deprecatedStatus = new ShellJob();
$deprecatedStatus->setCommand('cd /app && /usr/local/bin/php cron/updateDeprecatedStatus.php');
$deprecatedStatus->setSchedule(new CrontabSchedule('* * * * */2'));


$displayDate = new ShellJob();
$displayDate->setCommand('cd /app && /usr/local/bin/php cron/updateDisplayDate.php');
$displayDate->setSchedule(new CrontabSchedule('* * * * */5'));

You found the details how to use in the linked repository.

installing python packages without internet and using source code as .tar.gz and .whl

pipdeptree is a command line utility for displaying the python packages installed in an virtualenv in form of a dependency tree. Just use it: https://github.com/naiquevin/pipdeptree

Why do I always get the same sequence of random numbers with rand()?

rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().

If you want something random every time, you might try:

srand (time (0));

Redefining the Index in a Pandas DataFrame object

If you don't want 'a' in the index

In :

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

data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

data

Out:

    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In :

data2 = data.set_index('a')

Out:

     b   c
a
1    2   3
10  11  12
20  21  22

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

How to 'foreach' a column in a DataTable using C#?

You can check this out. Use foreach loop over a DataColumn provided with your DataTable.

 foreach(DataColumn column in dtTable.Columns)
 {
     // do here whatever you want to...
 }

How to connect to mysql with laravel?

You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.

Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.

Check if a specific value exists at a specific key in any subarray of a multidimensional array

If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}

Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';

Populate unique values into a VBA array from Excel

The VBA script below looks for all unique values from cell B5 all the way down to the very last cell in column B… $B$1048576. Once it is found, they are stored in the array (objDict).

Private Const SHT_MASTER = “MASTER”
Private Const SHT_INST_INDEX = “InstrumentIndex”

Sub UniqueList()
    Dim Xyber
    Dim objDict As Object
    Dim lngRow As Long

    Sheets(SHT_MASTER).Activate
    Xyber = Application.Transpose(Sheets(SHT_MASTER).Range([b5], Cells(Rows.count, “B”).End(xlUp)))
    Sheets(SHT_INST_INDEX).Activate
    Set objDict = CreateObject(“Scripting.Dictionary”)
    For lngRow = 1 To UBound(Xyber, 1)
    If Len(Xyber(lngRow)) > 0 Then objDict(Xyber(lngRow)) = 1
    Next
    Sheets(SHT_INST_INDEX).Range(“B1:B” & objDict.count) = Application.Transpose(objDict.keys)
End Sub

I have tested and documented with some screenshots of the this solution. Here is the link where you can find it....

http://xybernetics.com/techtalk/excelvba-getarrayofuniquevaluesfromspecificcolumn/

grep using a character vector with multiple patterns

In addition to @Marek's comment about not including fixed==TRUE, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6".

You also mention that there are lots of patterns. Assuming that they are in a vector

toMatch <- c("A1", "A9", "A6")

Then you can create your regular expression directly using paste and collapse = "|".

matches <- unique (grep(paste(toMatch,collapse="|"), 
                        myfile$Letter, value=TRUE))

sql server #region

I've used a technique similar to McVitie's, and only in stored procedures or scripts that are pretty long. I will break down certain functional portions like this:

BEGIN /** delete queries **/

DELETE FROM blah_blah

END /** delete queries **/

BEGIN /** update queries **/

UPDATE sometable SET something = 1

END /** update queries **/

This method shows up fairly nice in management studio and is really helpful in reviewing code. The collapsed piece looks sort of like:

BEGIN /** delete queries **/ ... /** delete queries **/

I actually prefer it this way because I know that my BEGIN matches with the END this way.

Finding all cycles in a directed graph

Depth first search with backtracking should work here. Keep an array of boolean values to keep track of whether you visited a node before. If you run out of new nodes to go to (without hitting a node you have already been), then just backtrack and try a different branch.

The DFS is easy to implement if you have an adjacency list to represent the graph. For example adj[A] = {B,C} indicates that B and C are the children of A.

For example, pseudo-code below. "start" is the node you start from.

dfs(adj,node,visited):  
  if (visited[node]):  
    if (node == start):  
      "found a path"  
    return;  
  visited[node]=YES;  
  for child in adj[node]:  
    dfs(adj,child,visited)
  visited[node]=NO;

Call the above function with the start node:

visited = {}
dfs(adj,start,visited)

What is the most elegant way to check if all values in a boolean array are true?

boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
   alltrue &= booleanArray[i];

I think this looks ok and behaves well...

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

How to position three divs in html horizontally?

I'd refrain from using floats for this sort of thing; I'd rather use inline-block.

Some more points to consider:

  • Inline styles are bad for maintainability
  • You shouldn't have spaces in selector names
  • You missed some important HTML tags, like <head> and <body>
  • You didn't include a doctype

Here's a better way to format your document:

<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
    <div id="left">Left Side Menu</div>
    <div id="middle">Random Content</div>
    <div id="right">Right Side Menu</div>
</div>
</body>
</html>

Here's a jsFiddle for good measure.

How to set tint for an image view programmatically in android?

You can change the tint, quite easily in code via:

imageView.setColorFilter(Color.argb(255, 255, 255, 255)); // White Tint

If you want color tint then

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.MULTIPLY);

For Vector Drawable

imageView.setColorFilter(ContextCompat.getColor(context, R.color.COLOR_YOUR_COLOR), android.graphics.PorterDuff.Mode.SRC_IN);

UPDATE:
@ADev has newer solution in his answer here, but his solution requires newer support library - 25.4.0 or above.

C++ IDE for Linux?

make + vim + gdb = one great IDE

How to get current memory usage in android?

Another way (currently showing 25MB free on my G1):

MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;

jQuery ui datepicker with Angularjs

var selectDate = element.datepicker({
    dateFormat:'dd/mm/yy',
    onSelect:function (date) {
        ngModelCtrl.$setViewValue(date);
        scope.$apply();
    }
}).on('changeDate', function(ev) {
    selectDate.hide();
    ngModelCtrl.$setViewValue(element.val());
    scope.$apply();
});                            

Why are my PowerShell scripts not running?

We can bypass execution policy in a nice way (inside command prompt):

type file.ps1 | powershell -command -

Or inside powershell:

gc file.ps1|powershell -c -

Hash Map in Python

class HashMap:
    def __init__(self):
        self.size = 64
        self.map = [None] * self.size

    def _get_hash(self, key):
        hash = 0

        for char in str(key):
            hash += ord(char)
        return hash % self.size

    def add(self, key, value):
        key_hash = self._get_hash(key)
        key_value = [key, value]

        if self.map[key_hash] is None:
            self.map[key_hash] = list([key_value])
            return True
        else:
            for pair in self.map[key_hash]:
                if pair[0] == key:
                    pair[1] = value
                    return True
                else:
                    self.map[key_hash].append(list([key_value]))
                    return True

    def get(self, key):
        key_hash = self._get_hash(key)
        if self.map[key_hash] is not None:
            for pair in self.map[key_hash]: 
                if pair[0] == key:
                    return pair[1]
        return None

    def delete(self, key):
        key_hash = self._get_hash(key)

        if self.map[key_hash] is None :
            return False
        for i in range(0, len(self.map[key_hash])):
            if self.map[key_hash][i][0] == key:
                self.map[key_hash].pop(i)
                return True

    def print(self):

        print('---Phonebook---')
        for item in self.map:
            if item is not None:
                print(str(item))

h = HashMap()

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2019 (Express Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQL2019\Express_ENU and click OK

Database Structure for Tree Data Structure

If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)

In common LDAP is used to organize records in hierarchical structure.

How to get all registered routes in Express?

Here's a little thing I use just to get the registered paths in express 4.x

app._router.stack          // registered routes
  .filter(r => r.route)    // take out all the middleware
  .map(r => r.route.path)  // get all the paths

How to apply box-shadow on all four sides?

You can different combinations at the following link.
https://www.cssmatic.com/box-shadow

The results which you need can be achieved by the following CSS

-webkit-box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);
-moz-box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);
box-shadow: 0px 0px 11px 1px rgba(0,0,0,1);

Force decimal point instead of comma in HTML5 number input (client-side)

Currently, Firefox honors the language of the HTML element in which the input resides. For example, try this fiddle in Firefox:

http://jsfiddle.net/ashraf_sabry_m/yzzhop75/1/

You will see that the numerals are in Arabic, and the comma is used as the decimal separator, which is the case with Arabic. This is because the BODY tag is given the attribute lang="ar-EG".

Next, try this one:

http://jsfiddle.net/ashraf_sabry_m/yzzhop75/2/

This one is displayed with a dot as the decimal separator because the input is wrapped in a DIV given the attribute lang="en-US".

So, a solution you may resort to is to wrap your numeric inputs with a container element that is set to use a culture that uses dots as the decimal separator.

Determine if char is a num or letter

You'll want to use the isalpha() and isdigit() standard functions in <ctype.h>.

char c = 'a'; // or whatever

if (isalpha(c)) {
    puts("it's a letter");
} else if (isdigit(c)) {
    puts("it's a digit");
} else {
    puts("something else?");
}

Javac is not found

Easiest way: search for javac.exe in windows search bar. Then copy and paste the entire folder name and add it into the environmental variables path in advanced system settings.

Is there a way to iterate over a range of integers?

It was suggested by Mark Mishyn to use slice but there is no reason to create array with make and use in for returned slice of it when array created via literal can be used and it's shorter

for i := range [5]int{} {
        fmt.Println(i)
}

Multi-line bash commands in makefile

As indicated in the question, every sub-command is run in its own shell. This makes writing non-trivial shell scripts a little bit messy -- but it is possible! The solution is to consolidate your script into what make will consider a single sub-command (a single line).

Tips for writing shell scripts within makefiles:

  1. Escape the script's use of $ by replacing with $$
  2. Convert the script to work as a single line by inserting ; between commands
  3. If you want to write the script on multiple lines, escape end-of-line with \
  4. Optionally start with set -e to match make's provision to abort on sub-command failure
  5. This is totally optional, but you could bracket the script with () or {} to emphasize the cohesiveness of a multiple line sequence -- that this is not a typical makefile command sequence

Here's an example inspired by the OP:

mytarget:
    { \
    set -e ;\
    msg="header:" ;\
    for i in $$(seq 1 3) ; do msg="$$msg pre_$${i}_post" ; done ;\
    msg="$$msg :footer" ;\
    echo msg=$$msg ;\
    }

Bootstrap Modal immediately disappearing

I had added bootstrap to my project via bower, then I imported the bootstrap.min.js file and after the modal.js file. (The button that opens the modal is inside a form). I just remove the import for modal.js and it works for me.

Tree view of a directory/folder in Windows?

TreeSize professional has what you want. but it focus on the sizes of folders and files.

Simple http post example in Objective-C?

You can do using two options:

Using NSURLConnection:

NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
// Form URL-Encoded Body

NSDictionary* bodyParameters = @{
    @"username": @"reallyrambody",
    @"password": @"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];

// Connection

NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];

/*
 * Utils: Add this section before your class implementation
 */

/**
 This creates a new query parameters string from the given NSDictionary. For
 example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
 string will be @"day=Tuesday&month=January".
 @param queryParameters The input dictionary.
 @return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
            [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
            [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
        ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
        [URL absoluteString],
        NSStringFromQueryParameters(queryParameters)
    ];
    return [NSURL URLWithString:URLString];
}

Using NSURLSession

- (void)sendRequest:(id)sender
{
    /* Configure session, choose between:
       * defaultSessionConfiguration
       * ephemeralSessionConfiguration
       * backgroundSessionConfigurationWithIdentifier:
     And set session-wide properties, such as: HTTPAdditionalHeaders,
     HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
     */
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];

    /* Create the Request:
       Token Duplicate (POST http://www.example.com/path)
     */

    NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";

    // Form URL-Encoded Body

    NSDictionary* bodyParameters = @{
        @"username": @"reallyram",
        @"password": @"123456"
    };
    request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];

    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
        }
        else {
            // Failure
            NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
        }
    }];
    [task resume];
}

/*
 * Utils: Add this section before your class implementation
 */

/**
 This creates a new query parameters string from the given NSDictionary. For
 example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
 string will be @"day=Tuesday&month=January".
 @param queryParameters The input dictionary.
 @return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
            [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
            [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
        ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
        [URL absoluteString],
        NSStringFromQueryParameters(queryParameters)
    ];
    return [NSURL URLWithString:URLString];
}

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

List<String> list = new ArrayList<String>(listOfTopicAuthors);

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had a such problem too because i was using IMG tag and UL tag.

Try to apply the 'corners' plugin to elements such as $('#mydiv').corner(), $('#myspan').corner(), $('#myp').corner() but NOT for $('#img').corner()! This rule is related with adding child DIVs into specified element for emulation round-corner effect. As we know IMG element couldn't have any child elements.

I've solved this by wrapping a needed element within the div and changing IMG to DIV with background: CSS property.

Good luck!

If (Array.Length == 0)

You can use

if (array == null || array.Length == 0)

OR

if (!(array != null && array.Length != 0))

NOTE!!!!! To insure that c# will implement the short circuit correctly; you have to compare that the object with NULL before you go to the children compare of the object.

C# 7.0 and above

if(!(array?.Length != 0))

Column count doesn't match value count at row 1

MySQL will also report "Column count doesn't match value count at row 1" if you try to insert multiple rows without delimiting the row sets in the VALUES section with parentheses, like so:

INSERT INTO `receiving_table`
  (id,
  first_name,
  last_name)
VALUES 
  (1002,'Charles','Babbage'),
  (1003,'George', 'Boole'),
  (1001,'Donald','Chamberlin'),
  (1004,'Alan','Turing'),
  (1005,'My','Widenius');

How to get the part of a file after the first line that matches a regular expression?

This could be a one way of doing it. If you know what line of the file you have your grep word and how many lines you have in your file:

grep -A466 'TERMINATE' file

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

For each row in an R dataframe

Well, since you asked for R equivalent to other languages, I tried to do this. Seems to work though I haven't really looked at which technique is more efficient in R.

> myDf <- head(iris)
> myDf
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> nRowsDf <- nrow(myDf)
> for(i in 1:nRowsDf){
+ print(myDf[i,4])
+ }
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.4

For the categorical columns though, it would fetch you a Data Frame which you could typecast using as.character() if needed.

Using margin:auto to vertically-align a div

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background:yellow;
    width:200px;
    padding:10px;
}

 - 


----------


<div class="black">
<div class="message">
    This is a popup message.
</div>

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

Implementing two interfaces in a class with same method. Which interface method is overridden?

As far as the compiler is concerned, those two methods are identical. There will be one implementation of both.

This isn't a problem if the two methods are effectively identical, in that they should have the same implementation. If they are contractually different (as per the documentation for each interface), you'll be in trouble.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

var filteredFiles = Directory
    .EnumerateFiles(path, "*.*") // .NET4 better than `GetFiles`
    .Where(
        // ignorecase faster than tolower...
        file => file.ToLower().EndsWith("aspx")
        || file.EndsWith("ascx", StringComparison.OrdinalIgnoreCase))
    .ToList();

Or, it may be faster to split and merge your globs (at least it looks cleaner):

"*.ext1;*.ext2".Split(';')
    .SelectMany(g => Directory.EnumerateFiles(path, g))
    .ToList();

How to upgrade Git to latest version on macOS?

You need to adjust shell path , the path will be set in either .bashrc or .bash_profile in your home directory, more likely .bash_profile.

So add into the path similar to the below and keep what you already have in the path, each segment is separated by a colon:

export PATH="/usr/local/bin:/usr/bin/git:/usr/bin:/usr/local/sbin:$PATH"

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

Is an HTTPS query string secure?

You can send password as MD5 hash param with some salt added. Compare it on the server side for auth.

Image overlay on responsive sized images bootstrap

<div class="col-md-4 py-3 pic-card">
          <div class="card ">
          <div class="pic-overlay"></div>
          <img class="img-fluid " src="images/Site Images/Health & Fitness-01.png" alt="">
          <div class="centeredcard">
            <h3>
              <span class="card-headings">HEALTH & FITNESS</span>
            </h3>
            <div class="content-inner mt-5">
              <p class="lead  p-overlay">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae ipsam nemo quasi quo quae voluptate.</p>
            </div>
          </div>
          </div>
        </div>


.pic-card{
     position: relative;

 }
 .pic-overlay{

    top: 0;
    left: 0;
    right:0;
    bottom:0;
    width: 100%;
    height: 100%;
    position: absolute;
    transition: background-color 0.5s ease;

 }
 .content-inner{
    position: relative;
     display: none;
 }

 .pic-card:hover{
     .pic-overlay{
        background-color: $dark-overlay;

     }

     .content-inner{
         display: block;
         cursor: pointer;
     }

     .card-headings{
        font-size: 15px;
        padding: 0;
     }

     .card-headings::after{
        content: '';
        width: 80%;
        border-bottom: solid 2px  rgb(52, 178, 179);
        position: absolute;
        left: 5%;
        top: 25%;
        z-index: 1;
     }
     .p-overlay{
         font-size: 15px;
     }
 }



enter code here

Check if string is in a pandas dataframe

If there is any chance that you will need to search for empty strings,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.

Instead, use

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

Calculate logarithm in python

math.log10(1.5)

Use the log10 function in the math module.

Reverse Contents in Array

First of all what value do you have in this pice of code? int temp;? You can't tell because in every single compilation it will have different value - you should initialize your value to not have trash value from memory. Next question is: why you assign this temp value to your array? If you want to stick with your solution I would change reverse function like this:

void reverse(int arr[], int count)
{
    int temp = 0;
    for (int i = 0; i < count/2; ++i)
    {
        temp = arr[count - i - 1];
        arr[count - i - 1] = arr[i];
        arr[i] = temp;
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

Now it will works but you have other options to handle this problem.

Solution using pointers:

void reverse(int arr[], int count)
{
    int* head = arr;
    int* tail = arr + count - 1;
    for (int i = 0; i < count/2; ++i)
    {
        if (head < tail)
        {
            int tmp = *tail;
            *tail = *head;
            *head = tmp;

            head++; tail--;
        }
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

And ofc like Carlos Abraham says use build in function in algorithm library

Graphviz: How to go from .dot to a graph?

dot file.dot -Tpng -o image.png

This works on Windows and Linux. Graphviz must be installed.

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

jQuery calculate sum of values in all text fields

If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce() method. You will need to convert your JQuery object into an array first:

 var sum = $('.price').toArray().reduce(function(sum,element) {
     if(isNaN(sum)) sum = 0;
     return sum + Number(element.value);
 }, 0);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

How to redirect 404 errors to a page in ExpressJS?

app.get('*',function(req,res){
 res.redirect('/login');
});

android studio 0.4.2: Gradle project sync failed error

After reporting the problem on the Android Studio feedback site, they found a solution for me. I am now using Gradle 1.10 and Android Studio 0.4.3.

Here is the link to the page with a description of how I fixed mine: https://code.google.com/p/android/issues/detail?id=65219

Hope this helps!

How to convert 'binary string' to normal string in Python3?

Please, see oficial encode() and decode() documentation from codecs library. utf-8 is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1 or utf_32.

Manifest Merger failed with multiple errors in Android Studio

This error occurs because you don't have proper statements at the Manifest root such:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.test">

So you should remove additional texts in it.

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

Write string to text file and ensure it always overwrites the existing content.

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

SQL left join vs multiple tables on FROM line?

The second is preferred because it is far less likely to result in an accidental cross join by forgetting to put inthe where clause. A join with no on clause will fail the syntax check, an old style join with no where clause will not fail, it will do a cross join.

Additionally when you later have to a left join, it is helpful for maintenance that they all be in the same structure. And the old syntax has been out of date since 1992, it is well past time to stop using it.

Plus I have found that many people who exclusively use the first syntax don't really understand joins and understanding joins is critical to getting correct results when querying.

how to set start value as "0" in chartjs?

For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes instead of yAxes. Note that an array (and plural) is used for yAxes (or xAxes), because you may as well have multiple axes.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

While pd.set_option('display.max_columns', None) sets the number of the maximum columns shown, the option pd.set_option('display.max_colwidth', -1) sets the maximum width of each single field.

For my purposes I wrote a small helper function to fully print huge data frames without affecting the rest of the code, it also reformats float numbers and sets the virtual display width. You may adopt it for your use cases.

def print_full(x):
    pd.set_option('display.max_rows', None)
    pd.set_option('display.max_columns', None)
    pd.set_option('display.width', 2000)
    pd.set_option('display.float_format', '{:20,.2f}'.format)
    pd.set_option('display.max_colwidth', None)
    print(x)
    pd.reset_option('display.max_rows')
    pd.reset_option('display.max_columns')
    pd.reset_option('display.width')
    pd.reset_option('display.float_format')
    pd.reset_option('display.max_colwidth')

How to get value of checked item from CheckedListBox?

You can iterate over the CheckedItems property:

foreach(object itemChecked in checkedListBox1.CheckedItems)
{
    MyCompanyClass company = (MyCompanyClass)itemChecked;    
    MessageBox.Show("ID: \"" + company.ID.ToString());
}

http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

gulp command not found - error after installing gulp

I had v0.12.3 of Nodejs on Win7 x64 and ran into similar issues when I tried installing gulp. This worked for me:

  1. Uninstalled Nodejs
  2. Installed Nodejs v0.10.29
  3. npm install -g npm
  4. npm install -g gulp

Android Room - simple select query - Cannot access database on the main thread

For quick queries you can allow room to execute it on UI thread.

AppDatabase db = Room.databaseBuilder(context.getApplicationContext(),
        AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();

In my case I had to figure out of the clicked user in list exists in database or not. If not then create the user and start another activity

       @Override
        public void onClick(View view) {



            int position = getAdapterPosition();

            User user = new User();
            String name = getName(position);
            user.setName(name);

            AppDatabase appDatabase = DatabaseCreator.getInstance(mContext).getDatabase();
            UserDao userDao = appDatabase.getUserDao();
            ArrayList<User> users = new ArrayList<User>();
            users.add(user);
            List<Long> ids = userDao.insertAll(users);

            Long id = ids.get(0);
            if(id == -1)
            {
                user = userDao.getUser(name);
                user.setId(user.getId());
            }
            else
            {
                user.setId(id);
            }

            Intent intent = new Intent(mContext, ChatActivity.class);
            intent.putExtra(ChatActivity.EXTRAS_USER, Parcels.wrap(user));
            mContext.startActivity(intent);
        }
    }

Disable Rails SQL logging in console

Just as an FYI, in Rails 2 you can do

ActiveRecord::Base.silence { <code you don't want to log goes here> }

Obviously the curly braces could be replaced with a do end block if you wanted.

How to display div after click the button in Javascript?

HTML Code:

<div id="welcomeDiv"  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />

Javascript:

function showDiv() {
   document.getElementById('welcomeDiv').style.display = "block";
}

See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/

Error: [ng:areq] from angular controller

There's also another way this could happen.

In my app I have a main module that takes care of the ui-router state management, config, and things like that. The actual functionality is all defined in other modules.

I had defined a module

angular.module('account', ['services']);

that had a controller 'DashboardController' in it, but had forgotten to inject it into the main module where I had a state that referenced the DashboardController.

Since the DashboardController wasn't available because of the missing injection, it threw this error.

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?

Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

document.createElement("script") synchronously

The answers above pointed me in the right direction. Here is a generic version of what I got working:

  var script = document.createElement('script');
  script.src = 'http://' + location.hostname + '/module';
  script.addEventListener('load', postLoadFunction);
  document.head.appendChild(script);

  function postLoadFunction() {
     // add module dependent code here
  }      

How to download/checkout a project from Google Code in Windows?

If you install TortoiseSVN you can use SVN under windows. It also gives you the SVN binaries. You needn't do the checkout from the command-line though as it integrates into Windows Explorer for you.

Using port number in Windows host file

Using netsh with connectaddress=127.0.0.1 did not work for me.

Despite looking everywhere on the internet I could not find the solution which solved this for me, which was to use connectaddress=127.x.x.x (i.e. any 127. ipv4 address, just not 127.0.0.1) as this appears to link back to localhost just the same but without the restriction, so that the loopback works in netsh.

How do I Set Background image in Flutter?

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

Check if a variable is a string in JavaScript

Performance

Today 2020.09.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.

Results

For all browsers (and both test cases)

  • solutions typeof||instanceof (A, I) and x===x+'' (H) are fast/fastest
  • solution _.isString (lodash lib) is medium/fast
  • solutions B and K are slowest

enter image description here

Update: 2020.11.28 I update results for x=123 Chrome column - for solution I there was probably an error value before (=69M too low) - I use Chrome 86.0 to repeat tests.

Details

I perform 2 tests cases for solutions A B C D E F G H I J K L

  • when variable is string - you can run it HERE
  • when variable is NOT string - you can run it HERE

Below snippet presents differences between solutions

_x000D_
_x000D_
// https://stackoverflow.com/a/9436948/860099
function A(x) {
  return (typeof x == 'string') || (x instanceof String)
}

// https://stackoverflow.com/a/17772086/860099
function B(x) {
  return Object.prototype.toString.call(x) === "[object String]"
}

// https://stackoverflow.com/a/20958909/860099
function C(x) {
  return _.isString(x);
}

// https://stackoverflow.com/a/20958909/860099
function D(x) {
  return $.type(x) === "string";
}

// https://stackoverflow.com/a/16215800/860099
function E(x) {
  return x?.constructor === String;
}

// https://stackoverflow.com/a/42493631/860099
function F(x){
  return x?.charAt != null
}


// https://stackoverflow.com/a/57443488/860099
function G(x){
  return String(x) === x
}

// https://stackoverflow.com/a/19057360/860099
function H(x){
  return x === x + ''
}

// https://stackoverflow.com/a/4059166/860099
function I(x) {
  return typeof x == 'string'
}

// https://stackoverflow.com/a/28722301/860099
function J(x){
  return x === x?.toString()
}

// https://stackoverflow.com/a/58892465/860099
function K(x){
  return x && typeof x.valueOf() === "string"
}

// https://stackoverflow.com/a/9436948/860099
function L(x) {
  return x instanceof String
}

// ------------------
//     PRESENTATION
// ------------------

console.log('Solutions results for different inputs \n\n');
console.log("'abc' Str  ''  ' ' '1' '0'  1   0   {} [] true false null undef");

let tests = [ 'abc', new String("abc"),'',' ','1','0',1,0,{},[],true,false,null,undefined];

[A,B,C,D,E,F,G,H,I,J,K,L].map(f=> {  
console.log(
  `${f.name}   ` + tests.map(v=> (1*!!f(v)) ).join`   `
)})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>


This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

For easier use CI have updated this so you can just use

$this->load->helper('language');

and to translate text

lang('language line');

and if you want to warp it inside label then use optional parameter

lang('language line', 'element id');

This will output

// becomes <label for="form_item_id">language_key</label>

For good reading http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html

What is the !! (not not) operator in JavaScript?

Some operators in JavaScript perform implicit type conversions, and are sometimes used for type conversion.

The unary ! operator converts its operand to a boolean and negates it.

This fact lead to the following idiom that you can see in your source code:

!!x // Same as Boolean(x). Note double exclamation mark

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Use putty. Put install directory path in environment values (PATH), and restart your PC if required.

Open cmd (command prompt) and type

C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/

It'll be copied to the system.

HTML Drag And Drop On Mobile Devices

The Sortable JS library is compatible with touch screens and does not require jQuery.

The way it handles touch screens it that you need to touch the screen for about 1 second to start dragging an item.

Also, they present a video test showing that this library is running faster than JQuery UI Sortable.

Clicking the back button twice to exit an activity

I know this is a very old question, but this is the easiest way to do what you want.

@Override
public void onBackPressed() {
   ++k; //initialise k when you first start your activity.
   if(k==1){
      //do whatever you want to do on first click for example:
      Toast.makeText(this, "Press back one more time to exit", Toast.LENGTH_LONG).show();
   }else{
      //do whatever you want to do on the click after the first for example:
      finish(); 
   }
}

I know this isn't the best method, but it works fine!

How to vertically center an image inside of a div element in HTML using CSS?

Another way is to set your line-height in the container div, and align your image to that using vertical-align: middle.

html:

<div class="container"><img></div>

css:

.container {
  width: 200px; /* or whatever you want */
  height: 200px; /* or whatever you want */
  line-height: 200px; /* or whatever you want, should match height */
  text-align: center;
}

.container > img {
  vertical-align: middle;
}

It's off the top of my head. But I've used this before - it should do the trick. Works for older browsers as well.

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

Error 500: Premature end of script headers

After many diff's, this was what was missing from the httpd.conf file on the server in question:

AddHandler php5-script .php

Solved the issue.

Unable to create Android Virtual Device

There is a new possible error for this one related to the latest Android Wear technology. I was trying to get an emulator started for the wear SDK in preparation for next week. The API level only supports it in the latest build of 4.4.2 KitKat.

So if you are using something such as the wearable, it starts the default off still in Eclipse as 2.3.3 Gingerbread. Be sure that your target matches the lowest possible supported target. For the wearables its the latest 19 KitKat.

C# How do I click a button by hitting Enter whilst textbox has focus?

I came across this whilst looking for the same thing myself, and what I note is that none of the listed answers actually provide a solution when you don't want to click the 'AcceptButton' on a Form when hitting enter.

A simple use-case would be a text search box on a screen where pressing enter should 'click' the 'Search' button, not execute the Form's AcceptButton behaviour.

This little snippet will do the trick;

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        if (!textBox.AcceptsReturn)
        {
            button1.PerformClick();
        }
    }
}

In my case, this code is part of a custom UserControl derived from TextBox, and the control has a 'ClickThisButtonOnEnter' property. But the above is a more general solution.

How to center a (background) image within a div?

This works for me for aligning the image to center of div.

.yourclass {
  background-image: url(image.png);
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

How to get difference between two rows for a column field?

select t1.rowInt,t1.Value,t2.Value-t1.Value as diff
from (select * from myTable) as t1,
     (select * from myTable where rowInt!=1
      union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2
where t1.rowInt=t2.rowInt-1

Load local HTML file in a C# WebBrowser

Update on @ghostJago answer above

for me it worked as the following lines in VS2017

string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh after the last command of st_new.sh has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that st_new.sh contains such a command. If that is the case, then you need to modify the script:

cmd &
BACK_PID=$!

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want
done

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

How to get file extension from string in C++

This is a solution I came up with. Then, I noticed that it is similar to what @serengeor posted.

It works with std::string and find_last_of, but the basic idea will also work if modified to use char arrays and strrchr. It handles hidden files, and extra dots representing the current directory. It is platform independent.

string PathGetExtension( string const & path )
{
  string ext;

  // Find the last dot, if any.
  size_t dotIdx = path.find_last_of( "." );
  if ( dotIdx != string::npos )
  {
    // Find the last directory separator, if any.
    size_t dirSepIdx = path.find_last_of( "/\\" );

    // If the dot is at the beginning of the file name, do not treat it as a file extension.
    // e.g., a hidden file:  ".alpha".
    // This test also incidentally avoids a dot that is really a current directory indicator.
    // e.g.:  "alpha/./bravo"
    if ( dotIdx > dirSepIdx + 1 )
    {
      ext = path.substr( dotIdx );
    }
  }

  return ext;
}

Unit test:

int TestPathGetExtension( void )
{
  int errCount = 0;

  string tests[][2] = 
  {
    { "/alpha/bravo.txt", ".txt" },
    { "/alpha/.bravo", "" },
    { ".alpha", "" },
    { "./alpha.txt", ".txt" },
    { "alpha/./bravo", "" },
    { "alpha/./bravo.txt", ".txt" },
    { "./alpha", "" },
    { "c:\\alpha\\bravo.net\\charlie.txt", ".txt" },
  };

  int n = sizeof( tests ) / sizeof( tests[0] );

  for ( int i = 0; i < n; ++i )
  {
    string ext = PathGetExtension( tests[i][0] );
    if ( ext != tests[i][1] )
    {
      ++errCount;
    }
  }

  return errCount;
}

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If anyone is having this exception and is building the query using Scala multi-line strings:

Looks like there is a problem with some JPA drivers in this situation. I'm not sure what is the character Scala uses for LINE END, but when you have a parameter right at the end of the line, the LINE END character seems to be attached to the parameter and so when the driver parses the query, this error comes up. A simple work around is to leave an empty space right after the param at the end:

SELECT * FROM some_table a
WHERE a.col = ?param
AND a.col2 = ?param2

So, just make sure to leave an empty space after param (and param2, if you have a line break there).

Links in <select> dropdown options

You can use the onChange property. Something like:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

How to run an android app in background?

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

How to Empty Caches and Clean All Targets Xcode 4 and later

My "DerivedData" with Xcode 10.2 and Mojave was here:

MacHD/Users/[MyUser]/Library/Developer/Xcode

Splitting comma separated string in a PL/SQL stored proc

CREATE OR REPLACE PROCEDURE insert_into (
   p_errcode        OUT   NUMBER,
   p_errmesg        OUT   VARCHAR2,
   p_rowsaffected   OUT   INTEGER
)
AS
   v_param0   VARCHAR2 (30) := '0.25,2.25,33.689, abc, 99';
   v_param1   VARCHAR2 (30) := '2.65,66.32, abc-def, 21.5';
BEGIN
   FOR i IN (SELECT COLUMN_VALUE
               FROM TABLE (SPLIT (v_param0, ',')))
   LOOP
      INSERT INTO tempo
                  (col1
                  )
           VALUES (i.COLUMN_VALUE
                  );
   END LOOP;

   FOR i IN (SELECT COLUMN_VALUE
               FROM TABLE (SPLIT (v_param1, ',')))
   LOOP
      INSERT INTO tempo
                  (col2
                  )
           VALUES (i.COLUMN_VALUE
                  );
   END LOOP;
END;

AngularJs: Reload page

This can be done by calling the reload() method of the window object in plain JavaScript

window.location.reload();

How do I quickly rename a MySQL database (change schema name)?

MySQL does not support the renaming of a database through its command interface at the moment, but you can rename the database if you have access to the directory in which MySQL stores its databases. For default MySQL installations this is usually in the Data directory under the directory where MySQL was installed. Locate the name of the database you want to rename under the Data directory and rename it. Renaming the directory could cause some permissions issues though. Be aware.

Note: You must stop MySQL before you can rename the database

I would recommend creating a new database (using the name you want) and export/import the data you need from the old to the new. Pretty simple.

How do I pass named parameters with Invoke-Command?

I needed something to call scripts with named parameters. We have a policy of not using ordinal positioning of parameters and requiring the parameter name.

My approach is similar to the ones above but gets the content of the script file that you want to call and sends a parameter block containing the parameters and values.

One of the advantages of this is that you can optionally choose which parameters to send to the script file allowing for non-mandatory parameters with defaults.

Assuming there is a script called "MyScript.ps1" in the temporary path that has the following parameter block:

[CmdletBinding(PositionalBinding = $False)]
param
(
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter1,
    [Parameter(Mandatory = $True)] [String] $MyNamedParameter2,
    [Parameter(Mandatory = $False)] [String] $MyNamedParameter3 = "some default value"
)

This is how I would call this script from another script:

$params = @{
    MyNamedParameter1 = $SomeValue
    MyNamedParameter2 = $SomeOtherValue
}

If ($SomeCondition)
{
    $params['MyNamedParameter3'] = $YetAnotherValue
}

$pathToScript = Join-Path -Path $env:Temp -ChildPath MyScript.ps1

$sb = [scriptblock]::create(".{$(Get-Content -Path $pathToScript -Raw)} $(&{
        $args
} @params)")
Invoke-Command -ScriptBlock $sb

I have used this in lots of scenarios and it works really well. One thing that you occasionally need to do is put quotes around the parameter value assignment block. This is always the case when there are spaces in the value.

e.g. This param block is used to call a script that copies various modules into the standard location used by PowerShell C:\Program Files\WindowsPowerShell\Modules which contains a space character.

$params = @{
        SourcePath      = "$WorkingDirectory\Modules"
        DestinationPath = "'$(Join-Path -Path $([System.Environment]::GetFolderPath('ProgramFiles')) -ChildPath 'WindowsPowershell\Modules')'"
    }

Hope this helps!

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

New -> Batch Drawable Import -> Click on Add button -> Select image -> Select Target Resolution, Target Name, Format -> Ok

Code not running in IE 11, works fine in Chrome

Follow this method if problem comes when working with angular2+ projects

I was looking for a solution when i got this error, and it got me here. But this question seems to be specific but the error is not, its a generic error. This is a common error for angular developers dealing with Internet Explorer.

I had the same issue while working with angular 2+, and it got resolved just by few simple steps.

In Angular latest versions, there are come commented codes in the polyfills.ts shows all the polyfills required for the smooth running in Internet Explorer versions IE09,IE10 and IE11

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';

Uncomment the codes and it would work perfectly in IE browsers

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

But you might see a performance drop in IE browsers compared to others :(

How to display multiple notifications in android

notificationManager.notify(0, notification);

Put this code instead of 0

new Random().nextInt() 

Like below it works for me

notificationManager.notify(new Random().nextInt(), notification);

how to put image in center of html page?

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }

HashSet vs. List performance

A lot of people are saying that once you get to the size where speed is actually a concern that HashSet<T> will always beat List<T>, but that depends on what you are doing.

Let's say you have a List<T> that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a List<T>.

I did a test for this on my machine, and, well, it has to be very very small to get an advantage from List<T>. For a list of short strings, the advantage went away after size 5, for objects after size 20.

1 item LIST strs time: 617ms
1 item HASHSET strs time: 1332ms

2 item LIST strs time: 781ms
2 item HASHSET strs time: 1354ms

3 item LIST strs time: 950ms
3 item HASHSET strs time: 1405ms

4 item LIST strs time: 1126ms
4 item HASHSET strs time: 1441ms

5 item LIST strs time: 1370ms
5 item HASHSET strs time: 1452ms

6 item LIST strs time: 1481ms
6 item HASHSET strs time: 1418ms

7 item LIST strs time: 1581ms
7 item HASHSET strs time: 1464ms

8 item LIST strs time: 1726ms
8 item HASHSET strs time: 1398ms

9 item LIST strs time: 1901ms
9 item HASHSET strs time: 1433ms

1 item LIST objs time: 614ms
1 item HASHSET objs time: 1993ms

4 item LIST objs time: 837ms
4 item HASHSET objs time: 1914ms

7 item LIST objs time: 1070ms
7 item HASHSET objs time: 1900ms

10 item LIST objs time: 1267ms
10 item HASHSET objs time: 1904ms

13 item LIST objs time: 1494ms
13 item HASHSET objs time: 1893ms

16 item LIST objs time: 1695ms
16 item HASHSET objs time: 1879ms

19 item LIST objs time: 1902ms
19 item HASHSET objs time: 1950ms

22 item LIST objs time: 2136ms
22 item HASHSET objs time: 1893ms

25 item LIST objs time: 2357ms
25 item HASHSET objs time: 1826ms

28 item LIST objs time: 2555ms
28 item HASHSET objs time: 1865ms

31 item LIST objs time: 2755ms
31 item HASHSET objs time: 1963ms

34 item LIST objs time: 3025ms
34 item HASHSET objs time: 1874ms

37 item LIST objs time: 3195ms
37 item HASHSET objs time: 1958ms

40 item LIST objs time: 3401ms
40 item HASHSET objs time: 1855ms

43 item LIST objs time: 3618ms
43 item HASHSET objs time: 1869ms

46 item LIST objs time: 3883ms
46 item HASHSET objs time: 2046ms

49 item LIST objs time: 4218ms
49 item HASHSET objs time: 1873ms

Here is that data displayed as a graph:

enter image description here

Here's the code:

static void Main(string[] args)
{
    int times = 10000000;


    for (int listSize = 1; listSize < 10; listSize++)
    {
        List<string> list = new List<string>();
        HashSet<string> hashset = new HashSet<string>();

        for (int i = 0; i < listSize; i++)
        {
            list.Add("string" + i.ToString());
            hashset.Add("string" + i.ToString());
        }

        Stopwatch timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            list.Remove("string0");
            list.Add("string0");
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");


        timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            hashset.Remove("string0");
            hashset.Add("string0");
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
        Console.WriteLine();
    }


    for (int listSize = 1; listSize < 50; listSize+=3)
    {
        List<object> list = new List<object>();
        HashSet<object> hashset = new HashSet<object>();

        for (int i = 0; i < listSize; i++)
        {
            list.Add(new object());
            hashset.Add(new object());
        }

        object objToAddRem = list[0];

        Stopwatch timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            list.Remove(objToAddRem);
            list.Add(objToAddRem);
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");



        timer = new Stopwatch();
        timer.Start();
        for (int i = 0; i < times; i++)
        {
            hashset.Remove(objToAddRem);
            hashset.Add(objToAddRem);
        }
        timer.Stop();
        Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms");
        Console.WriteLine();
    }

    Console.ReadLine();
}

React Native Responsive Font Size

I recently ran into this problem and ended up using react-native-extended-stylesheet

You can set you rem value and additional size conditions based on screen size. As per the docs:

// component
const styles = EStyleSheet.create({
  text: {
    fontSize: '1.5rem',
    marginHorizontal: '2rem'
  }
});
// app entry
let {height, width} = Dimensions.get('window');
EStyleSheet.build({
  $rem: width > 340 ? 18 : 16
});

Resize image proportionally with CSS?

We can resize image using CSS in the browser using media queries and the principle of responsive design.

    @media screen and (orientation: portrait) {
img.ri {
    max-width: 80%;
  }
}

_x000D_
_x000D_
@media screen and (orientation: landscape) {_x000D_
  img.ri { max-height: 80%; }_x000D_
}
_x000D_
_x000D_
_x000D_

What's the difference between isset() and array_key_exists()?

array_key_exists will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null.

$a = array('key1' => '????', 'key2' => null);

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true

There is another important difference: isset doesn't complain when $a does not exist, while array_key_exists does.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

It usually because in connection manager it may be still of 50 char , hence I have resolved the problem by going to Connection Manager--> Advanced and then change to 100 or may be 1000 if its big enough

Android findViewById() in Custom View

Try this in your constructor

MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);

How do I exit the Vim editor?

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.

I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

CSS scale down image to fit in containing div, without specifing original size

Several of these things did not work for me... however, this did. Might help someone else in the future. Here is the CSS:

    .img-area {
     display: block;
     padding: 0px 0 0 0px;
     text-indent: 0;
     width: 100%;
     background-size: 100% 95%;
     background-repeat: no-repeat;
     background-image: url("https://yourimage.png");

    }

Spring REST Service: how to configure to remove null objects in json response

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

How to delete a file via PHP?

Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.

You can also use a path calculated from the directory you're currently running the script in, eg:

unlink(dirname(__FILE__) . "/../../public_files/" . $filename);

(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I've not used it myself yet)

What does 'const static' mean in C and C++?

That line of code can actually appear in several different contexts and alghough it behaves approximately the same, there are small differences.

Namespace Scope

// foo.h
static const int i = 0;

'i' will be visible in every translation unit that includes the header. However, unless you actually use the address of the object (for example. '&i'), I'm pretty sure that the compiler will treat 'i' simply as a type safe 0. Where two more more translation units take the '&i' then the address will be different for each translation unit.

// foo.cc
static const int i = 0;

'i' has internal linkage, and so cannot be referred to from outside of this translation unit. However, again unless you use its address it will most likely be treated as a type-safe 0.

One thing worth pointing out, is that the following declaration:

const int i1 = 0;

is exactly the same as static const int i = 0. A variable in a namespace declared with const and not explicitly declared with extern is implicitly static. If you think about this, it was the intention of the C++ committee to allow const variables to be declared in header files without always needing the static keyword to avoid breaking the ODR.

Class Scope

class A {
public:
  static const int i = 0;
};

In the above example, the standard explicitly specifies that 'i' does not need to be defined if its address is not required. In other words if you only use 'i' as a type-safe 0 then the compiler will not define it. One difference between the class and namespace versions is that the address of 'i' (if used in two ore more translation units) will be the same for the class member. Where the address is used, you must have a definition for it:

// a.h
class A {
public:
  static const int i = 0;
};

// a.cc
#include "a.h"
const int A::i;            // Definition so that we can take the address

How to output something in PowerShell

I think the following is a good exhibit of Echo vs. Write-Host. Notice how test() actually returns an array of ints, not a single int as one could easily be led to believe.

function test {
    Write-Host 123
    echo 456 # AKA 'Write-Output'
    return 789
}

$x = test

Write-Host "x of type '$($x.GetType().name)' = $x"

Write-Host "`$x[0] = $($x[0])"
Write-Host "`$x[1] = $($x[1])"

Terminal output of the above:

123
x of type 'Object[]' = 456 789
$x[0] = 456
$x[1] = 789

Calling a Function defined inside another function in Javascript

You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

function outer() {
  return (function inside(){
    console.log("Inside inside function");
  });
}
outer()();

Or

function outer2() {
    let inside = function inside(){
      console.log("Inside inside");
    };
    return inside;
  }
outer2()();

How to split strings into text and number?

import re

s = raw_input()
m = re.match(r"([a-zA-Z]+)([0-9]+)",s)
print m.group(0)
print m.group(1)
print m.group(2)

Reading and writing binary file

Here is a short example, the C++ way using rdbuf. I got this from the web. I can't find my original source on this:

#include <fstream>
#include <iostream>

int main () 
{
  std::ifstream f1 ("C:\\me.txt",std::fstream::binary);

  std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);

  f2<<f1.rdbuf();

  return 0;
}

Unix: How to delete files listed in a file

Use this:

while IFS= read -r file ; do rm -- "$file" ; done < delete.list

If you need glob expansion you can omit quoting $file:

IFS=""
while read -r file ; do rm -- $file ; done < delete.list

But be warned that file names can contain "problematic" content and I would use the unquoted version. Imagine this pattern in the file

*
*/*
*/*/*

This would delete quite a lot from the current directory! I would encourage you to prepare the delete list in a way that glob patterns aren't required anymore, and then use quoting like in my first example.