Programs & Examples On #Equality

Test to determine if two or more items are either the exact same item or of equal values.

How do you test to see if a double is equal to NaN?

The below code snippet will help evaluate primitive type holding NaN.

double dbl = Double.NaN; Double.valueOf(dbl).isNaN() ? true : false;

Is there a difference between "==" and "is"?

== determines if the values are equal, while is determines if they are the exact same object.

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

In a typical script there will be no performance difference. More important may be the fact that thousand "===" is 1 KB heavier than thousand "==" :) JavaScript profilers can tell you if there is a performance difference in your case.

But personally I would do what JSLint suggests. This recommendation is there not because of performance issues, but because type coercion means ('\t\r\n' == 0) is true.

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

I would like to expand on the === operator.

=== is not an equality operator!

Not.

Let's get that point really across.

You might be familiar with === as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.

So what does === do?

=== is the pattern matching operator!

  • === matches regular expressions
  • === checks range membership
  • === checks being instance of a class
  • === calls lambda expressions
  • === sometimes checks equality, but mostly it does not

So how does this madness make sense?

  • Enumerable#grep uses === internally
  • case when statements use === internally
  • Fun fact, rescue uses === internally

That is why you can use regular expressions and classes and ranges and even lambda expressions in a case when statement.

Some examples

case value
when /regexp/
  # value matches this regexp
when 4..10
  # value is in range
when MyClass
  # value is an instance of class
when ->(value) { ... }
  # lambda expression returns true
when a, b, c, d
  # value matches one of a through d with `===`
when *array
  # value matches an element in array with `===`
when x
  # values is equal to x unless x is one of the above
end

All these example work with pattern === value too, as well as with grep method.

arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)                                                                                                                            
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

What is the difference between == and equals() in Java?

The major difference between == and equals() is

1) == is used to compare primitives.

For example :

        String string1 = "Ravi";
        String string2 = "Ravi";
        String string3 = new String("Ravi");
        String string4 = new String("Prakash");

        System.out.println(string1 == string2); // true because same reference in string pool
        System.out.println(string1 == string3); // false

2) equals() is used to compare objects. For example :

        System.out.println(string1.equals(string2)); // true equals() comparison of values in the objects
        System.out.println(string1.equals(string3)); // true
        System.out.println(string1.equals(string4)); // false

jQuery object equality

If you want to check contents are equal or not then just use JSON.stringify(obj)

Eg - var a ={key:val};

var b ={key:val};

JSON.stringify(a) == JSON.stringify(b) -----> If contents are same you gets true.

What's wrong with using == to compare floats in Java?

You can use Float.floatToIntBits().

Float.floatToIntBits(sectionID) == Float.floatToIntBits(currentSectionID)

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

static bool SetsContainSameElements<T>(IEnumerable<T> set1, IEnumerable<T> set2) {
    var setXOR = new HashSet<T>(set1);
    setXOR.SymmetricExceptWith(set2);
    return (setXOR.Count == 0);
}

Solution requires .NET 3.5 and the System.Collections.Generic namespace. According to Microsoft, SymmetricExceptWith is an O(n + m) operation, with n representing the number of elements in the first set and m representing the number of elements in the second. You could always add an equality comparer to this function if necessary.

Elegant ways to support equivalence ("equality") in Python classes

I think that the two terms you're looking for are equality (==) and identity (is). For example:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True       <-- a and b have values which are equal
>>> a is b
False      <-- a and b are not the same list object

Compare object instances for equality by their attributes

If you're dealing with one or more classes which you can't change from the inside, there are generic and simple ways to do this that also don't depend on a diff-specific library:

Easiest, unsafe-for-very-complex-objects method

pickle.dumps(a) == pickle.dumps(b)

pickle is a very common serialization lib for Python objects, and will thus be able to serialize pretty much anything, really. In the above snippet I'm comparing the str from serialized a with the one from b. Unlike the next method, this one has the advantage of also type checking custom classes.

The biggest hassle: due to specific ordering and [de/en]coding methods, pickle may not yield the same result for equal objects, specially when dealing with more complex ones (e.g. lists of nested custom-class instances) like you'll frequently find in some third-party libs. For those cases, I'd recommend a different approach:

Thorough, safe-for-any-object method

You could write a recursive reflection that'll give you serializable objects, and then compare results

from collections.abc import Iterable

BASE_TYPES = [str, int, float, bool, type(None)]


def base_typed(obj):
    """Recursive reflection method to convert any object property into a comparable form.
    """
    T = type(obj)
    from_numpy = T.__module__ == 'numpy'

    if T in BASE_TYPES or callable(obj) or (from_numpy and not isinstance(T, Iterable)):
        return obj

    if isinstance(obj, Iterable):
        base_items = [base_typed(item) for item in obj]
        return base_items if from_numpy else T(base_items)

    d = obj if T is dict else obj.__dict__

    return {k: base_typed(v) for k, v in d.items()}


def deep_equals(*args):
    return all(base_typed(args[0]) == base_typed(other) for other in args[1:])

Now it doesn't matter what your objects are, deep equality is assured to work

>>> from sklearn.ensemble import RandomForestClassifier
>>>
>>> a = RandomForestClassifier(max_depth=2, random_state=42)
>>> b = RandomForestClassifier(max_depth=2, random_state=42)
>>> 
>>> deep_equals(a, b)
True

The number of comparables doesn't matter as well

>>> c = RandomForestClassifier(max_depth=2, random_state=1000)
>>> deep_equals(a, b, c)
False

My use case for this was checking deep equality among a diverse set of already trained Machine Learning models inside BDD tests. The models belonged to a diverse set of third-party libs. Certainly implementing __eq__ like other answers here suggest wasn't an option for me.

Covering all the bases

You may be in a scenario where one or more of the custom classes being compared do not have a __dict__ implementation. That's not common by any means, but it is the case of a subtype within sklearn's Random Forest classifier: <type 'sklearn.tree._tree.Tree'>. Treat these situations in a case by case basis - e.g. specifically, I decided to replace the content of the afflicted type with the content of a method that gives me representative information on the instance (in this case, the __getstate__ method). For such, the second-to-last row in base_typed became

d = obj if T is dict else obj.__dict__ if '__dict__' in dir(obj) else obj.__getstate__()

Edit: for the sake of organization, I replaced the hideous oneliner above with return dict_from(obj). Here, dict_from is a really generic reflection made to accommodate more obscure libs (I'm looking at you, Doc2Vec)

def isproperty(prop, obj):
    return not callable(getattr(obj, prop)) and not prop.startswith('_')


def dict_from(obj):
    """Converts dict-like objects into dicts
    """
    if isinstance(obj, dict):
        # Dict and subtypes are directly converted
        d = dict(obj)

    elif '__dict__' in dir(obj):
        # Use standard dict representation when available
        d = obj.__dict__

    elif str(type(obj)) == 'sklearn.tree._tree.Tree':
        # Replaces sklearn trees with their state metadata
        d = obj.__getstate__()

    else:
        # Extract non-callable, non-private attributes with reflection
        kv = [(p, getattr(obj, p)) for p in dir(obj) if isproperty(p, obj)]
        d = {k: v for k, v in kv}

    return {k: base_typed(v) for k, v in d.items()}

Do mind none of the above methods yield True for objects with the same key-value pairs in differing order, as in

>>> a = {'foo':[], 'bar':{}}
>>> b = {'bar':{}, 'foo':[]}
>>> pickle.dumps(a) == pickle.dumps(b)
False

But if you want that you could use Python's built-in sorted method beforehand anyway.

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

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

The basic concept we have to be clear while approaching this question is to understand the difference between is and ==.

"is" is will compare the memory location. if id(a)==id(b), then a is b returns true else it returns false.

so, we can say that is is used for comparing memory locations. Whereas,

== is used for equality testing which means that it just compares only the resultant values. The below shown code may acts as an example to the above given theory.

code

Click here for the code

In the case of string literals(strings without getting assigned to variables), the memory address will be same as shown in the picture. so, id(a)==id(b). remaining this is self-explanatory.

Determine if 2 lists have the same elements, regardless of order?

You can simply check whether the multisets with the elements of x and y are equal:

import collections
collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is

sorted(x) == sorted(y)

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

How do I compare strings in Java?

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

How do you compare structs for equality in C?

memcmp does not compare structure, memcmp compares the binary, and there is always garbage in the struct, therefore it always comes out False in comparison.

Compare element by element its safe and doesn't fail.

equals vs Arrays.equals in Java

import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {
   // initializing three object arrays
   Object[] array1 = new Object[] { 1, 123 };
   Object[] array2 = new Object[] { 1, 123, 22, 4 };
   Object[] array3 = new Object[] { 1, 123 };

   // comparing array1 and array2
   boolean retval=Arrays.equals(array1, array2);
   System.out.println("array1 and array2 equal: " + retval);
   System.out.println("array1 and array2 equal: " + array1.equals(array2));

   // comparing array1 and array3
   boolean retval2=Arrays.equals(array1, array3);
   System.out.println("array1 and array3 equal: " + retval2);
   System.out.println("array1 and array3 equal: " + array1.equals(array3));

   }
}

Here is the output:

    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false

Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.

Python if not == vs if !=

Using dis to look at the bytecode generated for the two versions:

not ==

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 UNARY_NOT           
             10 RETURN_VALUE   

!=

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 RETURN_VALUE   

The latter has fewer operations, and is therefore likely to be slightly more efficient.


It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar vs. if not foo == bar the number of operations is exactly the same, it's just that the COMPARE_OP changes and POP_JUMP_IF_TRUE switches to POP_JUMP_IF_FALSE:

not ==:

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 POP_JUMP_IF_TRUE        16

!=

  2           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 POP_JUMP_IF_FALSE       16

In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all.


However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__ and __ne__ for the objects in question. Per the data model documentation:

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false.

For example:

>>> class Dummy(object):
    def __eq__(self, other):
        return True
    def __ne__(self, other):
        return True


>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True

Finally, and perhaps most importantly: in general, where the two are logically identical, x != y is much more readable than not x == y.

Start ssh-agent on login

Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)

If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)

Then edit .zshrc

vim ~/.zshrc

find plugins section and update it to use ssh-agent like so:

plugins=(ssh-agent git)

And that's all! You'll have ssh-agent up and running every time you start your shell

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

In my case finish() executed immediately after a dialog has shown.

How many characters can a Java String have?

While you can in theory Integer.MAX_VALUE characters, the JVM is limited in the size of the array it can use.

public static void main(String... args) {
    for (int i = 0; i < 4; i++) {
        int len = Integer.MAX_VALUE - i;
        try {
            char[] ch = new char[len];
            System.out.println("len: " + len + " OK");
        } catch (Error e) {
            System.out.println("len: " + len + " " + e);
        }
    }
}

on Oracle Java 8 update 92 prints

len: 2147483647 java.lang.OutOfMemoryError: Requested array size exceeds VM limit
len: 2147483646 java.lang.OutOfMemoryError: Requested array size exceeds VM limit
len: 2147483645 OK
len: 2147483644 OK

Note: in Java 9, Strings will use byte[] which will mean that multi-byte characters will use more than one byte and reduce the maximum further. If you have all four byte code-points e.g. emojis, you will only get around 500 million characters

Get HTML5 localStorage keys

I agree with Kevin he has the best answer but sometimes when you have different keys in your local storage with the same values for example you want your public users to see how many times they have added their items into their baskets you need to show them the number of times as well then you ca use this:

var set = localStorage.setItem('key', 'value');
var element = document.getElementById('tagId');

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  element.innerHTML =  localStorage.getItem(localStorage.key(i)) + localStorage.key(i).length;
}

How to read file contents into a variable in a batch file?

Read file contents into a variable:

for /f "delims=" %%x in (version.txt) do set Build=%%x

or

set /p Build=<version.txt

Both will act the same with only a single line in the file, for more lines the for variant will put the last line into the variable, while set /p will use the first.

Using the variable – just like any other environment variable – it is one, after all:

%Build%

So to check for existence:

if exist \\fileserver\myapp\releasedocs\%Build%.doc ...

Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Since ?99 the matching between format specifiers and floating-point argument types in C is consistent between printf and scanf. It is

  • %f for float
  • %lf for double
  • %Lf for long double

It just so happens that when arguments of type float are passed as variadic parameters, such arguments are implicitly converted to type double. This is the reason why in printf format specifiers %f and %lf are equivalent and interchangeable. In printf you can "cross-use" %lf with float or %f with double.

But there's no reason to actually do it in practice. Don't use %f to printf arguments of type double. It is a widespread habit born back in C89/90 times, but it is a bad habit. Use %lf in printf for double and keep %f reserved for float arguments.

assembly to compare two numbers

In TASM (x86 assembly) it can look like this:

cmp BL, BH
je EQUAL       ; BL = BH
jg GREATER     ; BL > BH
jmp LESS       ; BL < BH

in this case it compares two 8bit numbers that we temporarily store in the higher and the lower part of the register B. Alternatively you might also consider using jbe (if BL <= BH) or jge/jae (if BL >= BH).

Hopefully someone finds it helpful :)

Change jsp on button click

Just use two forms.

In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.

It will be like this :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form name="main1"  method="get" action="2nd.jsp">
        <input type="submit" name="ter" value="LOGOUT" >
    </form>
    <DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
        <input type="submit" value="FEEDBACK">
    </form></DIV>
