Programs & Examples On #Installed applications

Regular expression for validating names and surnames?

I would think you would be better off excluding the characters you don't want with a regex. Trying to get every umlaut, accented e, hyphen, etc. will be pretty insane. Just exclude digits (but then what about a guy named "George Forman the 4th") and symbols you know you don't want like @#$%^ or what have you. But even then, using a regex will only guarantee that the input matches the regex, it will not tell you that it is a valid name

EDIT after clarifying that this is trying to prevent XSS: A regex on a name field is obviously not going to stop XSS on it's own. However, this article has a section on filtering that is a starting point if you want to go that route.

http://tldp.org/HOWTO/Secure-Programs-HOWTO/cross-site-malicious-content.html

s/[\<\>\"\'\%\;\(\)\&\+]//g;

Why in C++ do we use DWORD rather than unsigned int?

When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.

When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.

When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.

I don't think WORD or DWORD will ever change.

Redefining the Index in a Pandas DataFrame object

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

In :

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

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

data

Out:

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

In :

data2 = data.set_index('a')

Out:

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

In :

data2.index.name = None

Out:

     b   c
 1   2   3
10  11  12
20  21  22

Converting a string to a date in JavaScript

I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object. https://jsfiddle.net/Sushil231088/q56yd0rp/

"17/9/2014".toDate("dd/MM/yyyy", "/")

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

What is DOM Event delegation?

Event delegation is handling an event that bubbles using an event handler on a container element, but only activating the event handler's behavior if the event happened on an element within the container that matches a given condition. This can simplify handling events on elements within the container.

For instance, suppose you want to handle a click on any table cell in a big table. You could write a loop to hook up a click handler to each cell...or you could hook up a click handler on the table and use event delegation to trigger it only for table cells (and not table headers, or the whitespace within a row around cells, etc.).

It's also useful when you're going to be adding and removing elements from the container, because you don't have to worry about adding and removing event handlers on those elements; just hook the event on the container and handle the event when it bubbles.

Here's a simple example (it's intentionally verbose to allow for inline explanation): Handling a click on any td element in a container table:

_x000D_
_x000D_
// Handle the event on the container_x000D_
document.getElementById("container").addEventListener("click", function(event) {_x000D_
    // Find out if the event targeted or bubbled through a `td` en route to this container element_x000D_
    var element = event.target;_x000D_
    var target;_x000D_
    while (element && !target) {_x000D_
        if (element.matches("td")) {_x000D_
            // Found a `td` within the container!_x000D_
            target = element;_x000D_
        } else {_x000D_
            // Not found_x000D_
            if (element === this) {_x000D_
                // We've reached the container, stop_x000D_
                element = null;_x000D_
            } else {_x000D_
                // Go to the next parent in the ancestry_x000D_
                element = element.parentNode;_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    if (target) {_x000D_
        console.log("You clicked a td: " + target.textContent);_x000D_
    } else {_x000D_
        console.log("That wasn't a td in the container table");_x000D_
    }_x000D_
});
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
    border: 1px solid #ddd;_x000D_
}_x000D_
th, td {_x000D_
    padding: 4px;_x000D_
    border: 1px solid #ddd;_x000D_
    font-weight: normal;_x000D_
}_x000D_
th.rowheader {_x000D_
    text-align: left;_x000D_
}_x000D_
td {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<table id="container">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>Language</th>_x000D_
            <th>1</th>_x000D_
            <th>2</th>_x000D_
            <th>3</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th class="rowheader">English</th>_x000D_
            <td>one</td>_x000D_
            <td>two</td>_x000D_
            <td>three</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th class="rowheader">Español</th>_x000D_
            <td>uno</td>_x000D_
            <td>dos</td>_x000D_
            <td>tres</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th class="rowheader">Italiano</th>_x000D_
            <td>uno</td>_x000D_
            <td>due</td>_x000D_
            <td>tre</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Before going into the details of that, let's remind ourselves how DOM events work.

DOM events are dispatched from the document to the target element (the capturing phase), and then bubble from the target element back to the document (the bubbling phase). This graphic in the old DOM3 events spec (now superceded, but the graphic's still valid) shows it really well:

enter image description here

Not all events bubble, but most do, including click.

The comments in the code example above describe how it works. matches checks to see if an element matches a CSS selector, but of course you can check for whether something matches your criteria in other ways if you don't want to use a CSS selector.

That code is written to call out the individual steps verbosely, but on vaguely-modern browsers (and also on IE if you use a polyfill), you can use closest and contains instead of the loop:

var target = event.target.closest("td");
    console.log("You clicked a td: " + target.textContent);
} else {
    console.log("That wasn't a td in the container table");
}

Live Example:

_x000D_
_x000D_
// Handle the event on the container_x000D_
document.getElementById("container").addEventListener("click", function(event) {_x000D_
    var target = event.target.closest("td");_x000D_
    if (target && this.contains(target)) {_x000D_
        console.log("You clicked a td: " + target.textContent);_x000D_
    } else {_x000D_
        console.log("That wasn't a td in the container table");_x000D_
    }_x000D_
});
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
    border: 1px solid #ddd;_x000D_
}_x000D_
th, td {_x000D_
    padding: 4px;_x000D_
    border: 1px solid #ddd;_x000D_
    font-weight: normal;_x000D_
}_x000D_
th.rowheader {_x000D_
    text-align: left;_x000D_
}_x000D_
td {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<table id="container">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>Language</th>_x000D_
            <th>1</th>_x000D_
            <th>2</th>_x000D_
            <th>3</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th class="rowheader">English</th>_x000D_
            <td>one</td>_x000D_
            <td>two</td>_x000D_
            <td>three</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th class="rowheader">Español</th>_x000D_
            <td>uno</td>_x000D_
            <td>dos</td>_x000D_
            <td>tres</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th class="rowheader">Italiano</th>_x000D_
            <td>uno</td>_x000D_
            <td>due</td>_x000D_
            <td>tre</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

closest checks the element you call it on to see if it matches the given CSS selector and, if it does, returns that same element; if not, it checks the parent element to see if it matches, and returns the parent if so; if not, it checks the parent's parent, etc. So it finds the "closest" element in the ancestor list that matches the selector. Since that might go past the container element, the code above uses contains to check that if a matching element was found, it's within the container — since by hooking the event on the container, you've indicated you only want to handle elements within that container.

Going back to our table example, that means that if you have a table within a table cell, it won't match the table cell containing the table:

_x000D_
_x000D_
// Handle the event on the container_x000D_
document.getElementById("container").addEventListener("click", function(event) {_x000D_
    var target = event.target.closest("td");_x000D_
    if (target && this.contains(target)) {_x000D_
        console.log("You clicked a td: " + target.textContent);_x000D_
    } else {_x000D_
        console.log("That wasn't a td in the container table");_x000D_
    }_x000D_
});
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
    border: 1px solid #ddd;_x000D_
}_x000D_
th, td {_x000D_
    padding: 4px;_x000D_
    border: 1px solid #ddd;_x000D_
    font-weight: normal;_x000D_
}_x000D_
th.rowheader {_x000D_
    text-align: left;_x000D_
}_x000D_
td {_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<!-- The table wrapped around the #container table -->_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>_x000D_
                <!-- This cell doesn't get matched, thanks to the `this.contains(target)` check -->_x000D_
                <table id="container">_x000D_
                    <thead>_x000D_
                        <tr>_x000D_
                            <th>Language</th>_x000D_
                            <th>1</th>_x000D_
                            <th>2</th>_x000D_
                            <th>3</th>_x000D_
                        </tr>_x000D_
                    </thead>_x000D_
                    <tbody>_x000D_
                        <tr>_x000D_
                            <th class="rowheader">English</th>_x000D_
                            <td>one</td>_x000D_
                            <td>two</td>_x000D_
                            <td>three</td>_x000D_
                        </tr>_x000D_
                        <tr>_x000D_
                            <th class="rowheader">Español</th>_x000D_
                            <td>uno</td>_x000D_
                            <td>dos</td>_x000D_
                            <td>tres</td>_x000D_
                        </tr>_x000D_
                        <tr>_x000D_
                            <th class="rowheader">Italiano</th>_x000D_
                            <td>uno</td>_x000D_
                            <td>due</td>_x000D_
                            <td>tre</td>_x000D_
                        </tr>_x000D_
                    </tbody>_x000D_
                </table>_x000D_
            </td>_x000D_
            <td>_x000D_
                This is next to the container table_x000D_
            </td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to convert a string to utf-8 in Python

Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use:

def make_unicode(input):
    if type(input) != unicode:
        input =  input.decode('utf-8')
    return input

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

  1. Go to Solution Explorer, click the Search button
  2. Leave checked both Search within file content and Search External Files
  3. Type the entities name which your mapping isn't recognizing.
  4. Delete all files RELATED to the problem. Those will probably be named after the same missing entity. DO NOT delete any file with your Context Class name on the file, specially if their extensions are .cs or .tt. In the Context .cs file.
  5. remove all lines of codes referencing the missing entity. They will look like this:

    public virtual DbSet< Entity1> Entity1 { get; set; }
    

This error is common to tables deleted from the database.

When one drops a table in the database, or one just changes the web.config.connectionStrings for the EF Mapped database, to point to a new one and not the one used to generate the original mappings is the problem.

It is this new db these entities with the 3027 error aren't present.

How can I write an anonymous function in Java?

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also


Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

HTML -- two tables side by side

With CSS: table {float:left;}? ?

java.util.Date format SSSSSS: if not microseconds what are the last 3 digits?

I used yet another trick to format date with 6-digit precision (microseconds):

System.out.println(
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.").format(microseconds/1000)
    +String.format("%06d", microseconds%1000000));

This technique can be extended further, to nanoseconds and up.

Change Volley timeout duration

To handle Android Volley Timeout you need to use RetryPolicy

RetryPolicy

  • Volley provides an easy way to implement your RetryPolicy for your requests.
  • Volley sets default Socket & ConnectionTImeout to 5 secs for all requests.

RetryPolicy is an interface where you need to implement your logic of how you want to retry a particular request when a timeout happens.

It deals with these three parameters

  • Timeout - Specifies Socket Timeout in millis per every retry attempt.
  • Number Of Retries - Number of times retry is attempted.
  • Back Off Multiplier - A multiplier which is used to determine exponential time set to socket for every retry attempt.

For ex. If RetryPolicy is created with these values

Timeout - 3000 ms, Num of Retry Attempts - 2, Back Off Multiplier - 2.0

Retry Attempt 1:

  • time = time + (time * Back Off Multiplier);
  • time = 3000 + 6000 = 9000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 9 Secs

Retry Attempt 2:

  • time = time + (time * Back Off Multiplier);
  • time = 9000 + 18000 = 27000ms
  • Socket Timeout = time;
  • Request dispatched with Socket Timeout of 27 Secs

So at the end of Retry Attempt 2 if still Socket Timeout happens Volley would throw a TimeoutError in your UI Error response handler.

//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. 
//Volley does retry for you if you have specified the policy.
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(5000, 
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

HashMaps and Null values?

Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?

I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :

if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");

Got this error:

Struts Problem Report

Struts has detected an unhandled exception:

Messages:   
File:   aoc/psisclient/samples/PDFValidation.java
Line number:    155
Stacktraces

java.lang.NullPointerException
    aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
    aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    ...

Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.

Get week day name from a given month, day and year individually in SQL Server

You need to construct a date string. You're using / or - operators which do MATH/numeric operations on the numeric return values of DATEPART. Then DATENAME is taking that numeric value and interpreting it as a date.

You need to convert it to a string. For example:

SELECT (
  DATENAME(dw, 
  CAST(DATEPART(m, GETDATE()) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(d, myDateCol1) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(yy, getdate()) AS VARCHAR))
  )

How to save username and password with Mercurial?

If you are using TortoiseHg you have to perform these three steps shown in the attached screen shot, this would add your credentials for the specific repository you are working with.

enter image description here

To add global settings you can access the file C:\users\user.name\mercurial.ini and add the section

[auth]
bb.prefix=https://bitbucket.org/zambezia/packagemanager
bb.username = $username
bb.password = $password

Hope this helps.

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

Receive result from DialogFragment

Just to have it as one of the options (since no one mentioned it yet) - you could use an event bus like Otto. So in the dialog you do:

bus.post(new AnswerAvailableEvent(42));

And have your caller (Activity or Fragment) subscribe to it:

@Subscribe public void answerAvailable(AnswerAvailableEvent event) {
   // TODO: React to the event somehow!
}

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

How to install Intellij IDEA on Ubuntu?

JetBrains has a new application called the Toolbox App which quickly and easily installs any JetBrains software you want, assuming you have the license. It also manages your login once to apply across all JetBrains software, a very useful feature.

To use it, download the tar.gz file here, then extract it and run the included executable jetbrains-toolbox. Then sign in, and press install next to IntelliJ IDEA:

enter image description here

If you want to move the executable to /usr/bin/ feel free, however it works fine out of the box wherever you extract it to.

This will also make the appropriate desktop entries upon install.

taking input of a string word by word

(This is for the benefit of others who may refer)

You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.

#include<iostream>
using namespace std;

main()
{
    char word[50];
    cin>>word;
    while(word){
        //Do stuff with word[]
        cin>>word;
    }
}

Is bool a native C type?

C99 added a bool type whose semantics are fundamentally different from those of just about all integer types that had existed before in C, including user-defined and compiler-extension types intended for such purposes, and which some programs may have "type-def"ed to bool.

For example, given bool a = 0.1, b=2, c=255, d=256;, the C99 bool type would set all four objects to 1. If a C89 program used typedef unsigned char bool, the objects would receive 0, 1, 255, and 0, respectively. If it used char, the values might be as above, or c might be -1. If it had used a compiler-extension bit or __bit type, the results would likely be 0, 0, 1, 0 (treating bit in a way equivalent to an unsigned bit-field of size 1, or an unsigned integer type with one value bit).

Using crontab to execute script every minute and another every 24 hours

every minute:

* * * * * /path/to/php /var/www/html/a.php

every 24hours (every midnight):

0 0 * * * /path/to/php /var/www/html/reset.php

See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml

NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

Difference between static STATIC_URL and STATIC_ROOT on Django

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>

How do I send an HTML email?

I found this way not sure it works for all the CSS primitives

By setting the header property "Content-Type" to "text/html"

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

now I can do stuff like

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

mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")

Regards

int to string in MySQL

You can do this:

select t2.*
from t1
join t2 on t2.url = 'site.com/path/' + CAST(t1.id AS VARCHAR(10)) + '/more' 
where t1.id > 9000

Pay attention to CAST(t1.id AS VARCHAR(10)).

Print in new line, java

Your best shot would be with

String.format("%n")

or

System.out.printf("%n");

It is supposed to print a newline character, depending on the current platform, so it's perfect for the console.

If you are printing to a file, then it depends.

What is the difference between private and protected members of C++ classes?

Private : Accessible by class member functions & friend function or friend class. For C++ class this is default access specifier.

Protected: Accessible by class member functions, friend function or friend class & derived classes.

  • You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
  • Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
  • Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.

Refer this link for more detail.

How to sum up elements of a C++ vector?

Nobody seems to address the case of summing elements of a vector that can have NaN values in it, e.g. numerical_limits<double>::quite_NaN()

I usually loop through the elements and bluntly check.

vector<double> x;

//...

size_t n = x.size();

double sum = 0;

for (size_t i = 0; i < n; i++){

  sum += (x[i] == x[i] ? x[i] : 0);

}

It's not fancy at all, i.e. no iterators or any other tricks but I this is how I do it. Some times if there are other things to do inside the loop and I want the code to be more readable I write

double val = x[i];

sum += (val == val ? val : 0);

//...

inside the loop and re-use val if needed.

LINQ to read XML

Or, if you want a more general approach - i.e. for nesting up to "levelN":

void Main()
{
    XElement rootElement = XElement.Load(@"c:\events\test.xml");

    Console.WriteLine(GetOutline(0, rootElement));  
}

private string GetOutline(int indentLevel, XElement element)
{
    StringBuilder result = new StringBuilder();

    if (element.Attribute("name") != null)
    {
        result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
    }

    foreach (XElement childElement in element.Elements())
    {
        result.Append(GetOutline(indentLevel + 1, childElement));
    }

    return result.ToString();
}

Render HTML to PDF in Django site

I get the code to generate the PDF from html template :

    import os

    from weasyprint import HTML

    from django.template import Template, Context
    from django.http import HttpResponse 


    def generate_pdf(self, report_id):

            # Render HTML into memory and get the template firstly
            template_file_loc = os.path.join(os.path.dirname(__file__), os.pardir, 'templates', 'the_template_pdf_generator.html')
            template_contents = read_all_as_str(template_file_loc)
            render_template = Template(template_contents)

            #rendering_map is the dict for params in the template 
            render_definition = Context(rendering_map)
            render_output = render_template.render(render_definition)

            # Using Rendered HTML to generate PDF
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s-%s-%s.pdf' % \
                                              ('topic-test','topic-test', '2018-05-04')
            # Generate PDF
            pdf_doc = HTML(string=render_output).render()
            pdf_doc.pages[0].height = pdf_doc.pages[0]._page_box.children[0].children[
                0].height  # Make PDF file as single page file 
            pdf_doc.write_pdf(response)
            return response

    def read_all_as_str(self, file_loc, read_method='r'):
        if file_exists(file_loc):
            handler = open(file_loc, read_method)
            contents = handler.read()
            handler.close()
            return contents
        else:
            return 'file not exist'  

How to have the formatter wrap code with IntelliJ?

IntelliJ IDEA 14, 15, 2016 & 2017

Format existing code

  1. Ensure right margin is not exceeded

    File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded

    File Settings Ensure right margin

  2. Reformat code

    Code > Reformat code...

    Reformat code

    or press Ctrl + Alt + L

    warning If you have something like this:

    thisLineIsVeryLongAndWillBeChanged();   // comment
    

    it will be converted to

    thisLineIsVeryLongAndWillBeChanged();   
    // comment  
    

    instead of

    // comment  
    thisLineIsVeryLongAndWillBeChanged();   
    

    This is why I select pieces of code before reformatting if the code looks like in the previous example.

Wrap when typing reaches right margin

  • IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin

    Wrap when typing

  • IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing

    Wrap on typing

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Creating executable files in Linux

What you describe is the correct way to handle this.

You said that you want to stay in the GUI. You can usually set the execute bit through the file properties menu. You could also learn how to create a custom action for the context menu to do this for you if you're so inclined. This depends on your desktop environment of course.

If you use a more advanced editor, you can script the action to happen when the file is saved. For example (I'm only really familiar with vim), you could add this to your .vimrc to make any new file that starts with "#!/*/bin/*" executable.

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif

Can I change the color of Font Awesome's icon color?

With reference to @ClarkeyBoy answer, below code works fine, if using latest version of Font-Awesome icons or if you using fa classes

.fa.icon-white {
    color: white;
}

And, then add icon-white to existing class

How to run functions in parallel?

You could use threading or multiprocessing.

Due to peculiarities of CPython, threading is unlikely to achieve true parallelism. For this reason, multiprocessing is generally a better bet.

Here is a complete example:

from multiprocessing import Process

def func1():
  print 'func1: starting'
  for i in xrange(10000000): pass
  print 'func1: finishing'

def func2():
  print 'func2: starting'
  for i in xrange(10000000): pass
  print 'func2: finishing'

if __name__ == '__main__':
  p1 = Process(target=func1)
  p1.start()
  p2 = Process(target=func2)
  p2.start()
  p1.join()
  p2.join()

The mechanics of starting/joining child processes can easily be encapsulated into a function along the lines of your runBothFunc:

def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

runInParallel(func1, func2)

Bi-directional Map in Java?

You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.

Is there a standard sign function (signum, sgn) in C/C++?

The accepted Answer with the overload below does indeed not trigger -Wtype-limits.

template <typename T> inline constexpr
  int signum(T x, std::false_type) {
  return T(0) < x;
}

template <typename T> inline constexpr
  int signum(T x, std::true_type) {
  return (T(0) < x) - (x < T(0));
}

template <typename T> inline constexpr
  int signum(T x) {
  return signum(x, std::is_signed<T>());
}

For C++11 an alternative could be.

template <typename T>
typename std::enable_if<std::is_unsigned<T>::value, int>::type
inline constexpr signum(T const x) {
    return T(0) < x;  
}

template <typename T>
typename std::enable_if<std::is_signed<T>::value, int>::type
inline constexpr signum(T const x) {
    return (T(0) < x) - (x < T(0));  
}

For me it does not trigger any warnings on GCC 5.3.1.

What is a raw type and why shouldn't we use it?

What is a raw type and why do I often hear that they shouldn't be used in new code?

A "raw type" is the use of a generic class without specifying a type argument(s) for its parameterized type(s), e.g. using List instead of List<String>. When generics were introduced into Java, several classes were updated to use generics. Using these class as a "raw type" (without specifying a type argument) allowed legacy code to still compile.

"Raw types" are used for backwards compatibility. Their use in new code is not recommended because using the generic class with a type argument allows for stronger typing, which in turn may improve code understandability and lead to catching potential problems earlier.

What is the alternative if we can't use raw types, and how is it better?

The preferred alternative is to use generic classes as intended - with a suitable type argument (e.g. List<String>). This allows the programmer to specify types more specifically, conveys more meaning to future maintainers about the intended use of a variable or data structure, and it allows compiler to enforce better type-safety. These advantages together may improve code quality and help prevent the introduction of some coding errors.

For example, for a method where the programmer wants to ensure a List variable called 'names' contains only Strings:

List<String> names = new ArrayList<String>();
names.add("John");          // OK
names.add(new Integer(1));  // compile error

How to remove anaconda from windows completely?

Since I didn't have the uninstaller listed - the solution turned out to be to reinstall Anaconda and then uninstall it.

Check if a value is within a range of numbers

If you're already using lodash, you could use the inRange() function: https://lodash.com/docs/4.17.15#inRange

_.inRange(3, 2, 4);
// => true

_.inRange(4, 8);
// => true

_.inRange(4, 2);
// => false

_.inRange(2, 2);
// => false

_.inRange(1.2, 2);
// => true

_.inRange(5.2, 4);
// => false

_.inRange(-3, -2, -6);
// => true

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Try adding the following to your eclipse.ini file:

-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe

You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.

How to validate domain name in PHP?

This is validation of domain name in javascript:

<script>
function frmValidate() {
 var val=document.frmDomin.name.value;
 if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(val)){
      alert("Valid Domain Name");
      return true;
 } else {
      alert("Enter Valid Domain Name");
      val.name.focus();
      return false;
 }
}
</script>

SQL Server table creation date query

For SQL Server 2000:

SELECT   su.name,so.name,so.crdate,* 
FROM     sysobjects so JOIN sysusers su
ON       so.uid = su.uid
WHERE    xtype='U'
ORDER BY so.name

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

php: catch exception and continue execution, is it possible?

Sure:

try {
   throw new Exception('Something bad');
} catch (Exception $e) {
    // Do nothing
}

You might want to go have a read of the PHP documentation on Exceptions.

What is the difference between `let` and `var` in swift?

Source: https://thenucleargeeks.com/2019/04/10/swift-let-vs-var/

When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

var a = 1 
print (a) // output 1
a = 2
print (a) // output 2

let b = 4
print (b) // output 4
b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"

Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

With android studio no jvm found, JAVA_HOME has been set

It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:

C:\Program Files (x86)\

You were setting the JAVA_HOME variable to the 32-bit version of Java. Set your JAVA_HOME variable to the following:

C:\Program Files\Java\jdk1.7.0_45

If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME variable to (with JAVAVERSION as the Java version number:

C:\Program Files\Java\jdkJAVAVERSION

Determine if map contains a value for a key?

Does something along these lines exist?

No. With the stl map class, you use ::find() to search the map, and compare the returned iterator to std::map::end()

so

map<int,Bar>::iterator it = m.find('2');
Bar b3;
if(it != m.end())
{
   //element found;
   b3 = it->second;
}

Obviously you can write your own getValue() routine if you want (also in C++, there is no reason to use out), but I would suspect that once you get the hang of using std::map::find() you won't want to waste your time.

Also your code is slightly wrong:

m.find('2'); will search the map for a keyvalue that is '2'. IIRC the C++ compiler will implicitly convert '2' to an int, which results in the numeric value for the ASCII code for '2' which is not what you want.

Since your keytype in this example is int you want to search like this: m.find(2);

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Under VISTA Command prompt: Click on the System Icon Select Defaults from the Menu On the Options tab in the Options group I have "Quick Edit Mode", "Insert Mode", and "Auto Complete" selected I think that "Quick Edit Mode" is what makes it work.

To paste whatever is in the Clipboard at the insertion point: Right Click. To copy from the Command Window Select by holding down the left mouse button and dragging the pointer across what you want to copy Once selected, right click To paste at the insertion point, right click again.

What is the proper REST response code for a valid request but an empty data?

As stated by many, 404 is misleading and it doesn't allow the client to discriminate if the request uri doesn't exist, or if the requested uri cannot fetch the requested resource.

The 200 status is expected to contain resource data - so it is not the right choice. The 204 status means something else entirely and should not be used as response for GET requests.

All other existing status are not applicable, for one reason or the other.

I have seen this topic being discussed over and over in multiple places. For me, it is painfully obvious that to eliminate the confusion around the topic, a dedicated success status is needed. Something like "209 - No resource to display".

It will be a 2xx status because not finding an ID should not be considered a client error (if the clients knew everything which is in the server's DB, they would not need to ask anything to the server, wouldn't they?). This dedicated status will address all issues debated with using other statuses.

The only question is: how do I get RFC to accept this as a standard?

Generate MD5 hash string with T-SQL

try this:

select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',  '[email protected]' )),3,32) 

Converting JSON data to Java object

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.

Hard reset of a single file

To revert to upstream/master do:

git checkout upstream/master -- myfile.txt

setting system property

For JBoss, in standalone.xml, put after .

<extensions>
</extensions>

<system-properties>
    <property name="my.project.dir" value="/home/francesco" />
</system-properties>

For eclipse:

http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2

How to get the nth occurrence in a string?

You can also use the string indexOf without creating any arrays.

The second parameter is the index to start looking for the next match.

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}

var s= "XYZ 123 ABC 456 ABC 789 ABC";

nthIndex(s,'ABC',3)

/*  returned value: (Number)
24
*/

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

Read specific columns with pandas or other python module

Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.

import pandas as pd

df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]

This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.

Getting Chrome to accept self-signed localhost certificate

2020-05-22: With only 5 openssl commands, you can accomplish this.

Please do not change your browser security settings.

With the following code, you can (1) become your own CA, (2) then sign your SSL certificate as a CA. (3) Then import the CA certificate (not the SSL certificate, which goes onto your server) into Chrome/Chromium. (Yes, this works even on Linux.)

NB: For Windows, some reports say that openssl must be run with winpty to avoid a crash.

######################
# Become a Certificate Authority
######################

# Generate private key
openssl genrsa -des3 -out myCA.key 2048
# Generate root certificate
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 825 -out myCA.pem

######################
# Create CA-signed certs
######################

NAME=mydomain.com # Use your own domain name
# Generate a private key
openssl genrsa -out $NAME.key 2048
# Create a certificate-signing request
openssl req -new -key $NAME.key -out $NAME.csr
# Create a config file for the extensions
>$NAME.ext cat <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $NAME # Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.2 = bar.$NAME # Optionally, add additional domains (I've added a subdomain here)
IP.1 = 192.168.0.13 # Optionally, add an IP address (if the connection which you have planned requires it)
EOF
# Create the signed certificate
openssl x509 -req -in $NAME.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
-out $NAME.crt -days 825 -sha256 -extfile $NAME.ext

To recap:

  1. Become a CA
  2. Sign your certificate using your CA cert+key
  3. Import myCA.pem as an "Authority" (not into "Your Certificates") in your Chrome settings (Settings > Manage certificates > Authorities > Import)
  4. Use the $NAME.crt and $NAME.key files in your server

Extra steps (for Mac, at least):

  1. Import the CA cert at "File > Import file", then also find it in the list, right click it, expand "> Trust", and select "Always"
  2. Add extendedKeyUsage=serverAuth,clientAuth below basicConstraints=CA:FALSE, and make sure you set the "CommonName" to the same as $NAME when it's asking for setup

You can check your work to ensure that the certificate is built correctly:

openssl verify -CAfile myCA.pem -verify_hostname bar.mydomain.com mydomain.com.crt

What is the difference between MOV and LEA?

LEA (Load Effective Address) is a shift-and-add instruction. It was added to 8086 because hardware is there to decode and calculate adressing modes.

How to skip "are you sure Y/N" when deleting files in batch files

Add /Q for quiet mode and it should remove the prompt.

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

Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this

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

When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.

iPhone/iPad browser simulator?

XCode does come with a simulator for the iPad and iPhone.

You can also use Safari on OS X to debug websites on your iOS device.

Notice: Array to string conversion in

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.

To echo elements of array properly, you can use the function, implode(separator, array) Example:

implode(' ', $var)

result:

first name[1], last name[1]
first name[2], last name[2]

More examples from W3C.

Leave only two decimal places after the dot

yourValue.ToString("0.00") will work.

Unmarshaling nested JSON objects

Combining map and struct allow unmarshaling nested JSON objects where the key is dynamic. => map[string]

For example: stock.json

{
  "MU": {
    "symbol": "MU",
    "title": "micro semiconductor",
    "share": 400,
    "purchase_price": 60.5,
    "target_price": 70
  },
  "LSCC":{
    "symbol": "LSCC",
    "title": "lattice semiconductor",
    "share": 200,
    "purchase_price": 20,
    "target_price": 30
  }
}

Go application

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

type Stock struct {
    Symbol        string  `json:"symbol"`
    Title         string  `json:"title"`
    Share         int     `json:"share"`
    PurchasePrice float64 `json:"purchase_price"`
    TargetPrice   float64 `json:"target_price"`
}
type Account map[string]Stock

func main() {
    raw, err := ioutil.ReadFile("stock.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }
    var account Account
    log.Println(account)
}

The dynamic key in the hash is handle a string, and the nested object is represented by a struct.

regex with space and letters only?

$('#input').on('keyup', function() {
     var RegExpression = /^[a-zA-Z\s]*$/;  
     ...

});

\s will allow the space

A general tree implementation?

node = { 'parent':0, 'left':0, 'right':0 }
import copy
root = copy.deepcopy(node)
root['parent'] = -1
left = copy

just to show another thought on implementation if you stick to the "OOP"

class Node:
    def __init__(self,data):
        self.data = data
        self.child = {}
    def append(self, title, child):
        self.child[title] = child

CEO = Node( ('ceo', 1000) )
CTO = ('cto',100)
CFO = ('cfo', 10)
CEO.append('left child', CTO)
CEO.append('right child', CFO)

print CEO.data
print ' ', CEO.child['left child']
print ' ', CEO.child['right child']

How to run Node.js as a background process and never die?

Simple solution (if you are not interested in coming back to the process, just want it to keep running):

nohup node server.js &

There's also the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Powerful solution (allows you to reconnect to the process if it is interactive):

screen

You can then detach by pressing Ctrl+a+d and then attach back by running screen -r

Also consider the newer alternative to screen, tmux.

How can I make one python file run another?

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. Treat it like a module: import file. This is good because it's secure, fast, and maintainable. Code gets reused as it's supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

To solve this issue you need to run your application by increasing the memory limit by using the option --max_old_space_size. By default the memory limit of Node.js is 512 mb.

node --max_old_space_size=2000  server.js 

How do you revert to a specific tag in Git?

Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname to display the commit it points to.

In your case you have at least these two alternatives:

  1. Reset the current branch to specific tag:

    git reset --hard tagname
    
  2. Generate revert commit on top to get you to the state of the tag:

    git revert tag
    

This might introduce some conflicts if you have merge commits though.

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

For me at least, this happened when I removed a reference to an assembly and added a reference to a newer version of it, which had a different name. In this case, it seems that the old assembly remained in the bin and obj folder, and was not removed with the clean solution operation from Visual Studio (maybe because it is not part of the project anymore). In this case, it was enough to delete the contents of the bin and obj folders of the project where he error happens, from Windows Explorer (or a file management tool). Then, from Visual Studio, clean the solution and rebuild.

How to replace all dots in a string using JavaScript

Here's another implementation of replaceAll. Hope it helps someone.

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

Setting an int to Infinity in C++

You can also use INT_MAX:

http://www.cplusplus.com/reference/climits/

it's equivalent to using numeric_limits.

How to find the kth largest element in an unsorted array of length n in O(n)?

You do like quicksort. Pick an element at random and shove everything either higher or lower. At this point you'll know which element you actually picked, and if it is the kth element you're done, otherwise you repeat with the bin (higher or lower), that the kth element would fall in. Statistically speaking, the time it takes to find the kth element grows with n, O(n).

How to read a .properties file which contains keys that have a period character using Shell script

I found using while IFS='=' read -r to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop.

I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).

The solution does sourcing but massages the contents before sourcing:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

Explanation:

grep -v '^ *#': discard comment lines grep '[^ ] *=': discards lines without = split($0,a,"="): splits line at = and stores into array a, i.e. a[1] is the key, a[2] is the value gensub(/\./, "_", "g", a[1]): replaces . with _ print gensub... "=" a[2]} concatenates the result of gensub above with = and value.

Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.

Python equivalent to 'hold on' in Matlab

Just call plt.show() at the end:

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)    

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

Auto-size dynamic text to fill fixed size container

Here's an improved looping method that uses binary search to find the largest possible size that fits into the parent in the fewest steps possible (this is faster and more accurate than stepping by a fixed font size). The code is also optimized in several ways for performance.

By default, 10 binary search steps will be performed, which will get within 0.1% of the optimal size. You could instead set numIter to some value N to get within 1/2^N of the optimal size.

Call it with a CSS selector, e.g.: fitToParent('.title-span');

/**
 * Fit all elements matching a given CSS selector to their parent elements'
 * width and height, by adjusting the font-size attribute to be as large as
 * possible. Uses binary search.
 */
var fitToParent = function(selector) {
    var numIter = 10;  // Number of binary search iterations
    var regexp = /\d+(\.\d+)?/;
    var fontSize = function(elem) {
        var match = elem.css('font-size').match(regexp);
        var size = match == null ? 16 : parseFloat(match[0]);
        return isNaN(size) ? 16 : size;
    }
    $(selector).each(function() {
        var elem = $(this);
        var parentWidth = elem.parent().width();
        var parentHeight = elem.parent().height();
        if (elem.width() > parentWidth || elem.height() > parentHeight) {
            var maxSize = fontSize(elem), minSize = 0.1;
            for (var i = 0; i < numIter; i++) {
                var currSize = (minSize + maxSize) / 2;
                elem.css('font-size', currSize);
                if (elem.width() > parentWidth || elem.height() > parentHeight) {
                    maxSize = currSize;
                } else {
                    minSize = currSize;
                }
            }
            elem.css('font-size', minSize);
        }
    });
};

Address already in use: JVM_Bind

This problem mostly occurs because there could be another istance of the code running, from some previous tests you did most probably. Find out and close any other instance or if it is ok, try restarting the server.

How to reference a .css file on a razor view?

I prefer to use the razor html helper from Client Dependency dll

Html.RequireCss("yourfile", 9999); // 9999 is loading priority 

c++ and opencv get and set pixel color to Mat

You did everything except copying the new pixel value back to the image.

This line takes a copy of the pixel into a local variable:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

Break a previous commit into multiple commits

If you just want to extract something from existing commit and keep the original one, you can use

git reset --patch HEAD^

instead of git reset HEAD^. This command allows you to reset just chunks you need.

After you chose the chunks you want to reset, you'll have staged chunks that will reset changes in previous commit after you do

git commit --amend --no-edit

and unstaged chunks that you can add to the separate commit by

git add .
git commit -m "new commit"

Off topic fact:

In mercurial they have hg split - the second feature after hg absorb I'd like to see in git.

LINQ select one field from list of DTO objects to array

You can use:

var mySKUs = myLines.Select(l => l.Sku).ToList();

The Select method, in this case, performs a mapping from IEnumerable<Line> to IEnumerable<string> (the SKU), then ToList() converts it to a List<string>.

Note that this requires using System.Linq; to be at the top of your .cs file.

Get SELECT's value and text in jQuery

$('select').val()  // Get's the value

$('select option:selected').val() ; // Get's the value

$('select').find('option:selected').val() ; // Get's the value

$('select option:selected').text()  // Gets you the text of the selected option

Check FIDDLE

latex large division sign in a math formula

Another option is to use \dfrac instead of \frac, which makes the whole fraction larger and hence more readable.

And no, I don't know if there is an option to get something in between \frac and \dfrac, sorry.

Eclipse error "ADB server didn't ACK, failed to start daemon"

I had the same problem. But there was no process of adb on my laptop. I just log out and log in to my account, and it's resolved...

ADB could start from CMD windows after that.

Constructors in Go

If you want to force the factory function usage, name your struct (your class) with the first character in lowercase. Then, it won't be possible to instantiate directly the struct, the factory method will be required.

This visibility based on first character lower/upper case work also for struct field and for the function/method. If you don't want to allow external access, use lower case.

How do I get the value of text input field using JavaScript?

You can read value by

searchTxt.value

_x000D_
_x000D_
function searchURL() {
   let txt = searchTxt.value;
   console.log(txt);
   // window.location = "http://www.myurl.com/search/" + txt; ...
}

document.querySelector('.search').addEventListener("click", ()=>searchURL());
_x000D_
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

<button class="search">Search</button>
_x000D_
_x000D_
_x000D_

UPDATE

I see many downvotes but any comments - however (for future readers) actually this solution works

What is difference between functional and imperative programming languages?

There seem to be many opinions about what functional programs and what imperative programs are.

I think functional programs can most easily be described as "lazy evaluation" oriented. Instead of having a program counter iterate through instructions, the language by design takes a recursive approach.

In a functional language, the evaluation of a function would start at the return statement and backtrack, until it eventually reaches a value. This has far reaching consequences with regards to the language syntax.

Imperative: Shipping the computer around

Below, I've tried to illustrate it by using a post office analogy. The imperative language would be mailing the computer around to different algorithms, and then have the computer returned with a result.

Functional: Shipping recipes around

The functional language would be sending recipes around, and when you need a result - the computer would start processing the recipes.

This way, you ensure that you don't waste too many CPU cycles doing work that is never used to calculate the result.

When you call a function in a functional language, the return value is a recipe that is built up of recipes which in turn is built of recipes. These recipes are actually what's known as closures.

// helper function, to illustrate the point
function unwrap(val) {
  while (typeof val === "function") val = val();
  return val;
}

function inc(val) {
  return function() { unwrap(val) + 1 };
}

function dec(val) {
  return function() { unwrap(val) - 1 };
}

function add(val1, val2) {
  return function() { unwrap(val1) + unwrap(val2) }
}

// lets "calculate" something

let thirteen = inc(inc(inc(10)))
let twentyFive = dec(add(thirteen, thirteen))

// MAGIC! The computer still has not calculated anything.
// 'thirteen' is simply a recipe that will provide us with the value 13

// lets compose a new function

let doubler = function(val) {
  return add(val, val);
}

// more modern syntax, but it's the same:
let alternativeDoubler = (val) => add(val, val)

// another function
let doublerMinusOne = (val) => dec(add(val, val));

// Will this be calculating anything?

let twentyFive = doubler(thirteen)

// no, nothing has been calculated. If we need the value, we have to unwrap it:
console.log(unwrap(thirteen)); // 26

The unwrap function will evaluate all the functions to the point of having a scalar value.

Language Design Consequences

Some nice features in imperative languages, are impossible in functional languages. For example the value++ expression, which in functional languages would be difficult to evaluate. Functional languages make constraints on how the syntax must be, because of the way they are evaluated.

On the other hand, with imperative languages can borrow great ideas from functional languages and become hybrids.

Functional languages have great difficulty with unary operators like for example ++ to increment a value. The reason for this difficulty is not obvious, unless you understand that functional languages are evaluated "in reverse".

Implementing a unary operator would have to be implemented something like this:

let value = 10;

function increment_operator(value) {
  return function() {
    unwrap(value) + 1;
  }
}

value++ // would "under the hood" become value = increment_operator(value)

Note that the unwrap function I used above, is because javascript is not a functional language, so when needed we have to manually unwrap the value.

It is now apparent that applying increment a thousand times would cause us to wrap the value with 10000 closures, which is worthless.

The more obvious approach, is to actually directly change the value in place - but voila: you have introduced modifiable values a.k.a mutable values which makes the language imperative - or actually a hybrid.

Under the hood, it boils down to two different approaches to come up with an output when provided with an input.

Below, I'll try to make an illustration of a city with the following items:

  1. The Computer
  2. Your Home
  3. The Fibonaccis

Imperative Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Put The Computer into a box and mark it with a sticky note:

    Field Value
    Mail Address The Fibonaccis
    Return Address Your Home
    Parameters 3
    Return Value undefined

    and send off the computer.

  2. The Fibonaccis will upon receiving the box do as they always do:

    • Is the parameter < 2?

      • Yes: Change the sticky note, and return the computer to the post office:

        Field Value
        Mail Address The Fibonaccis
        Return Address Your Home
        Parameters 3
        Return Value 0 or 1 (returning the parameter)

        and return to sender.

      • Otherwise:

        1. Put a new sticky note on top of the old one:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, step 2, c/oThe Fibonaccis
          Parameters 2 (passing parameter-1)
          Return Value undefined

          and send it.

        2. Take off the returned sticky note. Put a new sticky note on top of the initial one and send The Computer again:

          Field Value
          Mail Address The Fibonaccis
          Return Address Otherwise, done, c/o The Fibonaccis
          Parameters 2 (passing parameter-2)
          Return Value undefined
        3. By now, we should have the initial sticky note from the requester, and two used sticky notes, each having their Return Value field filled. We summarize the return values and put it in the Return Value field of the final sticky note.

          Field Value
          Mail Address The Fibonaccis
          Return Address Your Home
          Parameters 3
          Return Value 2 (returnValue1 + returnValue2)

          and return to sender.

As you can imagine, quite a lot of work starts immediately after you send your computer off to the functions you call.

The entire programming logic is recursive, but in truth the algorithm happens sequentially as the computer moves from algorithm to algorithm with the help of a stack of sticky notes.

Functional Languages

Task: Calculate the 3rd fibonacci number. Steps:

  1. Write the following down on a sticky note:

    Field Value
    Instructions The Fibonaccis
    Parameters 3

That's essentially it. That sticky note now represents the computation result of fib(3).

We have attached the parameter 3 to the recipe named The Fibonaccis. The computer does not have to perform any calculations, unless somebody needs the scalar value.

Functional Javascript Example

I've been working on designing a programming language named Charm, and this is how fibonacci would look in that language.

fib: (n) => if (                         
  n < 2               // test
  n                   // when true
  fib(n-1) + fib(n-2) // when false
)
print(fib(4));

This code can be compiled both into imperative and functional "bytecode".

The imperative javascript version would be:

let fib = (n) => 
  n < 2 ?
  n : 
  fib(n-1) + fib(n-2);

The HALF functional javascript version would be:

let fib = (n) => () =>
  n < 2 ?
  n :
  fib(n-1) + fib(n-2);

The PURE functional javascript version would be much more involved, because javascript doesn't have functional equivalents.

let unwrap = ($) =>
  typeof $ !== "function" ? $ : unwrap($());

let $if = ($test, $whenTrue, $whenFalse) => () =>
  unwrap($test) ? $whenTrue : $whenFalse;

let $lessThen = (a, b) => () =>
  unwrap(a) < unwrap(b);

let $add = ($value, $amount) => () =>
  unwrap($value) + unwrap($amount);

let $sub = ($value, $amount) => () =>
  unwrap($value) - unwrap($amount);

let $fib = ($n) => () =>
  $if(
    $lessThen($n, 2),
    $n,
    $add( $fib( $sub($n, 1) ), $fib( $sub($n, 2) ) )
  );

I'll manually "compile" it into javascript code:

"use strict";

// Library of functions:
  /**
   * Function that resolves the output of a function.
   */
  let $$ = (val) => {
    while (typeof val === "function") {
      val = val();
    }
    return val;
  }

  /**
   * Functional if
   *
   * The $ suffix is a convention I use to show that it is "functional"
   * style, and I need to use $$() to "unwrap" the value when I need it.
   */
  let if$ = (test, whenTrue, otherwise) => () =>
    $$(test) ? whenTrue : otherwise;

  /**
   * Functional lt (less then)
   */
  let lt$ = (leftSide, rightSide)   => () => 
    $$(leftSide) < $$(rightSide)


  /**
   * Functional add (+)
   */
  let add$ = (leftSide, rightSide) => () => 
    $$(leftSide) + $$(rightSide)

// My hand compiled Charm script:

  /**
   * Functional fib compiled
   */
  let fib$ = (n) => if$(                 // fib: (n) => if(
    lt$(n, 2),                           //   n < 2
    () => n,                             //   n
    () => add$(fib$(n-2), fib$(n-1))     //   fib(n-1) + fib(n-2)
  )                                      // )

// This takes a microsecond or so, because nothing is calculated
console.log(fib$(30));

// When you need the value, just unwrap it with $$( fib$(30) )
console.log( $$( fib$(5) ))

// The only problem that makes this not truly functional, is that
console.log(fib$(5) === fib$(5)) // is false, while it should be true
// but that should be solveable

https://jsfiddle.net/819Lgwtz/42/

How to get all selected values from <select multiple=multiple>?

if you want as you expressed with breaks after each value;

$('#select-meal-type').change(function(){
    var meals = $(this).val();
    var selectedmeals = meals.join(", "); // there is a break after comma

    alert (selectedmeals); // just for testing what will be printed
})

Android: Is it possible to display video thumbnails?

I am answering this question late but hope it will help the other candidate facing same problem.

I have used two methods to load thumbnail for videos list the first was

    Bitmap bmThumbnail;
    bmThumbnail = ThumbnailUtils.createVideoThumbnail(FILE_PATH
                    + videoList.get(position),
            MediaStore.Video.Thumbnails.MINI_KIND);

    if (bmThumbnail != null) {
        Log.d("VideoAdapter","video thumbnail found");
        holder.imgVideo.setImageBitmap(bmThumbnail);
    } else {
        Log.d("VideoAdapter","video thumbnail not found");
    }

its look good but there was a problem with this solution because when i scroll video list it will freeze some time due to its large processing.

so after this i found another solution which works perfectly by using Glide Library.

 Glide
            .with( mContext )
            .load( Uri.fromFile( new File( FILE_PATH+videoList.get(position) ) ) )
            .into( holder.imgVideo );

I recommended the later solution for showing thumbnail with video list . thanks

What is the best way to implement a "timer"?

Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

How to fix Error: laravel.log could not be opened?

Add to composer.json

"scripts": {
    "post-install-cmd": [
          "chgrp -R www-data storage bootstrap/cache",
          "chmod -R ug+rwx storage bootstrap/cache"
     ]
}

After composer install

TypeError: 'module' object is not callable

Add to the main __init__.py in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass

Convert binary to ASCII and vice versa

if you don'y want to import any files you can use this:

with open("Test1.txt", "r") as File1:
St = (' '.join(format(ord(x), 'b') for x in File1.read()))
StrList = St.split(" ")

to convert a text file to binary.

and you can use this to convert it back to string:

StrOrgList = StrOrgMsg.split(" ")


for StrValue in StrOrgList:
    if(StrValue != ""):
        StrMsg += chr(int(str(StrValue),2))
print(StrMsg)

hope that is helpful, i've used this with some custom encryption to send over TCP.

Undefined reference to vtable

The GCC FAQ has an entry on it:

The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual [class.dtor]/7.

Therefore, you need to provide a definition for the virtual destructor:

virtual ~CDasherModule()
{ };

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

super() raises "TypeError: must be type, not classobj" for new-style class

You can also use class TextParser(HTMLParser, object):. This makes TextParser a new-style class, and super() can be used.

How to align td elements in center

I personally didn't find any of these answers helpful. What worked in my case was giving the element float:none and position:relative. After that the element centered itself in the <td>.

How to delete an element from an array in C#

As a generic extension, 2.0-compatible:

using System.Collections.Generic;
public static class Extensions {
    //=========================================================================
    // Removes all instances of [itemToRemove] from array [original]
    // Returns the new array, without modifying [original] directly
    // .Net2.0-compatible
    public static T[] RemoveFromArray<T> (this T[] original, T itemToRemove) {  
        int numIdx = System.Array.IndexOf(original, itemToRemove);
        if (numIdx == -1) return original;
        List<T> tmp = new List<T>(original);
        tmp.RemoveAt(numIdx);
        return tmp.ToArray();
    }
}

Usage:

int[] numbers = {1, 3, 4, 9, 2};
numbers = numbers.RemoveFromArray(4);

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

These are usually to make sure that the browser gets a new version when the site gets updated with a new version, e.g. as part of our build process we'd have something like this:

/Resources/Combined.css?v=x.x.x.buildnumber

Since this changes with every new code push, the client's forced to grab a new version, just because of the querystring. Look at this page (at the time of this answer) for example:

<link ... href="http://sstatic.net/stackoverflow/all.css?v=c298c7f8233d">

I think instead of a revision number the SO team went with a file hash, which is an even better approach, even with a new release, the browsers only forced to grab a new version when the file actually changes.

Both of these approaches allow you to set the cache header to something ridiculously long, say 20 years...yet when it changes, you don't have to worry about that cache header, the browser sees a different querystring and treats it as a different, new file.

nginx showing blank PHP pages

Make sure you've got this in /etc/nginx/fastcgi_params

fastcgi_param SCRIPT_FILENAME $request_filename;

Who knows why this isn't there already? The amount of time this must collectively waste!

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

What is setBounds and how do I use it?

This is a method of the java.awt.Component class. It is used to set the position and size of a component:

setBounds

public void setBounds(int x,
                  int y,
                  int width,
                  int height) 

Moves and resizes this component. The new location of the top-left corner is specified by x and y, and the new size is specified by width and height. Parameters:

  • x - the new x-coordinate of this component
  • y - the new y-coordinate of this component
  • width - the new width of this component
  • height - the new height of this component

x and y as above correspond to the upper left corner in most (all?) cases.

It is a shortcut for setLocation and setSize.

This generally only works if the layout/layout manager are non-existent, i.e. null.

How do I correctly clone a JavaScript object?

If you're okay with a shallow copy, the underscore.js library has a clone method.

y = _.clone(x);

or you can extend it like

copiedObject = _.extend({},originalObject);

Python: Binding Socket: "Address already in use"

socket.socket() should run before socket.bind() and use REUSEADDR as said

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

  • Assumming you tried everything reasonable (delete target, refresh, clean, rebuild, maven install...) and that you realized that Eclipse does not behave reasonable...
  • Now: Check if there is no errors suggesting it can be a plugin (any plugin) that has something to do with tests.

  • In my case:

    • I removed EclEmma.
    • It started working...

Spent few hours on trying to guess it!.

Plain Old CLR Object vs Data Transfer Object

I wrote an article for that topic: DTO vs Value Object vs POCO.

In short:

  • DTO != Value Object
  • DTO ? POCO
  • Value Object ? POCO

Git's famous "ERROR: Permission to .git denied to user"

After Googling for few days, I found this is the only question similar to my situation.

However, I just solved the problem! So I am putting my answer here to help anyone else searching for this issue.

Here is what I did:

  1. Open "Keychain Access.app" (You can find it in Spotlight or LaunchPad)

  2. Select "All items" in Category

  3. Search "git"

  4. Delete every old & strange item

  5. Try to Push again and it just WORKED

Error in launching AVD with AMD processor

For Android Studio 1.0.2:

First make sure Intel x86 emulator accelerator is installer. Check it in your SDK Manager. If not, then install it from there.

Go to your Android SDK folder, **{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager**

There you will find silent_install.bat.

Run it. It will create haxm_silent_run.log. After that, close and restart your Android Studio and then run your app.

It will work. In case of a problem, check the haxm_silent_run.log file.

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Example use of "continue" statement in Python?

It is not absolutely necessary since it can be done with IFs but it's more readable and also less expensive in run time.

I use it in order to skip an iteration in a loop if the data does not meet some requirements:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]

for time in commit_times:
    hour = time[0]
    minutes = time[1]

    # If the hour is not between 0 and 24
    # and the minutes not between 0 and 59 then we know something is wrong.
    # Then we don't want to use this value,
    # we skip directly to the next iteration in the loop.
    if not (0 <= hour <= 24 and 0 <= minutes <= 59):
        continue

    # From here you know the time format in the tuples is reliable.
    # Apply some logic based on time.
    print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

Output:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

As you can see, the wrong value did not make it after the continue statement.

How to access a dictionary element in a Django template?

you can use the dot notation:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup (e.g., foo["bar"])
  • Attribute lookup (e.g., foo.bar)
  • Method call (e.g., foo.bar())
  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.

How to position a div in bottom right corner of a browser?

This snippet works in IE7 at least

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
  #foo {
    position: fixed;
    bottom: 0;
    right: 0;
  }