</body>
</html>

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • How to get/generate the create statement for an existing hive table?

    As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

    Usage:

    SHOW CREATE TABLE myTable;
    

    Naming convention - underscore in C++ and C# variables

    The Microsoft naming standard for C# says variables and parameters should use the lower camel case form IE: paramName. The standard also calls for fields to follow the same form but this can lead to unclear code so many teams call for an underscore prefix to improve clarity IE: _fieldName.

    Does MySQL ignore null values on unique constraints?

    Yes, MySQL allows multiple NULLs in a column with a unique constraint.

    CREATE TABLE table1 (x INT NULL UNIQUE);
    INSERT table1 VALUES (1);
    INSERT table1 VALUES (1);   -- Duplicate entry '1' for key 'x'
    INSERT table1 VALUES (NULL);
    INSERT table1 VALUES (NULL);
    SELECT * FROM table1;
    

    Result:

    x
    NULL
    NULL
    1
    

    This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.

    Javamail Could not convert socket to TLS GMail

    Try using the smtpsend program that comes with JavaMail, as described here. If that fails in the same way, there's something wrong with your JDK configuration or your network configuration.

    MySQL error #1054 - Unknown column in 'Field List'

    I had this error aswell.

    I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

    jquery function setInterval

    try this declare the function outside the ready event.

        $(document).ready(function(){    
           setInterval(swapImages(),1000); 
        });
    
    
        function swapImages(){
    
        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() :         $('#siteNewsHead img:first');
        active.removeClass('active');
        next.addClass('active');
    }
    

    How to do relative imports in Python?

    You have to append the module’s path to PYTHONPATH:

    export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"
    

    Laravel: How to Get Current Route Name? (v5 ... v7)

    You can use bellow code to get route name in blade file

    request()->route()->uri
    

    How to fluently build JSON in Java?

    The reference implementation includes a fluent interface. Check out JSONWriter and its toString-implementing subclass JSONStringer

    How to detect when keyboard is shown and hidden

    Swift - 4

    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
       addKeyBoardListener()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self) //remove observer
    }
    
    func addKeyBoardListener() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
    
    }
    
    @objc func keyboardWillHide(_ notification: Notification) {
    
    }
    

    Node: log in a file instead of the console

    You can also have a look at this npm module: https://www.npmjs.com/package/noogger

    noogger

    simple and straight forward...

    #1292 - Incorrect date value: '0000-00-00'

    After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.

    It's incorrect to use zeros in date or in datetime, just put null instead of zeros.

    How to connect android wifi to adhoc wifi?

    I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

    However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

        public class MainActivity extends Activity {
    
    private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
    private static final int CHIPKIT_WIFI_PRIORITY = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
        final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
        final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
        final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
        final TextView textIp = (TextView) findViewById(R.id.Ip);
    
        final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
    
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.BSSID = CHIPKIT_BSSID;
        wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
        wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
    
        myWifiManager.setWifiEnabled(true);
    
        int netID = myWifiManager.addNetwork(wifiConfiguration);
    
        myWifiManager.enableNetwork(netID, true);
    
        textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
                + myWifiManager.getWifiState() + "\n\n");
    
        btnDoSomething.setOnClickListener(new View.OnClickListener() {          
            public void onClick(View v) {
                clearTextViews(textWifiManager, textIp);                
            }           
        });
    
        btnNewScan.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getNewScan(myWifiManager, textWifiManager, textIp);
            }
        });     
    }
    
    private void clearTextViews(TextView...tv) {
        for(int i = 0; i<tv.length; i++){
            tv[i].setText("");
        }       
    }
    
    public void getNewScan(WifiManager wm, TextView...textViews) {
        wm.startScan();
    
        List<ScanResult> scanResult = wm.getScanResults();
    
        String scan = "";
    
        for (int i = 0; i < scanResult.size(); i++) {
            scan += (scanResult.get(i).toString() + "\n\n");
        }
    
        textViews[0].setText(scan);
        textViews[1].setText(wm.toString());
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    

    Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

    and my manifest:

        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.digilent.simpleclient"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    

    Hope that helps!

    change figure size and figure format in matplotlib

    You can set the figure size if you explicitly create the figure with

    plt.figure(figsize=(3,4))
    

    You need to set figure size before calling plt.plot() To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff

    "Correct" way to specifiy optional arguments in R functions

    You could also use missing() to test whether or not the argument y was supplied:

    fooBar <- function(x,y){
        if(missing(y)) {
            x
        } else {
            x + y
        }
    }
    
    fooBar(3,1.5)
    # [1] 4.5
    fooBar(3)
    # [1] 3
    

    Convert array of indices to 1-hot encoded numpy array

    Here is what I find useful:

    def one_hot(a, num_classes):
      return np.squeeze(np.eye(num_classes)[a.reshape(-1)])
    

    Here num_classes stands for number of classes you have. So if you have a vector with shape of (10000,) this function transforms it to (10000,C). Note that a is zero-indexed, i.e. one_hot(np.array([0, 1]), 2) will give [[1, 0], [0, 1]].

    Exactly what you wanted to have I believe.

    PS: the source is Sequence models - deeplearning.ai

    How to get everything after a certain character?

    strtok is an overlooked function for this sort of thing. It is meant to be quite fast.

    $s = '233718_This_is_a_string';
    $firstPart = strtok( $s, '_' );
    $allTheRest = strtok( '' ); 
    

    Empty string like this will force the rest of the string to be returned.

    NB if there was nothing at all after the '_' you would get a FALSE value for $allTheRest which, as stated in the documentation, must be tested with ===, to distinguish from other falsy values.

    Creating an iframe with given HTML dynamically

    The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.

    const html = '<html>...</html>';
    const iframe = document.createElement('iframe');
    const blob = new Blob([html], {type: 'text/html'});
    iframe.src = window.URL.createObjectURL(blob);
    document.body.appendChild(iframe);
    

    How to rename HTML "browse" button of an input type=file?

    1. Wrap the <input type="file"> with a <label> tag;
    2. Add a tag (with the text that you need) inside the label, like a <span> or <a>;
    3. Make this tag look like a button;
    4. Make input[type="file"] invisible via display: none.

    An unhandled exception occurred during the execution of the current web request. ASP.NET

    1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
    2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

    Check your problem is solved.

    How do I change a tab background color when using TabLayout?

    You can try this:

    <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
        <item name="tabBackground">@drawable/background</item>
    </style>
    

    In your background xml file:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_selected="true" android:drawable="@color/white" />
        <item android:drawable="@color/black" />
    </selector>
    

    Get selected value in dropdown list using JavaScript

    If you ever run across code written purely for Internet Explorer you might see this:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.options(e.selectedIndex).value;
    

    Running the above in Firefox et al will give you an 'is not a function' error, because Internet Explorer allows you to get away with using () instead of []:

    var e = document.getElementById("ddlViewBy");
    var strUser = e.options[e.selectedIndex].value;
    

    The correct way is to use square brackets.

    Html.Raw() in ASP.NET MVC Razor view

    Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

    @{int count = 0;}
    @foreach (var item in Model.Resources)
    {
        @(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw("")) 
        // some code
        @(count <= 3 ? Html.Raw("</div>") : Html.Raw("")) 
        @(count++)
    
    }
    

    By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

    Android - Back button in the title bar

    The simplest way and best practice as google explains in here :

    1.Add a parent for your childActivity in the AndroidManifest.xml :

    <activity 
            android:name=".ChildActivity"
            android:parentActivityName=".ParentActivity" >
    </activity>
    

    2.Activate the back button in your childActivity :

    myActionOrActionSupportBar.setDisplayHomeAsUpEnabled(true);
    

    Worked for me, I hope it works for you too.

    Enable VT-x in your BIOS security settings (refer to documentation for your computer)

    Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.

    Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security

    Sending mail from Python using SMTP

    Or

    import smtplib
     
    from email.message import EmailMessage
    from getpass import getpass
    
    
    password = getpass()
    
    message = EmailMessage()
    message.set_content('Message content here')
    message['Subject'] = 'Your subject here'
    message['From'] = "USERNAME@DOMAIN"
    message['To'] = "[email protected]"
    
    try:
        smtp_server = None
        smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
        smtp_server.ehlo()
        smtp_server.starttls()
        smtp_server.ehlo()
        smtp_server.login("USERNAME@DOMAIN", password)
        smtp_server.send_message(message)
    except Exception as e:
        print("Error: ", str(e))
    finally:
        if smtp_server is not None:
            smtp_server.quit()
    

    If you want to use Port 465 you have to create an SMTP_SSL object.

    How to check identical array in most efficient way?

    You could compare String representations so:

    array1.toString() == array2.toString()
    array1.toString() !== array3.toString()
    

    but that would also make

    array4 = ['1',2,3,4,5]
    

    equal to array1 if that matters to you

    What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

    Varying is an alias for varchar, so no difference, see documentation :)

    The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

    RegEx to match stuff between parentheses

    If s is your string:

    s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
     .replace(/\)[^(]*$/, "") // trim everything after last parenthesis
     .split(/\)[^(]*\(/);      // split between parenthesis
    

    NSUserDefaults - How to tell if a key exists

    The objectForKey: method will return nil if the value does not exist. Here's a simple IF / THEN test that will tell you if the value is nil:

    if([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"] != nil) {
        ...
    }
    

    Get specific object by id from array of objects in AngularJS

    The simple way to get (one) element from array by id:

    The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

    function isBigEnough(element) {
        return element >= 15;
    }
    
    var integers = [12, 5, 8, 130, 160, 44];
    integers.find(isBigEnough); // 130  only one element - first
    

    you don't need to use filter() and catch first element xx.filter()[0] like in comments above

    The same for objects in array

    var foo = {
    "results" : [{
        "id" : 1,
        "name" : "Test"
    }, {
        "id" : 2,
        "name" : "Beispiel"
    }, {
        "id" : 3,
        "name" : "Sample"
    }
    ]};
    
    var secondElement = foo.results.find(function(item){
        return item.id == 2;
    });
    
    var json = JSON.stringify(secondElement);
    console.log(json);
    

    Of course if you have multiple id then use filter() method to get all objects. Cheers

    _x000D_
    _x000D_
    function isBigEnough(element) {_x000D_
        return element >= 15;_x000D_
    }_x000D_
    _x000D_
    var integers = [12, 5, 8, 130, 160, 44];_x000D_
    integers.find(isBigEnough); // 130  only one element - first
    _x000D_
    _x000D_
    _x000D_

    _x000D_
    _x000D_
    var foo = {_x000D_
    "results" : [{_x000D_
        "id" : 1,_x000D_
        "name" : "Test"_x000D_
    }, {_x000D_
        "id" : 2,_x000D_
        "name" : "Beispiel"_x000D_
    }, {_x000D_
        "id" : 3,_x000D_
        "name" : "Sample"_x000D_
    }_x000D_
    ]};_x000D_
    _x000D_
    var secondElement = foo.results.find(function(item){_x000D_
        return item.id == 2;_x000D_
    });_x000D_
    _x000D_
    var json = JSON.stringify(secondElement);_x000D_
    console.log(json);
    _x000D_
    _x000D_
    _x000D_

    How to see PL/SQL Stored Function body in Oracle

    SELECT text 
    FROM all_source
    where name = 'FGETALGOGROUPKEY'
    order by line
    

    alternatively:

    select dbms_metadata.get_ddl('FUNCTION', 'FGETALGOGROUPKEY')
    from dual;
    

    Create a simple HTTP server with Java?

    A servlet container is definitely the way to go. If Tomcat or Jetty are too heavyweight for you, consider Winstone or TTiny.

    Set margins in a LinearLayout programmatically

    So that works fine, but how on earth do you give the buttons margins so there is space between them?

    You call setMargins() on the LinearLayout.LayoutParams object.

    I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.

    LinearLayout.LayoutParams is a subclass of LinearLayout.MarginLayoutParams, as indicated in the documentation.

    Is this impossible?

    No.

    it wouldn't be the first Android layout task you can only do in XML

    You are welcome to supply proof of this claim.

    Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.

    String formatting: % vs. .format vs. string literal

    Yet another advantage of .format (which I don't see in the answers): it can take object properties.

    In [12]: class A(object):
       ....:     def __init__(self, x, y):
       ....:         self.x = x
       ....:         self.y = y
       ....:         
    
    In [13]: a = A(2,3)
    
    In [14]: 'x is {0.x}, y is {0.y}'.format(a)
    Out[14]: 'x is 2, y is 3'
    

    Or, as a keyword argument:

    In [15]: 'x is {a.x}, y is {a.y}'.format(a=a)
    Out[15]: 'x is 2, y is 3'
    

    This is not possible with % as far as I can tell.

    How do I sort an observable collection?

    I learned a lot from the other solutions, but I found a couple of problems. First, some depend on IndexOf which tends to be pretty slow for large lists. Second, my ObservableCollection had EF entities and using the Remove seemed to corrupt some of the foreign key properties. Maybe I'm doing something wrong.

    Regardless, A Move can be used instead Remove/Insert, but that causes some issues with the performance fix.

    To fix the performance problem, I create a dictionary with the IndexOf sorted values. To keep the dictionary up-to-date and to preserve the entity properties, use a swap implemented with two moves instead of one as implemented in other solutions.

    A single move shifts the indexes of the elements between the locations, which would invalidate the IndexOf dictionary. Adding a second move to implement a swap restores locations.

    public static void Sort<TSource, TKey>(this ObservableCollection<TSource> collection, Func<TSource, TKey> keySelector)
    {
        List<TSource> sorted = collection.OrderBy(keySelector).ToList();
        Dictionary<TSource, int> indexOf = new Dictionary<TSource, int>();
    
        for (int i = 0; i < sorted.Count; i++)
            indexOf[sorted[i]] = i;
    
        int idx = 0;
        while (idx < sorted.Count)
            if (!collection[idx].Equals(sorted[idx])) {
                int newIdx = indexOf[collection[idx]]; // where should current item go?
                collection.Move(newIdx, idx); // move whatever's there to current location
                collection.Move(idx + 1, newIdx); // move current item to proper location
            }
            else {
                idx++;
            }
    }
    

    Remove element from JSON Object

    JSfiddle

    function deleteEmpty(obj){
            for(var k in obj)
             if(k == "children"){
                 if(obj[k]){
                         deleteEmpty(obj[k]);
                 }else{
                       delete obj.children;
                  } 
             }
        }
    
    for(var i=0; i< a.children.length; i++){
     deleteEmpty(a.children[i])
    }
    

    How to downgrade Node version

    If you are on macOS and are not using NVM, the simplest way is to run the installer that comes from node.js web site. It it clever enough to manage substitution of your current installation with the new one, even if it is an older one. At least this worked for me.

    Detect network connection type on Android

    To get a more precise (and user friendly) information about connection type. You can use this code (derived from a @hide method in TelephonyManager.java).

    This method returns a String describing the current connection type.
    i.e. one of : "WIFI" , "2G" , "3G" , "4G" , "5G" , "-" (not connected) or "?" (unknown)

    Remark: This code requires API 25+, but you can easily support older versions by using int instead of const. (See comments in code).

    public static String getNetworkClass(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);      
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null || !info.isConnected())
            return "-"; // not connected
        if (info.getType() == ConnectivityManager.TYPE_WIFI)
            return "WIFI";
        if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            int networkType = info.getSubtype();
            switch (networkType) {
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                case TelephonyManager.NETWORK_TYPE_CDMA:
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                case TelephonyManager.NETWORK_TYPE_IDEN:     // api< 8: replace by 11
                case TelephonyManager.NETWORK_TYPE_GSM:      // api<25: replace by 16
                    return "2G";
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                case TelephonyManager.NETWORK_TYPE_HSPA:
                case TelephonyManager.NETWORK_TYPE_EVDO_B:   // api< 9: replace by 12
                case TelephonyManager.NETWORK_TYPE_EHRPD:    // api<11: replace by 14
                case TelephonyManager.NETWORK_TYPE_HSPAP:    // api<13: replace by 15
                case TelephonyManager.NETWORK_TYPE_TD_SCDMA: // api<25: replace by 17
                    return "3G";
                case TelephonyManager.NETWORK_TYPE_LTE:      // api<11: replace by 13
                case TelephonyManager.NETWORK_TYPE_IWLAN:    // api<25: replace by 18
                case 19: // LTE_CA
                    return "4G";
                case TelephonyManager.NETWORK_TYPE_NR:       // api<29: replace by 20
                    return "5G";
                default:
                    return "?";
             }
        }
        return "?";
    }
    

    TypeError: 'float' object is not subscriptable

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

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

    Instead, you want slicing:

    PriceList[:7] = [PizzaChange]*7
    

    How can I detect when an Android application is running in the emulator?

    All answers in one method

    static boolean checkEmulator()
    {
        try
        {
            String buildDetails = (Build.FINGERPRINT + Build.DEVICE + Build.MODEL + Build.BRAND + Build.PRODUCT + Build.MANUFACTURER + Build.HARDWARE).toLowerCase();
    
            if (buildDetails.contains("generic") 
            ||  buildDetails.contains("unknown") 
            ||  buildDetails.contains("emulator") 
            ||  buildDetails.contains("sdk") 
            ||  buildDetails.contains("genymotion") 
            ||  buildDetails.contains("x86") // this includes vbox86
            ||  buildDetails.contains("goldfish")
            ||  buildDetails.contains("test-keys"))
                return true;
        }   
        catch (Throwable t) {Logger.catchedError(t);}
    
        try
        {
            TelephonyManager    tm  = (TelephonyManager) App.context.getSystemService(Context.TELEPHONY_SERVICE);
            String              non = tm.getNetworkOperatorName().toLowerCase();
            if (non.equals("android"))
                return true;
        }
        catch (Throwable t) {Logger.catchedError(t);}
    
        try
        {
            if (new File ("/init.goldfish.rc").exists())
                return true;
        }
        catch (Throwable t) {Logger.catchedError(t);}
    
        return false;
    }
    

    Capture iOS Simulator video for App Preview

    I'm actually surprised no one provided my answer. This is what you do (this will work if you have at least 1 eligible device):

    1. Record, edit and finish the App Preview with the device you have.
    2. Export as a file.
    3. Go to your Simulators and print screen 1 shot on each the different sizes of iPhone.
    4. Create new App Preview in iMovie.
    5. Insert the screenshot of the desired size FIRST, then add the file of the App Preview you've already made.
    6. Export using Share -> App Preview
    7. Repeat step 4 to 6 for new sizes.

    You should be able to get your App Preview in the desired resolution.

    Remove duplicate rows in MySQL

    if you have a large table with huge number of records then above solutions will not work or take too much time. Then we have a different solution

    -- Create temporary table
    
    CREATE TABLE temp_table LIKE table1;
    
    -- Add constraint
    ALTER TABLE temp_table ADD UNIQUE(title, company,site_id);
    
    -- Copy data
    INSERT IGNORE INTO temp_table SELECT * FROM table1;
    
    -- Rename and drop
    RENAME TABLE table1 TO old_table1, temp_table TO table1;
    DROP TABLE old_table1;
    

    How to delete an app from iTunesConnect / App Store Connect

    You Can Now Delete App.

    On October 4, 2018, Apple released a new update of the appstoreconnect (previously iTunesConnect).

    It's now easier to manage apps you no longer need in App Store Connect by removing them from your main view in My Apps, even if they haven't been submitted for approval. You must have the Legal or Admin role to remove apps.

    From the homepage, click My Apps, then choose the app you want to remove. Scroll to the Additional Information section, then click Remove App. In the dialog that appears, click Remove. You can restore a removed app at any time, as long as the app name is not currently in use by another developer.

    From the homepage, click My Apps. In the upper right-hand corner, click the arrow next to All Statuses. From the drop-down menu, choose Removed Apps. Choose the app you want to restore. Scroll to the Additional Information section, then click Restore App.

    You can show the removed app by clicking on all Statuses on the top right of the screen and then select Removed Apps. Thank you @Daniel for the tips.

    enter image description here

    Please note:

    you can only remove apps if all versions of that app are in one of the following states: Prepare for Submission, Invalid Binary, Developer Rejected, Rejected, Metadata Rejected, Developer, Removed from Sale.

    Android activity life cycle - what are all these methods for?

    I run some logs as per answers above and here is the output:

    Starting Activity

    On Activity Load (First Time)
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onCreate: 
    D/IndividualChatActivity: onStart: 
    D/IndividualChatActivity: onResume: 
    D/IndividualChatActivity: onPostResume: 
    
    Reload After BackPressed
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onCreate: 
    D/IndividualChatActivity: onStart: 
    D/IndividualChatActivity: onResume: 
    D/IndividualChatActivity: onPostResume: 
    
    OnMaximize(Circle Button)
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onRestart: 
    D/IndividualChatActivity: onStart: 
    D/IndividualChatActivity: onResume: 
    D/IndividualChatActivity: onPostResume: 
    
    OnMaximize(Square Button)
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onRestart: 
    D/IndividualChatActivity: onStart: 
    D/IndividualChatActivity: onResume: 
    D/IndividualChatActivity: onPostResume: 
    

    Stopping The Activity

    On BackPressed
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onPause:
    D/IndividualChatActivity: onStop: 
    D/IndividualChatActivity: onDestroy: 
    
    OnMinimize (Circle Button)
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onPause: 
    D/IndividualChatActivity: onStop: 
    
    OnMinimize (Square Button)
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onPause: 
    D/IndividualChatActivity: onStop: 
    
    Going To Another Activity
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onPause:
    D/IndividualChatActivity: onStop: 
    
    Close The App
    ————————————————————————————————————————————————
    D/IndividualChatActivity: onDestroy: 
    

    In my personal opinion only two are required onStart and onStop.

    onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).

    How to turn a string formula into a "real" formula

    Say, let we have column E filled by formulas that returns string, like:

    = " = " & D7
    

    where D7 cell consist more complicated formula, that composes final desired result, say:

    = 3.02 * 1024 * 1024 * 1024
    

    And so in all huge qty of rows that are.

    When rows are a little - it just enough to copy desired cells as values (by RMB)
    to nearest column, say G, and press F2 with following Enter in each of rows.
    However, in case of huge qty of rows it's impossible ...

    So, No VBA. No extra formulas. No F&R

    No mistakes, no typo, but stupid mechanical actions instead only,

    Like on a Ford conveyor. And in just a few seconds only:

    1. [Assume, all of involved columns are in "General" format.]
    2. Open Notepad++
    3. Select entire column D
    4. Ctrl+C
    5. Ctrl+V in NPP
    6. Ctrl+A in NPP
    7. Select cell in the first row of desired column G1
    8. Ctrl+V
    9. Enjoy :) .

    Python: Get HTTP headers from urllib2.urlopen call?

    Actually, it appears that urllib2 can do an HTTP HEAD request.

    The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.

    Here's my take on it:

    import urllib2
    
    # Derive from Request class and override get_method to allow a HEAD request.
    class HeadRequest(urllib2.Request):
        def get_method(self):
            return "HEAD"
    
    myurl = 'http://bit.ly/doFeT'
    request = HeadRequest(myurl)
    
    try:
        response = urllib2.urlopen(request)
        response_headers = response.info()
    
        # This will just display all the dictionary key-value pairs.  Replace this
        # line with something useful.
        response_headers.dict
    
    except urllib2.HTTPError, e:
        # Prints the HTTP Status code of the response but only if there was a 
        # problem.
        print ("Error code: %s" % e.code)
    

    If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.

    This is the HTTP request and response from the code above, as captured by Wireshark:

    HEAD /doFeT HTTP/1.1
    Accept-Encoding: identity
    Host: bit.ly
    Connection: close
    User-Agent: Python-urllib/2.7

    HTTP/1.1 301 Moved
    Server: nginx
    Date: Sun, 19 Feb 2012 13:20:56 GMT
    Content-Type: text/html; charset=utf-8
    Cache-control: private; max-age=90
    Location: http://www.kidsidebyside.org/?p=445
    MIME-Version: 1.0
    Content-Length: 127
    Connection: close
    Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly

    However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.

    The request above involves a redirect. Here is request to the destination, as captured by Wireshark:

    GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
    Accept-Encoding: identity
    Host: www.kidsidebyside.org
    Connection: close
    User-Agent: Python-urllib/2.7

    An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:

    import httplib2
    
    url = "http://bit.ly/doFeT"
    http_interface = httplib2.Http()
    
    try:
        response, content = http_interface.request(url, method="HEAD")
        print ("Response status: %d - %s" % (response.status, response.reason))
    
        # This will just display all the dictionary key-value pairs.  Replace this
        # line with something useful.
        response.__dict__
    
    except httplib2.ServerNotFoundError, e:
        print (e.message)
    

    This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.

    Here's the first request:

    HEAD /doFeT HTTP/1.1
    Host: bit.ly
    accept-encoding: gzip, deflate
    user-agent: Python-httplib2/0.7.2 (gzip)

    Here's the second request, to the destination:

    HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
    Host: www.kidsidebyside.org
    accept-encoding: gzip, deflate
    user-agent: Python-httplib2/0.7.2 (gzip)

    How to prevent text in a table cell from wrapping

    There are at least two ways to do it:

    Use nowrap attribute inside the "td" tag:

    <th nowrap="nowrap">Really long column heading</th>
    

    Use non-breakable spaces between your words:

    <th>Really&nbsp;long&nbsp;column&nbsp;heading</th>
    

    Difference between .keystore file and .jks file

    You are confused on this.

    A keystore is a container of certificates, private keys etc.

    There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

    JKS is Java's keystore implementation. There is also BKS etc.

    These are all keystore types.

    So to answer your question:

    difference between .keystore files and .jks files

    There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

    Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

    ContextLoaderListener has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml

    You can customize this by using

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
    </context-param>
    

    on web.xml, or remove this listener if you don't need one.

    Add item to Listview control

    Simple one, just do like this..

    ListViewItem lvi = new ListViewItem(pet.Name);
        lvi.SubItems.Add(pet.Type);
        lvi.SubItems.Add(pet.Age);
        listView.Items.Add(lvi);
    

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

    There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.

    Confused about UPDLOCK, HOLDLOCK

    Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

    As for the HOLDLOCK hint the documentation states:

    HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

    ...

    SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

    and the Transaction Isolation Level topic explains what SERIALIZABLE means:

    No other transactions can modify data that has been read by the current transaction until the current transaction completes.

    Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

    Therefore the behavior you see is perfectly explained by the product documentation:

    • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
    • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
    • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
      SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
    • TABLOCKX no need for explanations

    The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

    After OP edit:

    I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

    The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

    How to convert empty spaces into null values, using SQL Server?

    I solved a similar problem using NULLIF function:

    UPDATE table 
    SET col1 = NULLIF(col1, '')
    

    From the T-SQL reference:

    NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.

    What's the difference between nohup and ampersand

    myprocess.out & would run the process in background using a subshell. If the current shell is terminated (say by logout), all subshells are also terminated so the background process would also be terminated. The nohup command ignores the HUP signal and thus even if the current shell is terminated, the subshell and myprocess.out would continue to run in the background. Another difference is that & alone doesn't redirect the stdout/stderr so if there are any output or error, those are displayed on the terminal. nohup on the other hand redirect the stdout/stderr to nohup.out or $HOME/nohup.out.

    CSS content generation before or after 'input' elements

    This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

    input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

    In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

    Note that this is even referred to in the spec:

    This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

    And more explicitly:

    Replaced elements do not have ::before and ::after pseudo-elements

    How to find the files that are created in the last hour in unix

    sudo find / -Bmin 60
    

    From the man page:

    -Bmin n

    True if the difference between the time of a file's inode creation and the time find was started, rounded up to the next full minute, is n minutes.

    Obviously, you may want to set up a bit differently, but this primary seems the best solution for searching for any file created in the last N minutes.

    How to open maximized window with Javascript?

     window.open('your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')
    

    aspx page to redirect to a new page

    <%@ Page Language="C#" %>
    <script runat="server">
      protected override void OnLoad(EventArgs e)
      {
          Response.Redirect("new.aspx");
      }
    </script>
    

    Phone Number Validation MVC

    To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.

    Usage

    @Html.DisplayForPhone(item.Phone)
    

    HtmlHelper Extension

    public static class HtmlHelperExtensions
    {
        public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
        {
            if (phone == null)
            {
                return new HtmlString(string.Empty);
            }
            string formatted = phone;
            if (phone.Length == 10)
            {
                formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
            }
            else if (phone.Length == 7)
            {
                formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
            }
            string s = $"<a href='tel:{phone}'>{formatted}</a>";
            return new HtmlString(s);
        }
    }
    

    How to find elements by class

    This should work:

    soup = BeautifulSoup(sdata)
    mydivs = soup.findAll('div')
    for div in mydivs: 
        if (div.find(class_ == "stylelistrow"):
            print div
    

    Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

    Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.

    Leave off the parenthesis when including the directive in your html:

    <my-directive callback="someFunction" />
    

    Then "unwrap" the function in your directive's link or controller. here is an example:

    app.directive("myDirective", function() {
    
        return {
            restrict: "E",
            scope: {
                callback: "&"                              
            },
            template: "<div ng-click='callback(data)'></div>", // call function this way...
            link: function(scope, element, attrs) {
                // unwrap the function
                scope.callback = scope.callback(); 
    
                scope.data = "data from somewhere";
    
                element.bind("click",function() {
                    scope.$apply(function() {
                        callback(data);                        // ...or this way
                    });
                });
            }
        }
    }]);    
    

    The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:

    <outer-directive callback="someFunction" >
        <middle-directive callback="callback" >
            <inner-directive callback="callback" />
        </middle-directive>
    </outer-directive>
    

    Then you would end up with something like this in your inner-directive:

    callback()()()(data); 
    

    Which would fail in other nesting scenarios.

    I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters

    I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.

    How to get the full url in Express?

    Using url.format:

    var url = require('url');
    

    This support all protocols and include port number. If you don't have a query string in your originalUrl you can use this cleaner solution:

    var requrl = url.format({
        protocol: req.protocol,
        host: req.get('host'),
        pathname: req.originalUrl,
    });
    

    If you have a query string:

    var urlobj = url.parse(req.originalUrl);
    urlobj.protocol = req.protocol;
    urlobj.host = req.get('host');
    var requrl = url.format(urlobj);
    

    Remove all line breaks from a long string of text

    You can try using string replace:

    string = string.replace('\r', '').replace('\n', '')
    

    What encoding/code page is cmd.exe using?

    Yes, it’s frustrating—sometimes type and other programs print gibberish, and sometimes they do not.

    First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.

    But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.

    When programs use standard C-library I/O functions like printf, the program’s output encoding must match the console’s output encoding, or you will get gibberish. chcp shows and sets the current codepage. All output using standard C-library I/O functions is treated as if it is in the codepage displayed by chcp.

    Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:

    • A program can get the console’s current codepage using chcp or GetConsoleOutputCP, and configure itself to output in that encoding, or

    • You or a program can set the console’s current codepage using chcp or SetConsoleOutputCP to match the default output encoding of the program.

    However, programs that use Win32 APIs can write UTF-16LE strings directly to the console with WriteConsoleW. This is the only way to get correct output without setting codepages. And even when using that function, if a string is not in the UTF-16LE encoding to begin with, a Win32 program must pass the correct codepage to MultiByteToWideChar. Also, WriteConsoleW will not work if the program’s output is redirected; more fiddling is needed in that case.

    type works some of the time because it checks the start of each file for a UTF-16LE Byte Order Mark (BOM), i.e. the bytes 0xFF 0xFE. If it finds such a mark, it displays the Unicode characters in the file using WriteConsoleW regardless of the current codepage. But when typeing any file without a UTF-16LE BOM, or for using non-ASCII characters with any command that doesn’t call WriteConsoleW—you will need to set the console codepage and program output encoding to match each other.


    How can we find this out?

    Here’s a test file containing Unicode characters:

    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    

    Here’s a Java program to print out the test file in a bunch of different Unicode encodings. It could be in any programming language; it only prints ASCII characters or encoded bytes to stdout.

    import java.io.*;
    
    public class Foo {
    
        private static final String BOM = "\ufeff";
        private static final String TEST_STRING
            = "ASCII     abcde xyz\n"
            + "German    äöü ÄÖÜ ß\n"
            + "Polish    aezznl\n"
            + "Russian   ??????? ???\n"
            + "CJK       ??\n";
    
        public static void main(String[] args)
            throws Exception
        {
            String[] encodings = new String[] {
                "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };
    
            for (String encoding: encodings) {
                System.out.println("== " + encoding);
    
                for (boolean writeBom: new Boolean[] {false, true}) {
                    System.out.println(writeBom ? "= bom" : "= no bom");
    
                    String output = (writeBom ? BOM : "") + TEST_STRING;
                    byte[] bytes = output.getBytes(encoding);
                    System.out.write(bytes);
                    FileOutputStream out = new FileOutputStream("uc-test-"
                        + encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
                    out.write(bytes);
                    out.close();
                }
            }
        }
    }
    

    The output in the default codepage? Total garbage!

    Z:\andrew\projects\sx\1259084>chcp
    Active code page: 850
    
    Z:\andrew\projects\sx\1259084>java Foo
    == UTF-8
    = no bom
    ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    = bom
    ´++ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    == UTF-16LE
    = no bom
    A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
     = bom
     ¦A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
     == UTF-16BE
    = no bom
     A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    = bom
    ¦  A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    == UTF-32LE
    = no bom
    A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
       = bom
     ¦  A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
       == UTF-32BE
    = no bom
       A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    = bom
      ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    

    However, what if we type the files that got saved? They contain the exact same bytes that were printed to the console.

    Z:\andrew\projects\sx\1259084>type *.txt
    
    uc-test-UTF-16BE-bom.txt
    
    
    ¦  A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    
    uc-test-UTF-16BE-nobom.txt
    
    
     A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h        ?????z?|?D?B
     R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
     C J K              O`Y}
    
    uc-test-UTF-16LE-bom.txt
    
    
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    
    uc-test-UTF-16LE-nobom.txt
    
    
    A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
    
    uc-test-UTF-32BE-bom.txt
    
    
      ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z
    
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    
    uc-test-UTF-32BE-nobom.txt
    
    
       A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
       R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
      ?O
       C   J   K                              O`  Y}
    
    uc-test-UTF-32LE-bom.txt
    
    
     A S C I I           a b c d e   x y z
     G e r m a n         ä ö ü   Ä Ö Ü   ß
     P o l i s h         a e z z n l
     R u s s i a n       ? ? ? ? ? ? ?   ? ? ?
     C J K               ? ?
    
    uc-test-UTF-32LE-nobom.txt
    
    
    A   S   C   I   I                       a   b   c   d   e       x   y   z
       G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
       P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
       R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
    ?  O?
       C   J   K                               `O  }Y
    
    uc-test-UTF-8-bom.txt
    
    
    ´++ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    
    uc-test-UTF-8-nobom.txt
    
    
    ASCII     abcde xyz
    German    +ñ+Â++ +ä+û+£ +ƒ
    Polish    -à-Ö+¦+++ä+é
    Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
    CJK       õ¢áÕÑ¢
    

    The only thing that works is UTF-16LE file, with a BOM, printed to the console via type.

    If we use anything other than type to print the file, we get garbage:

    Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
     ¦A S C I I           a b c d e   x y z
     G e r m a n         õ ÷ ³   - Í _   ¯
     P o l i s h         ????z?|?D?B?
     R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
     C J K               `O}Y
             1 file(s) copied.
    

    From the fact that copy CON does not display Unicode correctly, we can conclude that the type command has logic to detect a UTF-16LE BOM at the start of the file, and use special Windows APIs to print it.

    We can see this by opening cmd.exe in a debugger when it goes to type out a file:

    enter image description here

    After type opens a file, it checks for a BOM of 0xFEFF—i.e., the bytes 0xFF 0xFE in little-endian—and if there is such a BOM, type sets an internal fOutputUnicode flag. This flag is checked later to decide whether to call WriteConsoleW.

    But that’s the only way to get type to output Unicode, and only for files that have BOMs and are in UTF-16LE. For all other files, and for programs that don’t have special code to handle console output, your files will be interpreted according to the current codepage, and will likely show up as gibberish.

    You can emulate how type outputs Unicode to the console in your own programs like so:

    #include <stdio.h>
    #define UNICODE
    #include <windows.h>
    
    static LPCSTR lpcsTest =
        "ASCII     abcde xyz\n"
        "German    äöü ÄÖÜ ß\n"
        "Polish    aezznl\n"
        "Russian   ??????? ???\n"
        "CJK       ??\n";
    
    int main() {
        int n;
        wchar_t buf[1024];
    
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    
        n = MultiByteToWideChar(CP_UTF8, 0,
                lpcsTest, strlen(lpcsTest),
                buf, sizeof(buf));
    
        WriteConsole(hConsole, buf, n, &n, NULL);
    
        return 0;
    }
    

    This program works for printing Unicode on the Windows console using the default codepage.


    For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:

    Z:\andrew\projects\sx\1259084>chcp 65001
    Active code page: 65001
    
    Z:\andrew\projects\sx\1259084>java Foo
    == UTF-8
    = no bom
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    ? ???
    CJK       ??
     ??
    ?
    ?
    = bom
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    ?? ???
    CJK       ??
      ??
    ?
    ?
    == UTF-16LE
    = no bom
    A S C I I           a b c d e   x y z
    …
    

    However, a C program that sets a Unicode UTF-8 codepage:

    #include <stdio.h>
    #include <windows.h>
    
    int main() {
        int c, n;
        UINT oldCodePage;
        char buf[1024];
    
        oldCodePage = GetConsoleOutputCP();
        if (!SetConsoleOutputCP(65001)) {
            printf("error\n");
        }
    
        freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
        n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
        fwrite(buf, sizeof(buf[0]), n, stdout);
    
        SetConsoleOutputCP(oldCodePage);
    
        return 0;
    }
    

    does have correct output:

    Z:\andrew\projects\sx\1259084>.\test
    ASCII     abcde xyz
    German    äöü ÄÖÜ ß
    Polish    aezznl
    Russian   ??????? ???
    CJK       ??
    

    The moral of the story?

    • type can print UTF-16LE files with a BOM regardless of your current codepage
    • Win32 programs can be programmed to output Unicode to the console, using WriteConsoleW.
    • Other programs which set the codepage and adjust their output encoding accordingly can print Unicode on the console regardless of what the codepage was when the program started
    • For everything else you will have to mess around with chcp, and will probably still get weird output.

    How to configure PostgreSQL to accept all incoming connections

    Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data file and put something like

    host all all 172.0.0.0/8 trust

    It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm

    How do I open port 22 in OS X 10.6.7

    I think your port is probably open, but you don't have anything that listens on it.

    The Apple Mac OS X operating system has SSH installed by default but the SSH daemon is not enabled. This means you can’t login remotely or do remote copies until you enable it.

    To enable it, go to ‘System Preferences’. Under ‘Internet & Networking’ there is a ‘Sharing’ icon. Run that. In the list that appears, check the ‘Remote Login’ option. In OS X Yosemite and up, there is no longer an 'Internet & Networking' menu; it was moved to Accounts. The Sharing menu now has its own icon on the main System Preferences menu. (thx @AstroCB)

    This starts the SSH daemon immediately and you can remotely login using your username. The ‘Sharing’ window shows at the bottom the name and IP address to use. You can also find this out using ‘whoami’ and ‘ifconfig’ from the Terminal application.

    These instructions are copied from Enable SSH in Mac OS X, but I wanted to make sure they won't go away and to provide quick access.

    Setting a property by reflection with a string value

    You can use Convert.ChangeType() - It allows you to use runtime information on any IConvertible type to change representation formats. Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not IConvertible.

    The corresponding code (without exception handling or special case logic) would be:

    Ship ship = new Ship();
    string value = "5.5";
    PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
    propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
    

    window.onload vs <body onload=""/>

    If you're trying to write unobtrusive JS code (and you should be), then you shouldn't use <body onload="">.

    It is my understanding that different browsers handle these two slightly differently but they operate similarly. In most browsers, if you define both, one will be ignored.

    How to check the maximum number of allowed connections to an Oracle database?

    I thought this would work, based on this source.

    SELECT
      'Currently, ' 
      || (SELECT COUNT(*) FROM V$SESSION)
      || ' out of ' 
      || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX) 
      || ' connections are used.' AS USAGE_MESSAGE
    FROM 
      V$LICENSE VL
    

    However, Justin Cave is right. This query gives better results:

    SELECT
      'Currently, ' 
      || (SELECT COUNT(*) FROM V$SESSION)
      || ' out of ' 
      || VP.VALUE 
      || ' connections are used.' AS USAGE_MESSAGE
    FROM 
      V$PARAMETER VP
    WHERE VP.NAME = 'sessions'
    

    format statement in a string resource file

    Quote from Android Docs:

    If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

    <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
    

    In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

    Resources res = getResources();
    String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
    

    Curl setting Content-Type incorrectly

    I think you want to specify

    -H "Content-Type:text/xml"
    

    with a colon, not an equals.

    How do I pass data between Activities in Android application?

    Source class:

    Intent myIntent = new Intent(this, NewActivity.class);
    myIntent.putExtra("firstName", "Your First Name Here");
    myIntent.putExtra("lastName", "Your Last Name Here");
    startActivity(myIntent)
    

    Destination Class (NewActivity class):

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);
    
        Intent intent = getIntent();
    
        String fName = intent.getStringExtra("firstName");
        String lName = intent.getStringExtra("lastName");
    }
    

    Regex not operator

    You could capture the (2001) part and replace the rest with nothing.

    public static string extractYearString(string input) {
        return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
    }
    
    var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
    var result = extractYearString(subject);
    System.out.println(result); // <-- "2001"
    

    .*\(([0-9]{4})\).* means

    • .* match anything
    • \( match a ( character
    • ( begin capture
    • [0-9]{4} any single digit four times
    • ) end capture
    • \) match a ) character
    • .* anything (rest of string)

    Insert into a MySQL table or update if exists

    Try this:

    INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'

    Note:
    Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.

    force line break in html table cell

    I suggest you use a wrapper div or paragraph:

    <td><p style="width:50%;">Text only allowed to extend 50% of the cell.</p></td>
    

    And you can make a class out of it:

    <td class="linebreak"><p>Text only allowed to extend 50% of the cell.</p></td>
    
    td.linebreak p {
        width: 50%;
    }
    

    All of this assuming that you meant 50% as in 50% of the cell.

    SSLHandshakeException: No subject alternative names present

    Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

    When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

    When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

    You'll find more details about the specification and how to generate such a certificate in this answer.

    Generate random numbers following a normal distribution in C/C++

    Monte Carlo method The most intuitive way to do this would be to use a monte carlo method. Take a suitable range -X, +X. Larger values of X will result in a more accurate normal distribution, but takes longer to converge. a. Choose a random number z between -X to X. b. Keep with a probability of N(z, mean, variance) where N is the gaussian distribution. Drop otherwise and go back to step (a).

    Optional Parameters in Web Api Attribute Routing

    For an incoming request like /v1/location/1234, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid and not to deviceid.

    I think you should change your route template to be like [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")] and then parse the deiveOrAppid to figure out the type of id.

    Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ? character in this case. For example: [Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]

    Insert json file into mongodb

    In MongoDB To insert Json array data from file(from particular location from a system / pc) using mongo shell command. While executing below command, command should be in single line.

    var file = cat('I:/data/db/card_type_authorization.json'); var o = JSON.parse(file); db.CARD_TYPE_AUTHORIZATION.insert(o);

    JSON File: card_type_authorization.json

    [{
    "code": "visa",
    "position": 1,
    "description": "Visa",
    "isVertualCard": false,
    "comments": ""
    },{
        "code": "mastercard",
        "position": 2,
        "description": "Mastercard",
        "isVertualCard": false,
        "comments": ""
    }]
    

    how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

    You could use prop as well. Check the following code below.

    $(document).ready(function(){
    
       $('.staff_on_site').click(function(){
    
         var rBtnVal = $(this).val();
    
         if(rBtnVal == "yes"){
             $("#no_of_staff").prop("readonly", false); 
         }
         else{ 
             $("#no_of_staff").prop("readonly", true); 
         }
       });
    });
    

    Regex remove all special characters except numbers?

    If you don't mind including the underscore as an allowed character, you could try simply:

    result = subject.replace(/\W+/g, "");
    

    If the underscore must be excluded also, then

    result = subject.replace(/[^A-Z0-9]+/ig, "");
    

    (Note the case insensitive flag)

    How to convert a Datetime string to a current culture datetime string

    var culture = new CultureInfo( "en-GB" );
    var dateValue = new DateTime( 2011, 12, 1 );
    var result = dateValue.ToString( "d", culture ) );
    

    How to git clone a specific tag

    git clone --depth 1 --branch <tag_name> <repo_url>
    

    --depth 1 is optional but if you only need the state at that one revision, you probably want to skip downloading all the history up to that revision.

    How to assign the output of a Bash command to a variable?

    Here's your script...

    DIR=$(pwd)
    echo $DIR
    while [ "$DIR" != "/" ]; do
        cd ..
        DIR=$(pwd)
        echo $DIR
    done
    

    Note the spaces, use of quotes, and $ signs.

    ng if with angular for string contains

    All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives

    <li ng-repeat="select in Items">   
             <foo ng-repeat="newin select.values">
    <span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
    </li>
    //where x is your character to be found
    

    Convert a string date into datetime in Oracle

    Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

    My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

    How to set MimeBodyPart ContentType to "text/html"?

    What about using:

    mime_body_part.setHeader("Content-Type", "text/html");
    

    In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.

    What is Turing Complete?

    From wikipedia:

    Turing completeness, named after Alan Turing, is significant in that every plausible design for a computing device so far advanced can be emulated by a universal Turing machine — an observation that has become known as the Church-Turing thesis. Thus, a machine that can act as a universal Turing machine can, in principle, perform any calculation that any other programmable computer is capable of. However, this has nothing to do with the effort required to write a program for the machine, the time it may take for the machine to perform the calculation, or any abilities the machine may possess that are unrelated to computation.

    While truly Turing-complete machines are very likely physically impossible, as they require unlimited storage, Turing completeness is often loosely attributed to physical machines or programming languages that would be universal if they had unlimited storage. All modern computers are Turing-complete in this sense.

    I don't know how you can be more non-technical than that except by saying "turing complete means 'able to answer computable problem given enough time and space'".

    Replace non-ASCII characters with a single space

    What about this one?

    def replace_trash(unicode_string):
         for i in range(0, len(unicode_string)):
             try:
                 unicode_string[i].encode("ascii")
             except:
                  #means it's non-ASCII
                  unicode_string=unicode_string[i].replace(" ") #replacing it with a single space
         return unicode_string
    

    Stateless vs Stateful

    We make Webapps statefull by overriding HTTP stateless behaviour by using session objects.When we use session objets state is carried but we still use HTTP only.

    Get Number of Rows returned by ResultSet in Java

    You can use res.previous() as follows:

    ResulerSet res = getDate();
    if(!res.next()) {
        System.out.println("No Data Found.");
    } else {
        res.previous();
        while(res.next()) {
          //code to display the data in the table.
        }
    }
    

    Groovy: How to check if a string contains any element of an array?

    def valid = pointAddress.findAll { a ->
        validPointTypes.any { a.contains(it) }
    }
    

    Should do it

    How can I get Android Wifi Scan Results into a list?

    Try this code

    public class WiFiDemo extends Activity implements OnClickListener
     {      
        WifiManager wifi;       
        ListView lv;
        TextView textStatus;
        Button buttonScan;
        int size = 0;
        List<ScanResult> results;
    
        String ITEM_KEY = "key";
        ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
        SimpleAdapter adapter;
    
        /* Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            textStatus = (TextView) findViewById(R.id.textStatus);
            buttonScan = (Button) findViewById(R.id.buttonScan);
            buttonScan.setOnClickListener(this);
            lv = (ListView)findViewById(R.id.list);
    
            wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifi.isWifiEnabled() == false)
            {
                Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
                wifi.setWifiEnabled(true);
            }   
            this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
            lv.setAdapter(this.adapter);
    
            registerReceiver(new BroadcastReceiver()
            {
                @Override
                public void onReceive(Context c, Intent intent) 
                {
                   results = wifi.getScanResults();
                   size = results.size();
                }
            }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                    
        }
    
        public void onClick(View view) 
        {
            arraylist.clear();          
            wifi.startScan();
    
            Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
            try 
            {
                size = size - 1;
                while (size >= 0) 
                {   
                    HashMap<String, String> item = new HashMap<String, String>();                       
                    item.put(ITEM_KEY, results.get(size).SSID + "  " + results.get(size).capabilities);
    
                    arraylist.add(item);
                    size--;
                    adapter.notifyDataSetChanged();                 
                } 
            }
            catch (Exception e)
            { }         
        }    
    }
    

    WiFiDemo.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="16dp"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">
    
            <TextView
                android:id="@+id/textStatus"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Status" />
    
            <Button
                android:id="@+id/buttonScan"
                android:layout_width="wrap_content"
                android:layout_height="40dp"
                android:text="Scan" />
        </LinearLayout>
    
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"></ListView>
    </LinearLayout>
    

    For ListView- row.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="8dp">
    
        <TextView
            android:id="@+id/list_value"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14dp" />
    </LinearLayout>
    

    Add these permission in AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

    I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid on the parent, grid-area: 1/1/1/1; on the children, and justify-self for positioning of those children.

    _x000D_
    _x000D_
    <div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
      <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
      <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
      <div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Make Div Draggable using CSS

    $('#dialog').draggable({ handle: "#tblOverlay" , scroll: false });
    
        // Pop up Window 
              <div id="dialog">
                            <table  id="tblOverlay">
                                <tr><td></td></tr>
                             <table>
               </div>
    

    Options:

    1. handle : Avoids the sticky scroll bar issue. Sometimes your mouse pointer will stick to the popup window while dragging.
    2. scroll : Prevent popup window to go beyond parent page or out of current screen.

    How to use pull to refresh in Swift?

    Swift 4

    var refreshControl: UIRefreshControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
        tableView.addSubview(refreshControl) 
    }
    
    @objc func refresh(_ sender: Any) {
        //  your code to reload tableView
    }
    

    And you could stop refreshing with:

    refreshControl.endRefreshing()
    

    makefile execute another target

    If you removed the make all line from your "fresh" target:

    fresh :
        rm -f *.o $(EXEC)
        clear
    

    You could simply run the command make fresh all, which will execute as make fresh; make all.

    Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

    curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

    * Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                             ^^^^^
    

    The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

    How to filter Android logcat by application?

    On the left in the logcat view you have the "Saved Filters" windows. Here you can add a new logcat filter by Application Name (for example, com.your.package)

    Need to make a clickable <div> button

    Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

    Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

    HTML:

    <a id="music" href="Music.html">Music I Like</a>
    

    CSS:

    #music {
        background-color: black;
        color: white;
        display: block;
        height: 40px;
        line-height: 40px;
        text-decoration: none;
        width: 100px;
        text-align: center;
    }
    

    Output:

    enter image description here

    fatal error: iostream.h no such file or directory

    You should be using iostream without the .h.

    Early implementations used the .h variants but the standard mandates the more modern style.

    Array definition in XML?

    In XML values in text() nodes.

    If we write this

    <numbers>1,2,3</numbers>
    

    in element "numbers" will be one text() node with value "1,2,3".

    Native way to get many text() nodes in element is insert nodes of other types in text.

    Other available types is element or comment() node.

    Split with element node:

    <numbers>3<_/>2<_/>1</numbers>
    

    Split with comment() node:

    <numbers>3<!---->2<!---->1</numbers>
    

    We can select this values by this XPath

    //numbers/text()
    

    Select value by index

    //numbers/text()[3]
    

    Will return text() node with value "1"

    How to Exit a Method without Exiting the Program?

    The basic problem here is that you are mistaking System.Environment.Exit for return.

    Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

    I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

    If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

    I would recommend (as far as possible, and depending on the exact size of the figures):

    • Place the figures with [t] (or [h] if you must)
    • Place the figures as near as possible to the "right" place (differs for [t] and [h])
    • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

    In my experience, this is a big eater-up of non-available time (:-)


    In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

    Setting Spring Profile variable

    For Tomcat 8:

    Linux :

    Create setenv.sh and update it with following:

    export SPRING_PROFILES_ACTIVE=dev

    Windows:

    Create setenv.bat and update it with following:

    set SPRING_PROFILES_ACTIVE=dev

    How to install the JDK on Ubuntu Linux

    1. Install the appropriate version of OpenJDK

      JAVA_VERSION=8 sudo add-apt-repository -y ppa:openjdk-r/ppa sudo apt-get update sudo apt-get -qq install -y openjdk-$JAVA_VERSION-jdk

    2. Set Environment Variables in /etc/profile.d/jdk.sh

      JAVA_HOME=/usr/lib/jvm/java-$JAVA_VERSION-openjdk-amd64 echo "export JAVA_HOME=$JAVA_HOME" | sudo tee -a /etc/profile.d/jdk.sh echo "export J2SDKDIR=$JAVA_HOME" | sudo tee -a /etc/profile.d/jdk.sh echo "export J2REDIR=$JAVA_HOME/jre" | sudo tee -a /etc/profile.d/jdk.sh echo "export PATH=$PATH:$JAVA_HOME/bin:$J2REDIR/bin" | sudo tee -a /etc/profile.d/jdk.sh

    3. Check your installation

      /bin/bash /etc/profile.d/jdk.sh java -version echo $JAVA_HOME echo $J2REDIR echo $PATH

    What is the Git equivalent for revision number?

    We're using this command to get version and revision from git:

    git describe --always --tags --dirty
    

    It returns

    • commit hash as revision when no tagging is used (e.g. gcc7b71f)
    • tag name as version when on a tag (e.g. v2.1.0, used for releases)
    • tag name, revision number since last tag and commit hash when after a tag (e.g. v5.3.0-88-gcc7b71f)
    • same as above plus a "dirty" tag if the working tree has local modifications (e.g. v5.3.0-88-gcc7b71f-dirty)

    See also: https://www.git-scm.com/docs/git-describe#Documentation/git-describe.txt

    App.Config file in console application C#

    use this

    System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")
    

    How to search multiple columns in MySQL?

    1)

    select *
    from employee em
    where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';
    

    2)

    select *
    from employee em
    where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';
    

    First is usefull when we have data like : 'firstname lastname'.

    e.g

    • parth patel
    • parth p
    • patel parth

    Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.

    e.g

    • parth-patel
    • parth_p
    • patel#parth

    How do I get DOUBLE_MAX?

    Its in the standard float.h include file. You want DBL_MAX

    Select All checkboxes using jQuery

    $(document).ready(function () {
        $(".class").on('click', function () {
            $(".checkbox).prop('checked', true);
        });
    });
    

    Pandas every nth row

    There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

    df = pd.DataFrame('x', index=range(5), columns=list('abc'))
    df
    
       a  b  c
    0  x  x  x
    1  x  x  x
    2  x  x  x
    3  x  x  x
    4  x  x  x
    

    For example, to get every 2 rows, you can do

    df[::2]
    
       a  b  c
    0  x  x  x
    2  x  x  x
    4  x  x  x
    

    There's also GroupBy.first/GroupBy.head, you group on the index:

    df.index // 2
    # Int64Index([0, 0, 1, 1, 2], dtype='int64')
    
    df.groupby(df.index // 2).first()
    # Alternatively,
    # df.groupby(df.index // 2).head(1)
    
       a  b  c
    0  x  x  x
    1  x  x  x
    2  x  x  x
    

    The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

    # df.groupby(np.arange(len(df)) // 2).first()
    df.groupby(pd.RangeIndex(len(df)) // 2).first()
    
       a  b  c
    0  x  x  x
    1  x  x  x
    2  x  x  x
    

    How do I set the path to a DLL file in Visual Studio?

    The search path that the loader uses when you call LoadLibrary() can be altered by using the SetDllDirectory() function. So you could just call this and add the path to your dependency before you load it.

    See also DLL Search Order.

    Python recursive folder read

    This worked for me:

    import glob
    
    root_dir = "C:\\Users\\Scott\\" # Don't forget trailing (last) slashes    
    for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
         print(filename)
         # do stuff
    

    Best practices for SQL varchar column length

    I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.

    Full screen background image in an activity

    If you have bg.png as your background image then simply:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg"
        tools:context=".MainActivity" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/hello_world"/>
    </RelativeLayout>
    

    Find the unique values in a column and then sort them

    I prefer the oneliner:

    print(sorted(df['Column Name'].unique()))
    

    How to convert <font size="10"> to px?

    <font size=1>- font size 1</font><br>
    <span style="font-size:0.63em">- font size: 0.63em</span><br>
    
    <font size=2>- font size 2</font><br>
    <span style="font-size: 0.82em">- font size: 0.82em</span><br>
    
    <font size=3>- font size 3</font><br>
    <span style="font-size: 1.0em">- font size: 1.0em</span><br>
    
    <font size=4>- font size 4</font><br>
    <span style="font-size: 1.13em">- font size: 1.13em</span><br>
    
    <font size=5>- font size 5</font><br>
    <span style="font-size: 1.5em">- font size: 1.5em</span><br>
    
    <font size=6>- font size 6</font><br>
    <span style="font-size: 2em">- font size: 2em</span><br>
    
    <font size=7>- font size 7</font><br>
    <span style="font-size: 3em">- font size: 3em</span><br>
    

    Format a Go string without printing?

    fmt.SprintF function returns a string and you can format the string the very same way you would have with fmt.PrintF

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

    Try new_list = a[0:2] + [a[4]] + a[6:].

    Or more generally, something like this:

    from itertools import chain
    new_list = list(chain(a[0:2], [a[4]], a[6:]))
    

    This works with other sequences as well, and is likely to be faster.

    Or you could do this:

    def chain_elements_or_slices(*elements_or_slices):
        new_list = []
        for i in elements_or_slices:
            if isinstance(i, list):
                new_list.extend(i)
            else:
                new_list.append(i)
        return new_list
    
    new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])
    

    But beware, this would lead to problems if some of the elements in your list were themselves lists. To solve this, either use one of the previous solutions, or replace a[4] with a[4:5] (or more generally a[n] with a[n:n+1]).

    How can I change the user on Git Bash?

    For any OS

    This helped me so I'll put it here, just in case. Once you are done with adding the rsa keys for both the accounts, add a config file in your .ssh directory for both the accounts (.ssh/config)

    # First account
    Host github.com-<FIRST_ACCOUNT_USERNAME_HERE>
       HostName github.com
       User git
       IdentityFile ~/.ssh/id_rsa_user1
       
    # Second account
    Host github.com-<SECOND_ACCOUNT_USERNAME_HERE>   
       HostName github.com
       User git
       IdentityFile ~/.ssh/id_rsa_user2
    

    Make sure you use the correct usernames and RSA files. Next, you can open the terminal/git bash on the repository root and check which account you would be pushing from

    git config user.email
    

    Suppose this returns the first user email and you want to push from the second user. Change the local user.name and user.email :

    git config user.name "SECOND_USER"
    git config user.email "[email protected]"
    

    (This won't change the global config and you can have the first user set up as the global user). Once done, you can confirm with git config user.email and it should return the email of the second user. You're all set to push to GitHub with the second user. The rest is all the same old git add , git commit and git push. To push from the first user, change the local user.name again and follow the same steps. Hope it helps :)


    If the above steps are still not working for you, check to see if you have uploaded the RSA keys within GitHub portal. Refer to GitHub documentation:

    Then, clear your ssh cached keys Reference

    ssh-add -D
    

    Then add you 2 ssh keys

    ssh-add ~/.ssh/id_rsa_user1
    ssh-add ~/.ssh/id_rsa_user2
    

    Then type in your terminal:

    ssh -T [email protected]<SECOND_ACCOUNT_USERNAME_HERE>
    

    You should see the following output:

    Hi <SECOND_USERNAME>! You've successfully authenticated, but GitHub does not provide shell access.
    

    Then, assign the correct remote to your local repository. Make sure you put the same username as the one you gave in your .ssh/config file next to Host. In the following case [email protected]<SECOND_ACCOUNT_USERNAME_HERE>.

    git remote rm origin
    git remote add origin [email protected]<SECOND_ACCOUNT_USERNAME_HERE>:/your_username/your_repository.git
    

    How to use comparison operators like >, =, < on BigDecimal

    This thread has plenty of answers stating that the BigDecimal.compareTo(BigDecimal) method is the one to use to compare BigDecimal instances. I just wanted to add for anymore not experienced with using the BigDecimal.compareTo(BigDecimal) method to be careful with how you are creating your BigDecimal instances. So, for example...

    • new BigDecimal(0.8) will create a BigDecimal instance with a value which is not exactly 0.8 and which has a scale of 50+,
    • new BigDecimal("0.8") will create a BigDecimal instance with a value which is exactly 0.8 and which has a scale of 1

    ... and the two will be deemed to be unequal according to the BigDecimal.compareTo(BigDecimal) method because their values are unequal when the scale is not limited to a few decimal places.

    First of all, be careful to create your BigDecimal instances with the BigDecimal(String val) constructor or the BigDecimal.valueOf(double val) method rather than the BigDecimal(double val) constructor. Secondly, note that you can limit the scale of BigDecimal instances prior to comparing them by means of the BigDecimal.setScale(int newScale, RoundingMode roundingMode) method.

    Setting Inheritance and Propagation flags with set-acl and powershell

    Here's the MSDN page describing the flags and what is the result of their various combinations.

    Flag combinations => Propagation results
    =========================================
    No Flags => Target folder.
    ObjectInherit => Target folder, child object (file), grandchild object (file).
    ObjectInherit and NoPropagateInherit => Target folder, child object (file).
    ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
    ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
    ContainerInherit => Target folder, child folder, grandchild folder.
    ContainerInherit, and NoPropagateInherit => Target folder, child folder.
    ContainerInherit, and InheritOnly => Child folder, grandchild folder.
    ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
    ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
    ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
    ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
    ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).
    

    To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
    PropagationFlags.None
    

    So the specific code change you need to make for your example is:

    $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
    

    escaping question mark in regex javascript

    Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

    var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                                   ^^                            ^^
    

    Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:

    var questionmark_block = "\\?"; // A literal ?
    var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
    var re = new RegExp(initial_subpattern + questionmark_block, "g");
    

    And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

    _x000D_
    _x000D_
    const questionmark_block = String.raw`\?`; // A literal ?
    const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
    const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
    console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
    _x000D_
    _x000D_
    _x000D_

    A must-read: RegExp: Description at MDN.

    get the latest fragment in backstack

    Actually there's no latest fragment added to the stack because you can add several or fragments to the stack in a single transaction or just remove fragments without adding a new one.

    If you really want to have a stack of fragments and to be able to access a fragment by its index in the stack, you'd better have an abstraction layer over the FragmentManager and its backstack. Here's how you can do it:

    public class FragmentStackManager {
      private final FragmentManager fragmentManager;
      private final int containerId;
    
      private final List<Fragment> fragments = new ArrayList<>();
    
      public FragmentStackManager(final FragmentManager fragmentManager,
          final int containerId) {
        this.fragmentManager = fragmentManager;
        this.containerId = containerId;
      }
    
      public Parcelable saveState() {
        final Bundle state = new Bundle(fragments.size());
        for (int i = 0, count = fragments.size(); i < count; ++i) {
          fragmentManager.putFragment(state, Integer.toString(i), fragments.get(i));
        }
        return state;
      }
    
      public void restoreState(final Parcelable state) {
        if (state instanceof Bundle) {
          final Bundle bundle = (Bundle) state;
          int index = 0;
          while (true) {
            final Fragment fragment =
                fragmentManager.getFragment(bundle, Integer.toString(index));
            if (fragment == null) {
              break;
            }
    
            fragments.add(fragment);
            index += 1;
          }
        }
      }
    
      public void replace(final Fragment fragment) {
        fragmentManager.popBackStackImmediate(
            null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        fragmentManager.beginTransaction()
            .replace(containerId, fragment)
            .addToBackStack(null)
            .commit();
        fragmentManager.executePendingTransactions();
    
        fragments.clear();
        fragments.add(fragment);
      }
    
      public void push(final Fragment fragment) {
        fragmentManager
            .beginTransaction()
            .replace(containerId, fragment)
            .addToBackStack(null)
            .commit();
        fragmentManager.executePendingTransactions();
    
        fragments.add(fragment);
      }
    
      public boolean pop() {
        if (isEmpty()) {
          return false;
        }
    
        fragmentManager.popBackStackImmediate();
    
        fragments.remove(fragments.size() - 1);
        return true;
      }
    
      public boolean isEmpty() {
        return fragments.isEmpty();
      }
    
      public int size() {
        return fragments.size();
      }
    
      public Fragment getFragment(final int index) {
        return fragments.get(index);
      }
    }
    

    Now instead of adding and removing fragments by calling FragmentManager directly, you should use push(), replace(), and pop() methods of FragmentStackManager. And you will be able to access the topmost fragment by just calling stack.get(stack.size() - 1).

    But if you like hacks, I have to other ways of doing similar things. The only thing I have to mention is that these hacks will work only with support fragments.

    The first hack is just to get all active fragments added to the fragment manager. If you just replace fragments one by one and pop the from the stack this method will return the topmost fragment:

    public class BackStackHelper {
      public static List<Fragment> getTopFragments(
          final FragmentManager fragmentManager) {
        final List<Fragment> fragments = fragmentManager.getFragments();
        final List<Fragment> topFragments = new ArrayList<>();
    
        for (final Fragment fragment : fragments) {
          if (fragment != null && fragment.isResumed()) {
            topFragments.add(fragment);
          }
        }
    
        return topFragments;
      }
    }
    

    The second approach is event more hacky and allows you to get all fragments added in the last transaction for which addToBackStack has been called:

    package android.support.v4.app;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class BackStackHelper {
      public static List<Fragment> getTopFragments(
          final FragmentManager fragmentManager) {
        if (fragmentManager.getBackStackEntryCount() == 0) {
          return Collections.emptyList();
        }
    
        final List<Fragment> fragments = new ArrayList<>();
    
        final int count = fragmentManager.getBackStackEntryCount();
        final BackStackRecord record =
            (BackStackRecord) fragmentManager.getBackStackEntryAt(count - 1);
        BackStackRecord.Op op = record.mHead;
        while (op != null) {
          switch (op.cmd) {
            case BackStackRecord.OP_ADD:
            case BackStackRecord.OP_REPLACE:
            case BackStackRecord.OP_SHOW:
            case BackStackRecord.OP_ATTACH:
              fragments.add(op.fragment);
          }
          op = op.next;
        }
    
        return fragments;
      }
    }
    

    Please notice that in this case you have to put this class into android.support.v4.app package.

    How to get the current time in milliseconds in C Programming

    quick answer

    #include<stdio.h>   
    #include<time.h>   
    
    int main()   
    {   
        clock_t t1, t2;  
        t1 = clock();   
        int i;
        for(i = 0; i < 1000000; i++)   
        {   
            int x = 90;  
        }   
    
        t2 = clock();   
    
        float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
        printf("%f",diff);   
    
        return 0;   
    }
    

    How to convert MySQL time to UNIX timestamp using PHP?

    Use strtotime(..):

    $timestamp = strtotime($mysqltime);
    echo date("Y-m-d H:i:s", $timestamp);
    

    Also check this out (to do it in MySQL way.)

    http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp

    Prevent the keyboard from displaying on activity start

    Try to declare it in menifest file

    <activity android:name=".HomeActivity"
          android:label="@string/app_name"
          android:windowSoftInputMode="stateAlwaysHidden"
          >
    

    Mouseover or hover vue.js

    To show child or sibling elements it's possible with CSS only. If you use :hover before combinators (+, ~, >, space). Then the style applies not to hovered element.

    HTML

    <body>
      <div class="trigger">
        Hover here.
      </div>
      <div class="hidden">
        This message shows up.
      </div>
    </body>
    

    CSS

    .hidden { display: none; }
    .trigger:hover + .hidden { display: inline; }
    

    Maven: How do I activate a profile from command line?

    Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:

    <activation> <activeByDefault>false</activeByDefault> </activation>

    then your profile will be activated only after explicit declaration as -Pdev1

    How to add items to a spinner in Android?

    For adding item in Spinner, you can do one thing, try to create an adapter and then add/remove items into the adapter, then you can easily bind that adapter to spinner by using setAdapter() method.

    Here is an example:

    spinner.setAdapter(adapter);
    adapter.add(item1);
    adapter.add(item2);
    adapter.add(item3);
    adapter.add(item4);
    adapter.add(item5);
    adapter.notifyDataSetChanged();
    spinner.setAdapter(adapter);
    

    how do I change text in a label with swift?

    swift solution

    yourlabel.text = yourvariable
    

    or self is use for when you are in async {brackets} or in some Extension

    DispatchQueue.main.async{
        self.yourlabel.text = "typestring"
    }
    

    How to check if two arrays are equal with JavaScript?

    Even if this would seem super simple, sometimes it's really useful. If all you need is to see if two arrays have the same items and they are in the same order, try this:

    [1, 2, 3].toString() == [1, 2, 3].toString()
    true
    [1, 2, 3,].toString() == [1, 2, 3].toString()
    true
    [1,2,3].toString() == [1, 2, 3].toString()
    true
    

    However, this doesn't work for mode advanced cases such as:

    [[1,2],[3]].toString() == [[1],[2,3]].toString()
    true
    

    It depends what you need.

    Angular 6: How to set response type as text while making http call

    On your backEnd, you should add:

    @RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)
    

    On the frontEnd (Service):

    methodBlabla() 
    {
      const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
      return this.http.get(this.url,{ headers, responseType: 'text'});
    }
    

    How to convert JSON object to an Typescript array?

    To convert any JSON to array, use the below code:

    const usersJson: any[] = Array.of(res.json());
    

    Java random number with given length

    To generate a 6-digit number:

    Use Random and nextInt as follows:

    Random rnd = new Random();
    int n = 100000 + rnd.nextInt(900000);
    

    Note that n will never be 7 digits (1000000) since nextInt(900000) can at most return 899999.

    So how do I randomize the last 5 chars that can be either A-Z or 0-9?

    Here's a simple solution:

    // Generate random id, for example 283952-V8M32
    char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
    Random rnd = new Random();
    StringBuilder sb = new StringBuilder((100000 + rnd.nextInt(900000)) + "-");
    for (int i = 0; i < 5; i++)
        sb.append(chars[rnd.nextInt(chars.length)]);
    
    return sb.toString();
    

    onClick function of an input type="button" not working

    You've forgot to define an onclick attribute to do something when the button is clicked, so nothing happening is the correct execution, see below;

    <input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />
                                         ----------------------
    

    Repeat command automatically in Linux

    Running commands periodically without cron is possible when we go with while.

    As a command:

    while true ; do command ; sleep 100 ; done &
    [ ex: # while true;  do echo `date` ; sleep 2 ; done & ]
    

    Example:

    while true
    do echo "Hello World"
    sleep 100
    done &
    

    Do not forget the last & as it will put your loop in the background. But you need to find the process id with command "ps -ef | grep your_script" then you need to kill it. So kindly add the '&' when you running the script.

    # ./while_check.sh &
    

    Here is the same loop as a script. Create file "while_check.sh" and put this in it:

    #!/bin/bash
    while true; do 
        echo "Hello World" # Substitute this line for whatever command you want.
        sleep 100
    done
    

    Then run it by typing bash ./while_check.sh &

    Aggregate multiple columns at once

    You could try:

    agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
    

    Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

    Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

    I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

    Cast IList to List

    If you have an IList containing interfaces, you can cast it like this:

    List to IList

    List<Foo> Foos = new List<Foo>(); 
    IList<IFoo> IFoos = Foos.ToList<IFoo>();
    

    IList to List

    IList<IFoo> IFoos = new List<IFoo>();
    List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));
    

    This assumes Foo has IFoo interfaced.

    Querying Datatable with where condition

    You can do it with Linq, as mamoo showed, but the oldies are good too:

    var filteredDataTable = dt.Select(@"EmpId > 2
        AND (EmpName <> 'abc' OR EmpName <> 'xyz')
        AND EmpName like '%il%'" );
    

    TypeError: 'NoneType' object is not iterable in Python

    For me it was a case of having my Groovy hat on instead of the Python 3 one.

    Forgot the return keyword at the end of a def function.

    Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy (or Rust) way.

    Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ... block debugging/stepping thru code to figure out what was wrong.

    The solution for the message certainly did not make the error jump out at me.

    How to wrap text of HTML button with fixed width?

    If we have some inner divisions inside <button> tag like this-

    <button class="top-container">
        <div class="classA">
           <div class="classB">
               puts " some text to get print." 
           </div>
         </div>
         <div class="class1">
           <div class="class2">
               puts " some text to get print." 
           </div>
         </div>
    </button>
    

    Sometime Text of class A get overlap on class1 data because these both are in a single button tag. I try to break the tex using-

     word-wrap: break-word;         /* All browsers since IE 5.5+ */
     overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */ 
    

    But this won't worked then I try this-

    white-space: normal;
    

    after removing above css properties and got my task done.

    Hope will work for all !!!

    function to return a string in java

    Your code is fine. There's no problem with returning Strings in this manner.

    In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

    If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

    public String time_to_string(long t) // time in milliseconds
    {
        if (t < 0)
        {
            return "-";
        }
        else
        {
            int secs = (int)(t/1000);
            int mins = secs/60;
            secs = secs - (mins * 60);
            return String.format("%d:%02d", mins, secs);
        }
    }
    

    As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

    git replace local version with remote version

    My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

    In that scenario you can just run the following command:

    git checkout -- path/filename
    

    get number of columns of a particular row in given excel using Java

    Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
    I used the method below to get the last column index that contains an actual value.

    private int getLastFilledCellPosition(Row row) {
            int columnIndex = -1;
    
            for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
                Cell cell = row.getCell(i);
    
                if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                    continue;
                } else {
                    columnIndex = cell.getColumnIndex();
                    break;
                }
            }
    
            return columnIndex;
        }
    

    Writing numerical values on the plot with Matplotlib

    You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

    import numpy
    from matplotlib import pyplot
    
    x = numpy.arange(10)
    y = numpy.array([5,3,4,2,7,5,4,6,3,2])
    
    fig = pyplot.figure()
    ax = fig.add_subplot(111)
    ax.set_ylim(0,10)
    pyplot.plot(x,y)
    for i,j in zip(x,y):
        ax.annotate(str(j),xy=(i,j))
    
    pyplot.show()
    

    If you want the annotations offset a little, you could change the annotate line to something like

    ax.annotate(str(j),xy=(i,j+0.5))
    

    Regex for Mobile Number Validation

    Satisfies all your requirements if you use the trick told below

    Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/

    1. ^ start of line
    2. A + followed by \d+ followed by a or - which are optional.
    3. Whole point two is optional.
    4. Negative lookahead to make sure 0s do not follow.
    5. Match \d+ 10 times.
    6. Line end.

    DEMO Added multiline flag in demo to check for all cases

    P.S. You really need to specify which language you use so as to use an if condition something like below:

    // true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
    
    if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
    

    How to calculate the SVG Path for an arc (of a circle)

    This is an old question, but I found the code useful and saved me three minutes of thinking :) So I am adding a small expansion to @opsb's answer.

    If you wanted to convert this arc into a slice (to allow for fill) we can modify the code slightly:

    _x000D_
    _x000D_
    function describeArc(x, y, radius, spread, startAngle, endAngle){_x000D_
        var innerStart = polarToCartesian(x, y, radius, endAngle);_x000D_
       var innerEnd = polarToCartesian(x, y, radius, startAngle);_x000D_
        var outerStart = polarToCartesian(x, y, radius + spread, endAngle);_x000D_
        var outerEnd = polarToCartesian(x, y, radius + spread, startAngle);_x000D_
    _x000D_
        var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";_x000D_
    _x000D_
        var d = [_x000D_
            "M", outerStart.x, outerStart.y,_x000D_
            "A", radius + spread, radius + spread, 0, largeArcFlag, 0, outerEnd.x, outerEnd.y,_x000D_
            "L", innerEnd.x, innerEnd.y, _x000D_
            "A", radius, radius, 0, largeArcFlag, 1, innerStart.x, innerStart.y, _x000D_
            "L", outerStart.x, outerStart.y, "Z"_x000D_
        ].join(" ");_x000D_
    _x000D_
        return d;_x000D_
    }_x000D_
    _x000D_
    function polarToCartesian(centerX, centerY, radius, angleInDegrees) {_x000D_
      var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;_x000D_
    _x000D_
      return {_x000D_
        x: centerX + (radius * Math.cos(angleInRadians)),_x000D_
        y: centerY + (radius * Math.sin(angleInRadians))_x000D_
      };_x000D_
    }_x000D_
    _x000D_
    var path = describeArc(150, 150, 50, 30, 0, 50)_x000D_
    document.getElementById("p").innerHTML = path_x000D_
    document.getElementById("path").setAttribute('d',path)
    _x000D_
    <p id="p">_x000D_
    </p>_x000D_
    <svg width="300" height="300" style="border:1px gray solid">_x000D_
      <path id="path" fill="blue" stroke="cyan"></path>_x000D_
    </svg>
    _x000D_
    _x000D_
    _x000D_

    and there you go!

    List comprehension vs. lambda + filter

    An important difference is that list comprehension will return a list while the filter returns a filter, which you cannot manipulate like a list (ie: call len on it, which does not work with the return of filter).

    My own self-learning brought me to some similar issue.

    That being said, if there is a way to have the resulting list from a filter, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList(), I am curious to know it.

    EDIT: This is the case for Python 3, not 2 (see discussion in comments).

    Convert string to JSON Object

    Enclose the string in single quote it should work. Try this.

    var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
    var obj = $.parseJSON(jsonObj);
    

    Demo

    How to display line numbers in 'less' (GNU)

    You can also press = while less is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:

    myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1%  (press RETURN)
    

    So here for example, the screen was currently showing lines 20530-20585, and the files has a total of 1816468 lines.

    How to programmatically connect a client to a WCF service?

    You'll have to use the ChannelFactory class.

    Here's an example:

    var myBinding = new BasicHttpBinding();
    var myEndpoint = new EndpointAddress("http://localhost/myservice");
    using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
    {
        IMyService client = null;
    
        try
        {
            client = myChannelFactory.CreateChannel();
            client.MyServiceOperation();
            ((ICommunicationObject)client).Close();
            myChannelFactory.Close();
        }
        catch
        {
            (client as ICommunicationObject)?.Abort();
        }
    }
    

    Related resources:

    How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

    You have some options

    • Write a method on repository that return a initialized entity as R.J suggested.

    More work, best performance.

    • Use OpenEntityManagerInViewFilter to keep session open for the entire request.

    Less work, usually acceptable in web enviroments.

    • Use a helper class to initialize entities when required.

    Less work, useful when OEMIV is not at option, for example in a Swing application, but may be useful too on repository implementations to initialize any entity in one shot.

    For the last option, I wrote a utility class, JpaUtils to initilize entities at some deph.

    For example:

    @Transactional
    public class RepositoryHelper {
    
        @PersistenceContext
        private EntityManager em;
    
        public void intialize(Object entity, int depth) {
            JpaUtils.initialize(em, entity, depth);
        }
    }
    

    Datatable select method ORDER BY clause

    Use

    datatable.select("col1='test'","col1 ASC")
    

    Then before binding your data to the grid or repeater etc, use this

    datatable.defaultview.sort()
    

    That will solve your problem.

    Pandas groupby: How to get a union of strings

    a simple solution would be :

    >>> df.groupby(['A','B']).c.unique().reset_index()
    

    Node.js on multi-core machines

    It's possible to scale NodeJS out to multiple boxes using a pure TCP load balancer (HAProxy) in front of multiple boxes running one NodeJS process each.

    If you then have some common knowledge to share between all instances you could use a central Redis store or similar which can then be accessed from all process instances (e.g. from all boxes)

    Writing a large resultset to an Excel file using POI

    Unless you have to write formulas or formatting you should consider writing out a .csv file. Infinitely simpler, infinitely faster, and Excel will do the conversion to .xls or .xlsx automatically and correctly by definition.

    Calculate days between two Dates in Java 8

    Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).

    The docs for both actually mention both approaches and say to use whichever one is more readable.

    Passing arrays as parameters in bash

    As ugly as it is, here is a workaround that works as long as you aren't passing an array explicitly, but a variable corresponding to an array:

    function passarray()
    {
        eval array_internally=("$(echo '${'$1'[@]}')")
        # access array now via array_internally
        echo "${array_internally[@]}"
        #...
    }
    
    array=(0 1 2 3 4 5)
    passarray array # echo's (0 1 2 3 4 5) as expected
    

    I'm sure someone can come up with a clearner implementation of the idea, but I've found this to be a better solution than passing an array as "{array[@]"} and then accessing it internally using array_inside=("$@"). This becomes complicated when there are other positional/getopts parameters. In these cases, I've had to first determine and then remove the parameters not associated with the array using some combination of shift and array element removal.

    A purist perspective likely views this approach as a violation of the language, but pragmatically speaking, this approach has saved me a whole lot of grief. On a related topic, I also use eval to assign an internally constructed array to a variable named according to a parameter target_varname I pass to the function:

    eval $target_varname=$"(${array_inside[@]})"

    Hope this helps someone.

    How to save public key from a certificate in .pem format

    There are a couple ways to do this.

    First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

    E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem
    

    If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

    openssl> x509 -pubkey -noout -in cert.pem
    

    Output will look something like this:

    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
    3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
    7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
    j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
    OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
    5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
    FQIDAQAB
    -----END PUBLIC KEY-----
    

    How do you handle a form change in jQuery?

    Here is an elegant solution.

    There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example

    • for text/textarea it's defaultValue
    • for select it's defaultSelect
    • for checkbox/radio it's defaultChecked

    Here is the example.

    function bindFormChange($form) {
    
      function touchButtons() {
        var
          changed_objects = [],
          $observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
    
        changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
          var
            $input = $(this),
            changed = false;
    
          if ($input.is('input:text') || $input.is('textarea') ) {
            changed = (($input).prop('defaultValue') != $input.val());
          }
          if (!changed && $input.is('select') ) {
            changed = !$('option:selected', $input).prop('defaultSelected');
          }
          if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
            changed = (($input).prop('defaultChecked') != $input.is(':checked'));
          }
          if (changed) {
            return $input.attr('id');
          }
    
        }).toArray();
    
        if (changed_objects.length) {
          $observable_buttons.removeAttr('disabled')   
        } else {
          $observable_buttons.attr('disabled', 'disabled');
        }
      };
      touchButtons();
    
      $('input, textarea, select', $form).each(function () {
        var $input = $(this);
    
        $input.on('keyup change', function () {
          touchButtons();
        });
      });
    
    };
    

    Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.

    $('form').each(function () {
        bindFormChange($(this));
    });
    

    Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable

    How to create and download a csv file from php script?

    Try... csv download.

    <?php 
    mysql_connect('hostname', 'username', 'password');
    mysql_select_db('dbname');
    $qry = mysql_query("SELECT * FROM tablename");
    $data = "";
    while($row = mysql_fetch_array($qry)) {
      $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
    }
    
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="filename.csv"');
    echo $data; exit();
    ?>
    

    WPF binding to Listbox selectedItem

    For me, I usually use DataContext together in order to bind two-depth property such as this question.

    <TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

    Or, I prefer to use ElementName because it achieves bindings only with view controls.

    <TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />

    What is the right way to write my script 'src' url for a local development environment?

    This is an old post but...

    You can reference the working directory (the folder the .html file is located in) with ./, and the directory above that with ../

    Example directory structure:

    /html/public/
    - index.html
    - script2.js
    - js/
       - script.js
    

    To load script.js from inside index.html:

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

    This goes to the current working directory (location of index.html) and then to the js folder, and then finds the script.

    You could also specify ../ to go one directory above the working directory, to load things from there. But that is unusual.

    String.Replace(char, char) method in C#

    As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.

    One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.

    If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.

    string temp = mystring.Replace("\r\n", string.Empty);
    

    or:

    string temp = mystring.Replace(Environment.NewLine, string.Empty);
    

    Android - setOnClickListener vs OnClickListener vs View.OnClickListener

    Please note that for the sake of simplicity I have made reference to only the first code snippet i.e.,

    // Create an anonymous implementation of OnClickListener
    private OnClickListener mCorkyListener = new OnClickListener() {
        public void onClick(View v) {
          // do something when the button is clicked
        }
    };
    
    protected void onCreate(Bundle savedValues) {
        ...
        // Capture our button from layout
        Button button = (Button)findViewById(R.id.corky);
        // Register the onClick listener with the implementation above
        button.setOnClickListener(mCorkyListener);
        ...
    }
    

    setOnClickListener(View.OnClickListener l) is a public method of View class. Button class extends the View class and can therefore call setOnClickListener(View.OnClickListener l) method.

    setOnClickListener registers a callback to be invoked when the view (button in your case) is clicked. This answers should answer your first two questions:

    1. Where does setOnClickListener fit in the above logic?

    Ans. It registers a callback when the button is clicked. (Explained in detail in the next paragraph).

    2. Which one actually listens to the button click?

    Ans. setOnClickListener method is the one that actually listens to the button click.

    When I say it registers a callback to be invoked, what I mean is it will run the View.OnClickListener l that is the input parameter for the method. In your case, it will be mCorkyListener mentioned in button.setOnClickListener(mCorkyListener); which will then execute the method onClick(View v) mentioned within

    // Create an anonymous implementation of OnClickListener
    private OnClickListener mCorkyListener = new OnClickListener() {
        public void onClick(View v) {
          // do something when the button is clicked
        }
    };
    

    Moving on further, OnClickListener is an Interface definition for a callback to be invoked when a view (button in your case) is clicked. Simply saying, when you click that button, the methods within mCorkyListener (because it is an implementation of OnClickListener) are executed. But, OnClickListener has just one method which is OnClick(View v). Therefore, whatever action that needs to be performed on clicking the button must be coded within this method.

    Now that you know what setOnClickListener and OnClickListener mean, I'm sure you'll be able to differentiate between the two yourself. The third term View.OnClickListener is actually OnClickListener itself. The only reason you have View.preceding it is because of the difference in the import statment in the beginning of the program. If you have only import android.view.View; as the import statement you will have to use View.OnClickListener. If you mention either of these import statements: import android.view.View.*; or import android.view.View.OnClickListener; you can skip the View. and simply use OnClickListener.

    Create Excel file in Java

    Fair warning about Apache POI's Excel generation... (I know this is an old post, but it's important in case someone looks this up again like I just did)

    It had a memory leak issue, which supposedly was solved by 2006, but which people quite recently have still been experiencing. If you want to automate generating a large amount of excel (i.e., if you want to generate a single, large file, a large number of small files, or both), I'd recommend using a different API. Either that, or increasing the JVM stack size to preposterous proportions, and maybe looking into interning strings if you know you won't actually be working with many different strings (although, of course, interning strings means that if you have a large number of different strings, you'll have an entirely different program-crashing memory problem. So, consider that before you go that route).

    Random word generator- Python

    There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

    How do I display Ruby on Rails form validation error messages one at a time?

    ActiveRecord stores validation errors in an array called errors. If you have a User model then you would access the validation errors in a given instance like so:

    @user = User.create[params[:user]] # create will automatically call validators
    
    if @user.errors.any? # If there are errors, do something
    
      # You can iterate through all messages by attribute type and validation message
      # This will be something like:
      # attribute = 'name'
      # message = 'cannot be left blank'
      @user.errors.each do |attribute, message|
        # do stuff for each error
      end
    
      # Or if you prefer, you can get the full message in single string, like so:
      # message = 'Name cannot be left blank'
      @users.errors.full_messages.each do |message|
        # do stuff for each error
      end
    
      # To get all errors associated with a single attribute, do the following:
      if @user.errors.include?(:name)
        name_errors = @user.errors[:name]
    
        if name_errors.kind_of?(Array)
          name_errors.each do |error|
            # do stuff for each error on the name attribute
          end
        else
          error = name_errors
          # do stuff for the one error on the name attribute.
        end
      end
    end
    

    Of course you can also do any of this in the views instead of the controller, should you want to just display the first error to the user or something.

    How to select <td> of the <table> with javascript?

    try document.querySelectorAll("#table td");

    java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

    I copied the contents of the "C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf" directory to the "workspace\Servers\Tomcat v6.0 Server at localhost-config" directory for Eclipse. I refreshed the "Servers\Tomcat v6.0 Server at localhost-config" folder in the Eclipse Project Explorer and then everything was good.

    What is the difference between ndarray and array in numpy?

    numpy.ndarray() is a class, while numpy.array() is a method / function to create ndarray.

    In numpy docs if you want to create an array from ndarray class you can do it with 2 ways as quoted:

    1- using array(), zeros() or empty() methods: Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

    2- from ndarray class directly: There are two modes of creating an array using __new__: If buffer is None, then only shape, dtype, and order are used. If buffer is an object exposing the buffer interface, then all keywords are interpreted.

    The example below gives a random array because we didn't assign buffer value:

    np.ndarray(shape=(2,2), dtype=float, order='F', buffer=None)
    
    array([[ -1.13698227e+002,   4.25087011e-303],
           [  2.88528414e-306,   3.27025015e-309]])         #random
    

    another example is to assign array object to the buffer example:

    >>> np.ndarray((2,), buffer=np.array([1,2,3]),
    ...            offset=np.int_().itemsize,
    ...            dtype=int) # offset = 1*itemsize, i.e. skip first element
    array([2, 3])
    

    from above example we notice that we can't assign a list to "buffer" and we had to use numpy.array() to return ndarray object for the buffer

    Conclusion: use numpy.array() if you want to make a numpy.ndarray() object"

    Difference between style = "position:absolute" and style = "position:relative"

    Absolute positioning means that the element is taken completely out of the normal flow of the page layout. As far as the rest of the elements on the page are concerned, the absolutely positioned element simply doesn't exist. The element itself is then drawn separately, sort of "on top" of everything else, at the position you specify using the left, right, top and bottom attributes.

    Using the position you specify with these attributes, the element is then placed at that position within its last ancestor element which has a position attribute of anything other than static (page elements default to static when no position attribute specified), or the document body (browser viewport) if no such ancestor exists.

    For example, if I had this code:

    <body>
      <div style="position:absolute; left: 20px; top: 20px;"></div>
    </body>
    

    ...the <div> would be positioned 20px from the top of the browser viewport, and 20px from the left edge of same.

    However, if I did something like this:

     <div id="outer" style="position:relative">
       <div id="inner" style="position:absolute; left: 20px; top: 20px;"></div>
     </div>
    

    ...then the inner div would be positioned 20px from the top of the outer div, and 20px from the left edge of same, because the outer div isn't positioned with position:static because we've explicitly set it to use position:relative.

    Relative positioning, on the other hand, is just like stating no positioning at all, but the left, right, top and bottom attributes "nudge" the element out of their normal layout. The rest of the elements on the page still get laid out as if the element was in its normal spot though.

    For example, if I had this code:

    <span>Span1</span>
    <span>Span2</span>
    <span>Span3</span>
    

    ...then all three <span> elements would sit next to each other without overlapping.

    If I set the second <span> to use relative positioning, like this:

    <span>Span1</span>
    <span style="position: relative; left: -5px;">Span2</span>
    <span>Span3</span>
    

    ...then Span2 would overlap the right side of Span1 by 5px. Span1 and Span3 would sit in exactly the same place as they did in the first example, leaving a 5px gap between the right side of Span2 and the left side of Span3.

    Hope that clarifies things a bit.

    finished with non zero exit value

    when our code has layout.xml file error ,we get this error message. Check your xml files again.

    Assert that a method was called in a Python unit test

    You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

    class MyTest(TestCase):
      def testClear():
        old_clear = aw.Clear
        clear_calls = 0
        aw.Clear = lambda: clear_calls += 1
        aps.Request('nv2', aw)
        assert clear_calls == 1
        aw.Clear = old_clear
    

    Using pymox, you'd do it like this:

    class MyTest(mox.MoxTestBase):
      def testClear():
        aw = self.m.CreateMock(aps.Request)
        aw.Clear()
        self.mox.ReplayAll()
        aps.Request('nv2', aw)
    

    NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

    In my projects, this piece of code always worked as a default serializer which serializes the specified value as if there was no special converter:

    serializer.Serialize(writer, value);
    

    How do I use PHP to get the current year?

    With PHP heading in a more object-oriented direction, I'm surprised nobody here has referenced the built-in DateTime class:

    $now = new DateTime();
    $year = $now->format("Y");
    

    or one-liner with class member access on instantiation (php>=5.4):

    $year = (new DateTime)->format("Y");
    

    how to convert numeric to nvarchar in sql command

    declare @MyNumber int
    set @MyNumber = 123
    select 'My number is ' + CAST(@MyNumber as nvarchar(20))
    

    com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

    1. First Replace the MySQL dependency as given below

      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.44</version>
      </dependency>
      
    2. An error showing "Authentication plugin 'caching_sha2_password'" will appear. Run this command:

      mysql -u root -p
      ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
      

    Set LIMIT with doctrine 2?

     $qb = $this->getDoctrine()->getManager()->createQueryBuilder();  
     $qb->select('p') ->from('Pandora\UserBundle\Entity\PhoneNumber', 'p');
    $qb->where('p.number = :number');
    $qb->OrWhere('p.validatedNumber=:number');
    $qb->setMaxResults(1);
    $qb->setParameter('number',$postParams['From'] );
    $result = $qb->getQuery()->getResult();
     $data=$result[0];
    

    How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

    I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

    Subclipse svn:ignore

    It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.

    alt text

    For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.

    ALTER TABLE DROP COLUMN failed because one or more objects access this column

    You must remove the constraints from the column before removing the column. The name you are referencing is a default constraint.

    e.g.

    alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];
    alter table CompanyTransactions drop column [Created];
    

    How to deal with "data of class uneval" error from ggplot2?

    This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.