</style>
</head>
<body>
  <div id="foo">Hello World</div>
</body>
</html>

What is “2's Complement”?

Two's complement is one of the way of expressing a negative number and most of the controllers and processors store a negative number in 2's complement form

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

How do I start a process from C#?

You can use the System.Diagnostics.Process.Start method to start a process. You can even pass a URL as a string and it'll kick off the default browser.

ASP.NET Identity DbContext confusion

There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
" Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"

To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:

/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
    where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
    where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
    where TKey : IEquatable<TKey>
    where TUserClaim : IdentityUserClaim<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserLogin : IdentityUserLogin<TKey>
    where TRoleClaim : IdentityRoleClaim<TKey>
    where TUserToken : IdentityUserToken<TKey>
{
    /// <summary>
    /// Initializes a new instance of <see cref="IdentityDbContext"/>.
    /// </summary>
    /// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
    public IdentityDbContext(DbContextOptions options) : base(options)
    { }

    /// <summary>
    /// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
    /// </summary>
    protected IdentityDbContext()
    { }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
    /// </summary>
    public DbSet<TUser> Users { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
    /// </summary>
    public DbSet<TUserClaim> UserClaims { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
    /// </summary>
    public DbSet<TUserLogin> UserLogins { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
    /// </summary>
    public DbSet<TUserRole> UserRoles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
    /// </summary>
    public DbSet<TUserToken> UserTokens { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
    /// </summary>
    public DbSet<TRole> Roles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
    /// </summary>
    public DbSet<TRoleClaim> RoleClaims { get; set; }

    /// <summary>
    /// Configures the schema needed for the identity framework.
    /// </summary>
    /// <param name="builder">
    /// The builder being used to construct the model for this context.
    /// </param>
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<TUser>(b =>
        {
            b.HasKey(u => u.Id);
            b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
            b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
            b.ToTable("AspNetUsers");
            b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.UserName).HasMaxLength(256);
            b.Property(u => u.NormalizedUserName).HasMaxLength(256);
            b.Property(u => u.Email).HasMaxLength(256);
            b.Property(u => u.NormalizedEmail).HasMaxLength(256);
            b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
            b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
            b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
        });

        builder.Entity<TRole>(b =>
        {
            b.HasKey(r => r.Id);
            b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
            b.ToTable("AspNetRoles");
            b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.Name).HasMaxLength(256);
            b.Property(u => u.NormalizedName).HasMaxLength(256);

            b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
            b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
        });

        builder.Entity<TUserClaim>(b => 
        {
            b.HasKey(uc => uc.Id);
            b.ToTable("AspNetUserClaims");
        });

        builder.Entity<TRoleClaim>(b => 
        {
            b.HasKey(rc => rc.Id);
            b.ToTable("AspNetRoleClaims");
        });

        builder.Entity<TUserRole>(b => 
        {
            b.HasKey(r => new { r.UserId, r.RoleId });
            b.ToTable("AspNetUserRoles");
        });

        builder.Entity<TUserLogin>(b =>
        {
            b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
            b.ToTable("AspNetUserLogins");
        });

        builder.Entity<TUserToken>(b => 
        {
            b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
            b.ToTable("AspNetUserTokens");
        });
    }
}


Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:

First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.

   public class ApplicationDbContext 
    : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}


Extra Notes:

1) We can also change asp.net Identity default table names with the following solution:

    public class ApplicationDbContext : IdentityDbContext
    {    
        public ApplicationDbContext(): base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUser>().ToTable("user");
            modelBuilder.Entity<ApplicationUser>().ToTable("user");

            modelBuilder.Entity<IdentityRole>().ToTable("role");
            modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
        }
    }

2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...

    public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() 
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public ApplicationRole(string name)
        : this()
    {
        this.Name = name;
    }

    // Add any custom Role properties/code here
}


// Must be expressed in terms of our custom types:
public class ApplicationDbContext 
    : IdentityDbContext<ApplicationUser, ApplicationRole, 
    string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}

To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.

Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

public static const in TypeScript

You can use a getter, so that your property is going to be reading only. Example:

export class MyClass {
    private _LEVELS = {
        level1: "level1",
        level2: "level2",
        level2: "level2"
    };

    public get STATUSES() {
        return this._LEVELS;
    }
}

Used in another class:

import { MyClass } from "myclasspath";
class AnotherClass {
    private myClass = new MyClass();

    tryLevel() {
       console.log(this.myClass.STATUSES.level1);
    }
}

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

You have no shell at /bin/sh? Have you tried docker run -it pensu/busybox /usr/bin/sh ?

How to count lines of Java code using IntelliJ IDEA?

To find all including empty lines of code try @Neil's solution:

Open Find in Path (Ctrl+Shift+F)

Search for the following regular expression: \n'

For lines with at least one character use following expression:

(.+)\n

For lines with at least one word character or digit use following expression:

`(.*)([\w\d]+)(.*)\n`

Notice: But the last line of file is just counted if you have a line break after it.

Should image size be defined in the img tag height/width attributes or in CSS?

Option a. Simple straight fwd. What you see is what you get easy to make calculations.

Option b. Too messy to do this inline unless you want to have a site that can stretch. IE if you used the with:86em however modern browsers seem to handle this functionally adequately for my purposes.. . Personally the only time that i would use something like this is if i were to create a thumbnails catalogue.

/*css*/
ul.myThumbs{}
ul.myThumbs li {float:left; width:50px;}
ul.myThumbs li img{width:50px; height:50px;border:0;}

<!--html-->
<ul><li>
<img src="~/img/products/thumbs/productid.jpg" alt="" />
</li></ul>

Option c. Too messy to maintain.

Is there a "not equal" operator in Python?

There's the != (not equal) operator that returns True when two values differ, though be careful with the types because "1" != 1. This will always return True and "1" == 1 will always return False, since the types differ. Python is dynamically, but strongly typed, and other statically typed languages would complain about comparing different types.

There's also the else clause:

# This will always print either "hi" or "no hi" unless something unforeseen happens.
if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.
    print "hi"     # If indeed it is the string "hi" then print "hi"
else:              # hi and "hi" are not the same
    print "no hi"

The is operator is the object identity operator used to check if two objects in fact are the same:

a = [1, 2]
b = [1, 2]
print a == b # This will print True since they have the same values
print a is b # This will print False since they are different objects.

How to get the new value of an HTML input after a keypress has modified it?

Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.

As you will see from the table, the keypress and change event do not have uniform support whereas the keyup event does.

Also make sure you attach the event handler using a cross-browser-compatible method...

Cycles in family tree software

A few answers have shown ways to keep the assertions/invariants, but this seems like a misuse of assertions/invariant. Assertions are to make sure something that should be true is true, and invariants are to make sure something that shouldn't change doesn't change.

What you're asserting here is that incestuous relationships don't exist. Clearly they do exist, so your assertion is invalid. You can work around this assertion, but the real bug is in the assertion itself. The assertion should be removed.

Laravel migration default value

You can simple put the default value using default(). See the example

 $table->enum('is_approved', array('0','1'))->default('0');

I have used enum here and the default value is 0.

passing object by reference in C++

What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

The simple answer is that declaring a function as pass-by-reference:

void foo(int& x);

is all we need. It's then passed by reference automatically.

You now call this function like so:

int y = 5;
foo(y);

and y will be passed by reference.

You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

#include <iostream>
using namespace std;

class CDummy {
public:
    int isitme (CDummy* param);
};


int CDummy::isitme (CDummy* param)
{
    if (param == this) return true;
    else return false;
}

int main () {
    CDummy a;
    CDummy* b = &a;             // assigning address of a to b
    if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
        cout << "yes, &a is b";
    return 0;
}

Output:

yes, &a is b

Turning off hibernate logging console output

To get rid of logger output in console try this.

ch.qos.logback.classic.LoggerContext.LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.LoggerFactory.getILoggerFactory();

loggerContext.stop();

These statements disabled all the console outputs from logger.

What is a unix command for deleting the first N characters of a line?

Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

function stringStripNCharsFromStart { echo ${1:$2:${#1}} }

Usage: enter image description here

C++ - Assigning null to a std::string

There are two methods to consider which achieve the same effect for handling null pointers to C-style strings.

The ternary operator

void setvalue(const char *value)
{
    std::string mValue = value ? value : "";

}

or the humble if statement

void setvalue(const char *value)
{
    std::string mValue;
    if(value) mValue = value;

}

In both cases, value is only assigned to mValue when value is not a null pointer. In all other cases (i.e. when value is null), mValue will contain an empty string.

The ternary operator method may be useful for providing an alternative default string literal in the absence of a value from value:

std::string mValue = value ? value : "(NULL)";

Failed to resolve: com.google.firebase:firebase-core:16.0.1

Since May 23, 2018 update, when you're using a firebase dependency, you must include the firebase-core dependency, too.

If adding it, you still having the error, try to update the gradle plugin in your gradle-wrapper.properties to 4.5 version:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip

and resync the project.

How to avoid page refresh after button click event in asp.net

As you are using asp:Button which is a server control, post back will happen to avoid that go for html button,

asp:Button .... />

Type to

input type="button" .... />

Creating a generic method in C#

I know, I know, but...

public static bool TryGetQueryString<T>(string key, out T queryString)

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

From the documentation:

NOTE: Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

E.g. you have to set an android:radius="<bigger than 1dp>" to be able to do what you want:

<corners 
    android:radius="2dp"
    android:bottomRightRadius="0dp" 
    android:topRightRadius="0dp"/> 

Change font size of UISegmentedControl

In swift 5,

let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

In Flask, What is request.args and how is it used?

It has some interesting behaviour in some cases that is good to be aware of:

from werkzeug.datastructures import MultiDict

d = MultiDict([("ex1", ""), ("ex2", None)])

d.get("ex1", "alternive")
# returns: ''

d.get("ex2", "alternative")
# returns no visible output of any kind
# It is returning literally None, so if you do:
d.get("ex2", "alternative") is None
# it returns: True

d.get("ex3", "alternative")
# returns: 'alternative'

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

sqlite3.OperationalError: unable to open database file

Primary diagnosis: SQLite is unable to open that file for some reason.

Checking the obvious reasons why, and in approximate order that I recommend checking:

  • Is the program running on the same machine as you're testing it?
  • Is it running as you (or at least the same user as you're testing it as)?
  • Is the disk containing /tmp full? (You're on Unix, so use df /tmp to find out.)
  • Does the /tmp/cer directory have “odd” permissions? (SQLite needs to be able to create additional files in it in order to handle things like the commit log.)
  • Is the unit test code still using that database? (Concurrent opens are possible with a modern-enough SQLite and when in the right filesystem — though /tmp is virtually always on the right sort of FS so it's probably not that — but it's still not recommended.)
  • Is the development code really trying to write to that database, or is something “clever” catching you out and causing it to try to open something else? (I've been caught out by this in my code in the past; don't think it can't happen to you…)
  • Are you using the same version of the SQLite library in the unit tests and the production code?

If you're not on the same machine, it's quite possible that the production system doesn't have a /tmp/cer directory. Obvious to fix that first. Similarly, if you're on the same machine but running as different users, you're likely to have permissions/ownership problems. Disk space is another serious gotcha, but less likely. I don't think it's the last three, but they're worth checking if the more obvious deployment problems are sorted. If it's none of the above, you've hit an exotic problem and will have to report much more info (it might even be a bug in SQLite, but knowing the developers of it, I believe that to be quite unlikely).

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

Python 3.1.1 string to hex

Yet another method:

s = 'hello'

h = ''.join([hex(ord(i)) for i in s]);

# outputs: '0x680x650x6c0x6c0x6f'

This basically splits the string into chars, does the conversion through hex(ord(char)), and joins the chars back together. In case you want the result without the prefix 0x then do:

h = ''.join([str(hex(ord(i)))[2:4] for i in s]);

# outputs: '68656c6c6f'

Tested with Python 3.5.3.

Meaning of Choreographer messages in Logcat

In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.

You can hide the Choreographer outputs onto the Logcat view, using this filter expression :

tag:^((?!Choreographer).*)$

I used a regex explained elsewhere : Regular expression to match a line that doesn't contain a word?

How do I check if a PowerShell module is installed?

The current version of Powershell has a Get-InstalledModule function that suits this purpose well (or at least it did in my case).

Get-InstalledModule

Description

The Get-InstalledModule cmdlet gets PowerShell modules that are installed on a computer.

The only issue with it is that it throws an exception if the module that is being requested doesn't exist, so we need to set ErrorAction appropriately to suppress that case.

if ((Get-InstalledModule `
    -Name "AzureRm.Profile" `
    -MinimumVersion 5.0 ` # Optionally specify minimum version to have
    -ErrorAction SilentlyContinue) -eq $null) {

    # Install it...
}

Android Calling JavaScript functions in WebView

public void run(final String scriptSrc) { 
        webView.post(new Runnable() {
            @Override
            public void run() { 
                webView.loadUrl("javascript:" + scriptSrc); 
            }
        }); 
    }

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

If you did not uncheck offline work, then make you sure you have internet for Android Studio to normalize your project.

Does reading an entire file leave the file handle open?

Well, if you have to read file line by line to work with each line, you can use

with open('Path/to/file', 'r') as f:
    s = f.readline()
    while s:
        # do whatever you want to
        s = f.readline()

Or even better way:

with open('Path/to/file') as f:
    for line in f:
        # do whatever you want to

Base64 decode snippet in C++

Using base-n mini lib, you can do the following:

some_data_t in[] { ... };
constexpr int len = sizeof(in)/sizeof(in[0]);

std::string encoded;
bn::encode_b64(in, in + len, std::back_inserter(encoded));

some_data_t out[len];
bn::decode_b64(encoded.begin(), encoded.end(), out);

The API is generic, iterator-based.

Disclosure: I'm the author.

'ssh-keygen' is not recognized as an internal or external command

Are you running msysgit, or some other form of Windows git installation? msysgit is only one possible way to run git on Windows but it's probably also the simplest one. It's also the way recommended by the git website at http://git-scm.org/ .

If you are using msysgit, then you need to run the command in Git Bash, not in a standard Windows command line prompt. Git Bash is a prompt that is installed for you by msysgit, and is basically the most common Linux command line shell (bash) packaged for Windows to facilitate command line usage of git. msysgit should also install the ssh-keygen program in a place where it is accessible from Git Bash, but not necessarily from your usual Windows command line prompt.

How to set bootstrap navbar active class with Angular JS?

If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://stackoverflow.com/a/16231859/910764.

JavaScript

angular.module('myApp').directive('bsNavbar', ['$location', function ($location) {
  return {
    restrict: 'A',
    link: function postLink(scope, element) {
      scope.$watch(function () {
        return $location.path();
      }, function (path) {
        angular.forEach(element.children(), (function (li) {
          var $li = angular.element(li),
            regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
            isActive = regex.test(path);
          $li.toggleClass('active', isActive);
        }));
      });
    }
  };
}]);

HTML

<ul class="nav navbar-nav" bs-navbar>
  <li data-match-route="/home"><a href="#/home">Home</a></li>
  <li data-match-route="/about"><a href="#/about">About</a></li>
</ul>

Note: The above HTML classes assume you are using Bootstrap 3.x

Complex nesting of partials and templates

You may use ng-include to avoid using nested ng-views.

http://docs.angularjs.org/api/ng/directive/ngInclude
http://plnkr.co/edit/ngdoc:example-example39@snapshot?p=preview

My index page I use ng-view. Then on my sub pages which I need to have nested frames. I use ng-include. The demo shows a dropdown. I replaced mine with a link ng-click. In the function I would put $scope.template = $scope.templates[0]; or $scope.template = $scope.templates[1];

$scope.clickToSomePage= function(){
  $scope.template = $scope.templates[0];
};

How to make a smooth image rotation in Android?

Rotation Object programmatically.

// clockwise rotation :

    public void rotate_Clockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 180f, 0f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    }

// AntiClockwise rotation :

 public void rotate_AntiClockwise(View view) {
        ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 0f, 180f);
//        rotate.setRepeatCount(10);
        rotate.setDuration(500);
        rotate.start();
    } 

view is object of your ImageView or other widgets.

rotate.setRepeatCount(10); use to repeat your rotation.

500 is your animation time duration.

Bootstrap Navbar toggle button not working

Demo: http://jsfiddle.net/u1s62Lj8/1/

You need the jQuery and Boostrap Javascript files included in your HTML page for the toggle to work. (Make sure you include jQuery before Bootstrap.)

<html>
   <head>
       // stylesheets here
       <link rel="stylesheet" href=""/> 
   </head>
   <body>
      //your html code here

      // js scripts here
      // note jquery tag has to go before boostrap
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
   </body>
</html>

How to add a class to body tag?

You can extract that part of the URL using a simple regular expression:

var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);

How do I use this JavaScript variable in HTML?

Try this:

<body>
    <div id="divMsg"></div>
</body>
<script>
    var name = prompt("What's your name?");
    var lengthOfName = name.length;
    document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

Windows 7 environment variable not working in path

%M2% and %JAVA_HOME% need to be added to a PATH variable in the USER variables, not the SYSTEM variables.

Unicode character as bullet for list-item in CSS

ul {
    list-style-type: none;    
}

ul li:before {
    content:'*'; /* Change this to unicode as needed*/
    width: 1em !important;
    margin-left: -1em;
    display: inline-block;
}

How to do this using jQuery - document.getElementById("selectlist").value

Chaos is spot on, though for these sorts of questions you should check out the Jquery Documentation online - it really is quite comprehensive. The feature you are after is called 'jquery selectors'

Generally you do $('#ID').val() - the .afterwards can do a number of things on the element that is returned from the selector. You can also select all of the elements on a certain class and do something to each of them. Check out the documentation for some good examples.

Import text file as single character string

How about:

string <- readChar("foo.txt",nchars=1e6)

How do I generate a random number between two variables that I have stored?

Really fast, really easy:

srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.

And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random header to avoid that bias like so:

#include <random>

std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased

int r = gen(rng);

But you can also remove the bias in normal C++ like this:

int rangeRandomAlg2 (int min, int max){
    int n = max - min + 1;
    int remainder = RAND_MAX % n;
    int x;
    do{
        x = rand();
    }while (x >= RAND_MAX - remainder);
    return min + x % n;
}

and that was gotten from this post.

Invalid syntax when using "print"?

The syntax is changed in new 3.x releases rather than old 2.x releases: for example in python 2.x you can write: print "Hi new world" but in the new 3.x release you need to use the new syntax and write it like this: print("Hi new world")

check the documentation: http://docs.python.org/3.3/library/functions.html?highlight=print#print

Colouring plot by factor in R

The col argument in the plot function assign colors automatically to a vector of integers. If you convert iris$Species to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:

plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))

Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:

plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])

You can probably see how to further modify the code above to get any unique combination of colors.

Understanding __get__ and __set__ and Python descriptors

Before going into the details of descriptors it may be important to know how attribute lookup in Python works. This assumes that the class has no metaclass and that it uses the default implementation of __getattribute__ (both can be used to "customize" the behavior).

The best illustration of attribute lookup (in Python 3.x or for new-style classes in Python 2.x) in this case is from Understanding Python metaclasses (ionel's codelog). The image uses : as substitute for "non-customizable attribute lookup".

This represents the lookup of an attribute foobar on an instance of Class:

enter image description here

Two conditions are important here:

  • If the class of instance has an entry for the attribute name and it has __get__ and __set__.
  • If the instance has no entry for the attribute name but the class has one and it has __get__.

That's where descriptors come into it:

  • Data descriptors which have both __get__ and __set__.
  • Non-data descriptors which only have __get__.

In both cases the returned value goes through __get__ called with the instance as first argument and the class as second argument.

The lookup is even more complicated for class attribute lookup (see for example Class attribute lookup (in the above mentioned blog)).

Let's move to your specific questions:

Why do I need the descriptor class?

In most cases you don't need to write descriptor classes! However you're probably a very regular end user. For example functions. Functions are descriptors, that's how functions can be used as methods with self implicitly passed as first argument.

def test_function(self):
    return self

class TestClass(object):
    def test_method(self):
        ...

If you look up test_method on an instance you'll get back a "bound method":

>>> instance = TestClass()
>>> instance.test_method
<bound method TestClass.test_method of <__main__.TestClass object at ...>>

Similarly you could also bind a function by invoking its __get__ method manually (not really recommended, just for illustrative purposes):

>>> test_function.__get__(instance, TestClass)
<bound method test_function of <__main__.TestClass object at ...>>

You can even call this "self-bound method":

>>> test_function.__get__(instance, TestClass)()
<__main__.TestClass at ...>

Note that I did not provide any arguments and the function did return the instance I had bound!

Functions are Non-data descriptors!

Some built-in examples of a data-descriptor would be property. Neglecting getter, setter, and deleter the property descriptor is (from Descriptor HowTo Guide "Properties"):

class Property(object):
    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

Since it's a data descriptor it's invoked whenever you look up the "name" of the property and it simply delegates to the functions decorated with @property, @name.setter, and @name.deleter (if present).

There are several other descriptors in the standard library, for example staticmethod, classmethod.

The point of descriptors is easy (although you rarely need them): Abstract common code for attribute access. property is an abstraction for instance variable access, function provides an abstraction for methods, staticmethod provides an abstraction for methods that don't need instance access and classmethod provides an abstraction for methods that need class access rather than instance access (this is a bit simplified).

Another example would be a class property.

One fun example (using __set_name__ from Python 3.6) could also be a property that only allows a specific type:

class TypedProperty(object):
    __slots__ = ('_name', '_type')
    def __init__(self, typ):
        self._type = typ

    def __get__(self, instance, klass=None):
        if instance is None:
            return self
        return instance.__dict__[self._name]

    def __set__(self, instance, value):
        if not isinstance(value, self._type):
            raise TypeError(f"Expected class {self._type}, got {type(value)}")
        instance.__dict__[self._name] = value

    def __delete__(self, instance):
        del instance.__dict__[self._name]

    def __set_name__(self, klass, name):
        self._name = name

Then you can use the descriptor in a class:

class Test(object):
    int_prop = TypedProperty(int)

And playing a bit with it:

>>> t = Test()
>>> t.int_prop = 10
>>> t.int_prop
10

>>> t.int_prop = 20.0
TypeError: Expected class <class 'int'>, got <class 'float'>

Or a "lazy property":

class LazyProperty(object):
    __slots__ = ('_fget', '_name')
    def __init__(self, fget):
        self._fget = fget

    def __get__(self, instance, klass=None):
        if instance is None:
            return self
        try:
            return instance.__dict__[self._name]
        except KeyError:
            value = self._fget(instance)
            instance.__dict__[self._name] = value
            return value

    def __set_name__(self, klass, name):
        self._name = name

class Test(object):
    @LazyProperty
    def lazy(self):
        print('calculating')
        return 10

>>> t = Test()
>>> t.lazy
calculating
10
>>> t.lazy
10

These are cases where moving the logic into a common descriptor might make sense, however one could also solve them (but maybe with repeating some code) with other means.

What is instance and owner here? (in __get__). What is the purpose of these parameters?

It depends on how you look up the attribute. If you look up the attribute on an instance then:

  • the second argument is the instance on which you look up the attribute
  • the third argument is the class of the instance

In case you look up the attribute on the class (assuming the descriptor is defined on the class):

  • the second argument is None
  • the third argument is the class where you look up the attribute

So basically the third argument is necessary if you want to customize the behavior when you do class-level look-up (because the instance is None).

How would I call/use this example?

Your example is basically a property that only allows values that can be converted to float and that is shared between all instances of the class (and on the class - although one can only use "read" access on the class otherwise you would replace the descriptor instance):

>>> t1 = Temperature()
>>> t2 = Temperature()

>>> t1.celsius = 20   # setting it on one instance
>>> t2.celsius        # looking it up on another instance
20.0

>>> Temperature.celsius  # looking it up on the class
20.0

That's why descriptors generally use the second argument (instance) to store the value to avoid sharing it. However in some cases sharing a value between instances might be desired (although I cannot think of a scenario at this moment). However it makes practically no sense for a celsius property on a temperature class... except maybe as purely academic exercise.

How to set the matplotlib figure default size in ipython notebook?

I believe the following work in version 0.11 and above. To check the version:

$ ipython --version

It may be worth adding this information to your question.

Solution:

You need to find the file ipython_notebook_config.py. Depending on your installation process this should be in somewhere like

.config/ipython/profile_default/ipython_notebook_config.py

where .config is in your home directory.

Once you have located this file find the following lines

# Subset of matplotlib rcParams that should be different for the inline backend.
# c.InlineBackend.rc = {'font.size': 10, 'figure.figsize': (6.0, 4.0), 'figure.facecolor': 'white', 'savefig.dpi': 72, 'figure.subplot.bottom': 0.125, 'figure.edgecolor': 'white'}

Uncomment this line c.InlineBack... and define your default figsize in the second dictionary entry.

Note that this could be done in a python script (and hence interactively in IPython) using

pylab.rcParams['figure.figsize'] = (10.0, 8.0)

Sort JavaScript object by key

The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.


See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:

All methods that iterate over property keys do so in the same order:

  1. First all Array indices, sorted numerically.
  2. Then all string keys (that are not indices), in the order in which they were created.
  3. Then all symbols, in the order in which they were created.

So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.

Here’s how you can sort an object by its keys/properties, alphabetically:

_x000D_
_x000D_
const unordered = {
  'b': 'foo',
  'c': 'bar',
  'a': 'baz'
};

console.log(JSON.stringify(unordered));
// ? '{"b":"foo","c":"bar","a":"baz"}'

const ordered = Object.keys(unordered).sort().reduce(
  (obj, key) => { 
    obj[key] = unordered[key]; 
    return obj;
  }, 
  {}
);

console.log(JSON.stringify(ordered));
// ? '{"a":"baz","b":"foo","c":"bar"}'
_x000D_
_x000D_
_x000D_

Use var instead of const for compatibility with ES5 engines.

How to read a config file using python

You need a section in your file:

[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third

Then, read the properties:

import ConfigParser

config = ConfigParser.ConfigParser()
config.readfp(open(r'abc.txt'))
path1 = config.get('My Section', 'path1')
path2 = config.get('My Section', 'path2')
path3 = config.get('My Section', 'path3')

update query with join on two tables

Try this one

UPDATE employee 
set EMPLOYEE.MAIDEN_NAME = 
  (SELECT ADD1 
   FROM EMPS 
   WHERE EMP_CODE=EMPLOYEE.EMP_CODE);
WHERE EMPLOYEE.EMP_CODE >='00' 
AND EMPLOYEE.EMP_CODE <='ZZ';

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

If you have an issue, you need to locate your pg_hba.conf. The command is:

find / -name 'pg_hba.conf' 2>/dev/null

and after that change the configuration file:

Postgresql 9.3

Postgresql 9.3

Postgresql 9.4

Postgresql 9.3

The next step is: Restarting your db instance:

service postgresql-9.3 restart

If you have any problems, you need to set password again:

ALTER USER db_user with password 'db_password';

How are ssl certificates verified?

I KNOW THE BELOW IS LONG, BUT IT IS DETAILED, YET SIMPLIFIED ENOUGH. READ CAREFULLY AND I GUARANTEE YOU'LL START FINDING THIS TOPIC IS NOT ALL THAT COMPLICATED.

First of all, anyone can create 2 keys. One to encrypt data, and another to decrypt data. The former can be a private key, and the latter a public key, AND VICERZA.

Second of all, in simplest terms, a Certificate Authority (CA) offers the service of creating a certificate for you. How? They use certain values (the CA's issuer name, your server's public key, company name, domain, etc.) and they use their SUPER DUPER ULTRA SECURE SECRET private key and encrypt this data. The result of this encrypted data is a SIGNATURE.

So now the CA gives you back a certificate. The certificate is basically a file containing the values previously mentioned (CA's issuer name, company name, domain, your server's public key, etc.), INCLUDING the signature (i.e. an encrypted version of the latter values).

Now, with all that being said, here is a REALLY IMPORTANT part to remember: your device/OS (Windows, Android, etc.) pretty much keeps a list of all major/trusted CA's and their PUBLIC KEYS (if you're thinking that these public keys are used to decrypt the signatures inside the certificates, YOU ARE CORRECT!).

Ok, if you read the above, this sequential example will be a breeze now:

  1. Example-Company asks Example-CA to create for them a certificate.
  2. Example-CA uses their super private key to sign this certificate and gives Example-Company the certificate.
  3. Tomorrow, internet-user-Bob uses Chrome/Firefox/etc. to browse to https://example-company.com. Most, if not all, browsers nowadays will expect a certificate back from the server.
  4. The browser gets the certificate from example-company.com. The certificate says it's been issued by Example-CA. It just so happens to be that Bob's OS already has Example-CA in its list of trusted CA's, so the browser gets Example-CA's public key. Remember: this is all happening in Bob's computer/mobile/etc., not over the wire.
  5. So now the browser decrypts the signature in the certificate. FINALLY, the browser compares the decrypted values with the contents of the certificate itself. IF THE CONTENTS MATCH, THAT MEANS THE SIGNATURE IS VALID!

Why? Think about it, only this public key can decrypt the signature in such a way that the contents look like they did before the private key encrypted them.

How about man in the middle attacks?

This is one of the main reasons (if not the main reason) why the above standard was created.

Let's say hacker-Jane intercepts internet-user-Bob's request, and replies with her own certificate. However, hacker-Jane is still careful enough to state in the certificate that the issuer was Example-CA. Lastly, hacker-Jane remembers that she has to include a signature on the certificate. But what key does Jane use to sign (i.e. create an encrypted value of the certificate main contents) the certificate?????

So even if hacker-Jane signed the certificate with her own key, you see what's gonna happen next. The browser is gonna say: "ok, this certificate is issued by Example-CA, let's decrypt the signature with Example-CA's public key". After decryption, the browser notices that the certificate contents don't match at all. Hence, the browser gives a very clear warning to the user, and it says it doesn't trust the connection.

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

Get year, month or day from numpy datetime64

Anon's answer works great for me, but I just need to modify the statement for days

from:

days = dates - dates.astype('datetime64[M]') + 1

to:

days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1

How to get the selected row values of DevExpress XtraGrid?

var rowHandle = gridView.FocusedRowHandle;

var obj = gridView.GetRowCellValue(rowHandle, "FieldName");

//For example  
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));

http://localhost/phpMyAdmin/ unable to connect

Your web server isn't running! You need to find the XAMPP control panel and start the web server up.

Of course, you might find other problems after that, but this is the first step.

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Example template for C++

template< class T >
T mod( T a, T b )
{
    T const r = a%b;
    return ((r!=0)&&((r^b)<0) ? r + b : r);
}

With this template, the returned remainder will be zero or have the same sign as the divisor (denominator) (the equivalent of rounding towards negative infinity), instead of the C++ behavior of the remainder being zero or having the same sign as the dividend (numerator) (the equivalent of rounding towards zero).

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Fan out was clearly what you wanted. fanout

read rabbitMQ tutorial: https://www.rabbitmq.com/tutorials/tutorial-three-javascript.html

here's my example:

Publisher.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create exchange for queues
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      await channel.publish(process.env.EXCHANGE_NAME, '', Buffer.from('msg'))
    } catch(error) {
      console.error(error)
    }
})

Subscriber.js:

amqp.connect('amqp://<user>:<pass>@<host>:<port>', async (error0, connection) => {
    if (error0) {
      throw error0;
    }
    console.log('RabbitMQ connected')
    try {
      // Create/Bind a consumer queue for an exchange broker
      channel = await connection.createChannel()
      await channel.assertExchange(process.env.EXCHANGE_NAME, 'fanout', { durable: false });
      const queue = await channel.assertQueue('', {exclusive: true})
      channel.bindQueue(queue.queue, process.env.EXCHANGE_NAME, '')

      console.log(" [*] Waiting for messages in %s. To exit press CTRL+C");
      channel.consume('', consumeMessage, {noAck: true});
    } catch(error) {
      console.error(error)
    }
});

here is an example i found in the internet. maybe can also help. https://www.codota.com/code/javascript/functions/amqplib/Channel/assertExchange

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

How to recover stashed uncommitted changes

The easy answer to the easy question is git stash apply

Just check out the branch you want your changes on, and then git stash apply. Then use git diff to see the result.

After you're all done with your changes—the apply looks good and you're sure you don't need the stash any more—then use git stash drop to get rid of it.

I always suggest using git stash apply rather than git stash pop. The difference is that apply leaves the stash around for easy re-try of the apply, or for looking at, etc. If pop is able to extract the stash, it will immediately also drop it, and if you the suddenly realize that you wanted to extract it somewhere else (in a different branch), or with --index, or some such, that's not so easy. If you apply, you get to choose when to drop.

It's all pretty minor one way or the other though, and for a newbie to git, it should be about the same. (And you can skip all the rest of this!)


What if you're doing more-advanced or more-complicated stuff?

There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":

  1. You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.

    This is the easy case, described above. Run git stash save (or plain git stash, same thing). Check out the other branch and use git stash apply. This gets git to merge in your earlier changes, using git's rather powerful merge mechanism. Inspect the results carefully (with git diff) to see if you like them, and if you do, use git stash drop to drop the stash. You're done!

  2. You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.

    Now you want to keep, or even move, these changes, and apply your stash too.

    You can in fact git stash save again, as git stash makes a "stack" of changes. If you do that you have two stashes, one just called stash—but you can also write stash@{0}—and one spelled stash@{1}. Use git stash list (at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop, it drops the newest, and the one that was stash@{1} moves to the top of the stack. If you had even more, the one that was stash@{2} becomes stash@{1}, and so on.

    You can apply and then drop a specific stash, too: git stash apply stash@{2}, and so on. Dropping a specific stash, renumbers only the higher-numbered ones. Again, the one without a number is also stash@{0}.

    If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@{7} or was it stash@{4}? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December means a lot more to me than stash@{12}. (The git stash command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch.)

  3. (Extra-advanced) You've used git stash save -p, or carefully git add-ed and/or git rm-ed specific bits of your code before running git stash save. You had one version in the stashed index/staging area, and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index, and that sometimes fails with:

    Conflicts in index.  Try without --index.
    
  4. You're using git stash save --keep-index in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.

For complicated cases, I recommend starting in a "clean" working directory first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:

git status               # see if there's anything you need to commit
                         # uh oh, there is - let's put it on a new temp branch
git checkout -b temp     # create new temp branch to save stuff
git add ...              # add (and/or remove) stuff as needed
git commit               # save first set of changes

Now you're on a "clean" starting point. Or maybe it goes more like this:

git status               # see if there's anything you need to commit
                         # status says "nothing to commit"
git checkout -b temp     # optional: create new branch for "apply"
git stash apply          # apply stashed changes; see below about --index

The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply operation looks at what the commit changed, and tries to repeat it wherever you are now. The stash will still be there (apply keeps it around), so you can look at it more, or decide this was the wrong place to apply it and try again differently, or whatever.


Any time you have a stash, you can use git stash show -p to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index restores separately.) The command git stash apply, without --index, just tries to make those same changes in your work-directory now.

This is true even if you already have some changes. The apply command is happy to apply a stash to a modified working directory (or at least, to try to apply it). You can, for instance, do this:

git stash apply stash      # apply top of stash stack
git stash apply stash@{1}  # and mix in next stash stack entry too

You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:

Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.

If you start with a clean directory and are just doing several git apply operations, it's easy to back out: use git reset --hard to get back to the clean state, and change your apply operations. (That's why I recommend starting in a clean working directory first, for these complicated cases.)


What about the very worst possible case?

Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index, but it's no longer possible to apply the saved stash with --index, because the branch has diverged too much since the time you saved it.

This is what git stash branch is for.

If you:

  1. check out the exact commit you were on when you did the original stash, then
  2. create a new branch, and finally
  3. git stash apply --index

the attempt to re-create the changes definitely will work. This is what git stash branch newbranch does. (And it then drops the stash since it was successfully applied.)


Some final words about --index (what the heck is it?)

What the --index does is simple to explain, but a bit complicated internally:

  • When you have changes, you have to git add (or "stage") them before commiting.
  • Thus, when you ran git stash, you might have edited both files foo and zorg, but only staged one of those.
  • So when you ask to get the stash back, it might be nice if it git adds the added things and does not git add the non-added things. That is, if you added foo but not zorg back before you did the stash, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.

The --index flag to apply tries to set things up this way. If your work-tree is clean, this usually just works. If your work-tree already has stuff added, though, you can see how there might be some problems here. If you leave out --index, the apply operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes git's merge machinery, using the work-tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index makes it a lot easier for git stash apply to do its thing.

How do I convert uint to int in C#?

Given:

 uint n = 3;

int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only 
                           //i will be negative if n > Int32.MaxValue

int i = (int)n; //same behavior as unchecked

or

int i = Convert.ToInt32(n); //same behavior as checked

--EDIT

Included info as mentioned by Kenan E. K.

Iterating through all the cells in Excel VBA or VSTO 2005

You can use a For Each to iterate through all the cells in a defined range.

Public Sub IterateThroughRange()

Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range

Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")

For Each cell In rng.Cells
    cell.Value = cell.Address
Next cell

End Sub

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

List myArrayList  = Collections.synchronizedList(new ArrayList());

//add your elements  
 myArrayList.add();
 myArrayList.add();
 myArrayList.add();

synchronized(myArrayList) {
    Iterator i = myArrayList.iterator(); 
     while (i.hasNext()){
         Object  object = i.next();
     }
 }

Remove the string on the beginning of an URL

You can overload the String prototype with a removePrefix function:

String.prototype.removePrefix = function (prefix) {
    const hasPrefix = this.indexOf(prefix) === 0;
    return hasPrefix ? this.substr(prefix.length) : this.toString();
};

usage:

const domain = "www.test.com".removePrefix("www."); // test.com

How to easily get network path to the file you are working on?

In Win7 (and Vista I think), you can Shift+Right Click the file in question and select Copy as path to get the full network path. Note: if the shared drive is mapped to a letter, you will get that path instead (ie: X:\someguy\somefile.xls)

Razor-based view doesn't see referenced assemblies

Try adding the namespace your MyClasses is in to the web.config under

<pages> <namespaces></namespaces> </pages>

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.