Programs & Examples On #Jdic

JDIC is the Java Desktop Integration Components (JDIC) project, an attempt to improve Java apps' access to the underlying OS' facilities.

How do I configure Apache 2 to run Perl CGI scripts?

There are two ways to handle CGI scripts, SetHandler and AddHandler.

SetHandler cgi-script

applies to all files in a given context, no matter how they are named, even index.html or style.css.

AddHandler cgi-script .pl

is similar, but applies to files ending in .pl, in a given context. You may choose another extension or several, if you like.

Additionally, the CGI module must be loaded and Options +ExecCGI configured. To activate the module, issue

a2enmod cgi

and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set

chmod a+x

and it should start with

#! /usr/bin/perl

as its first line.

When you use SetHandler or AddHandler (and Options +ExecCGI) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory

<Directory /path/to/some/cgi-dir>
    SetHandler cgi-script
    Options +ExecCGI

Now SetHandler applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler inside a Directory or Location directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl.

Differences between key, superkey, minimal superkey, candidate key and primary key

Largely based on the accepted answer, but with a few tweaks to fit better the definitions taught in some courses:

  • Key: A set of = 1 columns.
  • Superkey: A key that ? a candidate key.
    • Therefore, a superkey must contain > 1 columns.
    • Minimal Super key = Candidate Key: A key that can uniquely identify each row in a table.
    • Primary Key: The chosen Candidate Key for doing that.
    • Secondary key / Alternate key: A Candidate Key not chosen for doing that.
  • Search Key: A key used for locating records.
  • Composite key or concatenate key: A key with > 1 columns.
    • Usually implies "composite primary key", although "composite alternate key" is also a thing.
  • Sort or control key: A key used to physically sequence the stored data.
  • Foreign Key A key in one table that matches the Primary Key of another table.
    • The table in which foreign key resides is called as dependent table.
    • The table to which foreign key refers is known as parent table.

Java/ JUnit - AssertTrue vs AssertFalse

I think it's just for your convenience (and the readers of your code)

Your code, and your unit tests should be ideally self documenting which this API helps with,

Think abt what is more clear to read:

AssertTrue(!(a > 3));


AssertFalse(a > 3);

When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

MVC: How to Return a String as JSON

The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.

What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).

I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.

return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here, 
//  or if that is done automatically

Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.

SQLite DateTime comparison

To solve this problem, I store dates as YYYYMMDD. Thus, where mydate >= '20090101' and mydate <= '20050505'

It just plain WORKS all the time. You may only need to write a parser to handle how users might enter their dates so you can convert them to YYYYMMDD.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JFrame;

public class Graphiic
    public Graphics GClass;
    public Graphics2D G2D;
    public  void Draw_Circle(JFrame jf,int radius , int  xLocation, int yLocation)
        GClass = jf.getGraphics();
        GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360);
        GClass.drawLine(100, 100, 200, 200);    


Intent.putExtra List

you can do it in two ways using

  • Serializable

  • Parcelable.

This examle will show you how to implement it with serializable

class Customer implements Serializable
   // properties, getter setters & constructor

// This is your custom object
Customer customer = new Customer(name, address, zip);

Intent intent = new Intent();
intent.setClass(SourceActivity.this, TargetActivity.this);
intent.putExtra("customer", customer);

// Now in your TargetActivity
Bundle extras = getIntent().getExtras();
if (extras != null)
    Customer customer = (Customer)extras.getSerializable("customer");
    // do something with the customer

Now have a look at this. This link will give you a brief overview of how to implement it with Parcelable.

Look at this.. This discussion will let you know which is much better way to implement it.


Running npm command within Visual Studio Code

You have to do the following 3 steps to fix your issues:

1.Download Node.js from here.

  1. Install it and then add the path C:\Program Files\nodejs to your System variables.

  2. Then restart your visual studio code editor.

Happy code

How to load up CSS files using Javascript?


document.getElementById("of head/body tag")
        .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

For Chrome:

  1. Set your email manager to Gmail

gmail handler

  1. Write mailto: in the address bar and press enter.


  1. Edit search engines:

Edit search engines

Edit search engines

  1. Write mt and enter in address bar.

How to do encryption using AES in Openssl

I am trying to write a sample program to do AES encryption using Openssl.

This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.

First, don't use AES_encrypt and AES_decrypt. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.

Instead, use the EVP_* interfaces. The EVP_* functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.

Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)

Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.

Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>   

int main(int arc, char *argv[])

    /* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */

    /* A 256 bit key */
    static const unsigned char key[] = "01234567890123456789012345678901";

    /* A 128 bit IV */
    static const unsigned char iv[] = "0123456789012345";

    /* Message to be encrypted */
    unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";

    /* Some additional data to be authenticated */
    static const unsigned char aad[] = "Some AAD data";

    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    /* Buffer for the tag */
    unsigned char tag[16];

    int decryptedtext_len = 0, ciphertext_len = 0;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp(stdout, ciphertext, ciphertext_len);
    printf("Tag is:\n");
    BIO_dump_fp(stdout, tag, 14);

    /* Mess with stuff */
    /* ciphertext[0] ^= 1; */
    /* tag[0] ^= 1; */

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);

    if(decryptedtext_len < 0)
        /* Verify error */
        printf("Decrypted text failed to verify\n");
        /* Add a NULL terminator. We are expecting printable text */
        decryptedtext[decryptedtext_len] = '\0';

        /* Show the decrypted text */
        printf("Decrypted text is:\n");
        printf("%s\n", decryptedtext);

    /* Remove error strings */

    return 0;

void handleErrors(void)
    unsigned long errCode;

    printf("An error occurred\n");
    while(errCode = ERR_get_error())
        char *err = ERR_error_string(errCode, NULL);
        printf("%s\n", err);

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
            int aad_len, unsigned char *key, unsigned char *iv,
            unsigned char *ciphertext, unsigned char *tag)
    int len = 0, ciphertext_len = 0;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the encryption operation. */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))

    /* Set IV length if default 12 bytes (96 bits) is not appropriate */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))

    /* Initialise key and IV */
    if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
    if(aad && aad_len > 0)
        if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))

    /* Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
        if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))

        ciphertext_len = len;

    /* Finalise the encryption. Normally ciphertext bytes may be written at
     * this stage, but this does not occur in GCM mode
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
    ciphertext_len += len;

    /* Get the tag */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))

    /* Clean up */

    return ciphertext_len;

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
            int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
            unsigned char *plaintext)
    int len = 0, plaintext_len = 0, ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
    if(aad && aad_len > 0)
        if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
        if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))

        plaintext_len = len;

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */

    if(ret > 0)
        /* Success */
        plaintext_len += len;
        return plaintext_len;
        /* Verify failed */
        return -1;

Editing dictionary values in a foreach loop

You can make a list copy of the dict.Values, then you can use the List.ForEach lambda function for iteration, (or a foreach loop, as suggested before).

new List<string>(myDict.Values).ForEach(str =>
  //Use str in any other way you need here.

Can't connect to local MySQL server through socket homebrew

You'll need to run mysql_install_db - easiest way is if you're in the install directory:

$ cd /usr/local/Cellar/mysql/<version>/ 
$ mysql_install_db

Alternatively, you can feed mysql_install_db a basedir parameter like the following:

$ mysql_install_db --basedir="$(brew --prefix mysql)"

javascript: Disable Text Select

Simple Copy this text and put on the before </body>

function disableselect(e) {
  return false

function reEnable() {
  return true

document.onselectstart = new Function ("return false")

if (window.sidebar) {
  document.onmousedown = disableselect
  document.onclick = reEnable

Separating class code into a header and cpp file

You leave the declarations in the header file:

class A2DD
  int gx;
  int gy;

    A2DD(int x,int y); // leave the declarations here
    int getSum();

And put the definitions in the implementation file.

A2DD::A2DD(int x,int y) // prefix the definitions with the class name
  gx = x;
  gy = y;

int A2DD::getSum()
  return gx + gy;

You could mix the two (leave getSum() definition in the header for instance). This is useful since it gives the compiler a better chance at inlining for example. But it also means that changing the implementation (if left in the header) could trigger a rebuild of all the other files that include the header.

Note that for templates, you need to keep it all in the headers.

HTML "overlay" which allows clicks to fall through to elements behind it

You can use an overlay with opacity set in order to the buttons/anchors in the back stay visible, but once you have that overlay over an element, you can't click it.

How to install a specific version of Node on Ubuntu?

It is possible to install specific version of nodejs from nodejs official distribution with using dpkg.

For example, currently recent 4.x version is 4.2.4, but you can install previous 4.2.3 version.

curl -s -O
sudo apt-get install rlwrap
sudo dpkg -i nodejs_4.2.3-1nodesource1~trusty1_amd64.deb

How to center a "position: absolute" element

html, body, ul, li, img {_x000D_
  box-sizing: border-box;_x000D_
  margin: 0px;  _x000D_
  padding: 0px;  _x000D_
#slideshowWrapper {_x000D_
  width: 25rem;_x000D_
  height: auto;_x000D_
  position: relative;_x000D_
  margin-top: 50px;_x000D_
  border: 3px solid black;_x000D_
ul {_x000D_
  list-style: none;_x000D_
  border: 3px solid blue;  _x000D_
li {_x000D_
  /* center horizontal */_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  top: 50%;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  font-size: 18px;_x000D_
  /* center horizontal */_x000D_
  border: 3px solid red; _x000D_
img {_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 4px;_x000D_
  //width: 200px;_x000D_
  height: 100px;_x000D_
  <div id="slideshowWrapper">_x000D_
    <ul id="slideshow">_x000D_
      <li><img src="" alt="Dummy 1" /></li>_x000D_
      <li><img src="" alt="Dummy 2" /></li>_x000D_
      <li><img src="" alt="Dummy 3" /></li>      _x000D_

adding child nodes in treeview

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

i faced the same problem but i solved it by moving the chromedriver to this path '/opt/google/chrome/'

and this code works correctly

from selenium.webdriver import Chrome
driver = Chrome('/opt/google/chrome/chromedrive')

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

Command to get time in milliseconds

date command didnt provide milli seconds on OS X, so used an alias from python

millis(){  python -c "import time; print(int(time.time()*1000))"; }


alias millis='python -c "import time; print(int(time.time()*1000))"'

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

$ time date +%s%N
date +%s%N  0.00s user 0.00s system 63% cpu 0.006 total

Python is still improving it's VM start time, and it is not as fast as ahead-of-time compiled code (such as date).

On my machine, it took about 30ms - 60ms (that is 5x-10x of 6ms taken by date)

$ time python -c "import time; print(int(time.time()*1000))"
python -c "import time; print(int(time.time()*1000))"  0.03s user 0.01s system 83% cpu 0.053 total

I figured awk is lightweight than python, so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

$ time awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'
awk '@load "time"; BEGIN{print int(1000 * gettimeofday())}'  0.00s user 0.00s system 74% cpu 0.010 total

How to remove the Flutter debug banner?

To remove the flutter debug banner, there are several possibilities :

1- The first one is to use the debugShowCheckModeBanner property in your MaterialApp widget .

Code :

  debugShowCheckedModeBanner: false,

And then do a hot reload.

2-The second possibility is to hide debug mode banner in Flutter Inspector if you use Android Studio or IntelliJ IDEA .

enter image description here

3- The third possibility is to use Dart DevTools .

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

anaconda/conda - install a specific package version

There is no version 1.3.0 for rope. 1.3.0 refers to the package cached-property. The highest available version of rope is 0.9.4.

You can install different versions with conda install package=version. But in this case there is only one version of rope so you don't need that.

The reason you see the cached-property in this listing is because it contains the string "rope": "cached-p rope erty"

py35_0 means that you need python version 3.5 for this specific version. If you only have python3.4 and the package is only for version 3.5 you cannot install it with conda.

I am not quite sure on the defaults either. It should be an indication that this package is inside the default conda channel.

How to check if a variable is not null?

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

I used all above changes but still I was getting same issue on my web application.

Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.

They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.

Hope this answer will help someone.This is what worked for me

Pandas - How to flatten a hierarchical index in columns

Andy Hayden's answer is certainly the easiest way -- if you want to avoid duplicate column labels you need to tweak a bit

In [34]: df
     USAF   WBAN  day  month  s_CD  s_CL  s_CNT  s_PC  tempf         year
                               sum   sum    sum   sum   amax   amin      
0  702730  26451    1      1    12     0     13     1  30.92  24.98  1993
1  702730  26451    2      1    13     0     13     0  32.00  24.98  1993
2  702730  26451    3      1     2    10     13     1  23.00   6.98  1993
3  702730  26451    4      1    12     0     13     1  10.04   3.92  1993
4  702730  26451    5      1    10     0     13     3  19.94  10.94  1993

In [35]: mi = df.columns

In [36]: mi
[(USAF, ), (WBAN, ), (day, ), (month, ), (s_CD, sum), (s_CL, sum), (s_CNT, sum), (s_PC, sum), (tempf, amax), (tempf, amin), (year, )]

In [37]: mi.tolist()
[('USAF', ''),
 ('WBAN', ''),
 ('day', ''),
 ('month', ''),
 ('s_CD', 'sum'),
 ('s_CL', 'sum'),
 ('s_CNT', 'sum'),
 ('s_PC', 'sum'),
 ('tempf', 'amax'),
 ('tempf', 'amin'),
 ('year', '')]

In [38]: ind = pd.Index([e[0] + e[1] for e in mi.tolist()])

In [39]: ind
Out[39]: Index([USAF, WBAN, day, month, s_CDsum, s_CLsum, s_CNTsum, s_PCsum, tempfamax, tempfamin, year], dtype=object)

In [40]: df.columns = ind

In [46]: df
     USAF   WBAN  day  month  s_CDsum  s_CLsum  s_CNTsum  s_PCsum  tempfamax  tempfamin  \
0  702730  26451    1      1       12        0        13        1      30.92      24.98   
1  702730  26451    2      1       13        0        13        0      32.00      24.98   
2  702730  26451    3      1        2       10        13        1      23.00       6.98   
3  702730  26451    4      1       12        0        13        1      10.04       3.92   
4  702730  26451    5      1       10        0        13        3      19.94      10.94   

0  1993  
1  1993  
2  1993  
3  1993  
4  1993

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Sometimes the files are actually located at ~/. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.

  • cd ~/

  • vim .bashrc

  • Paste the following...

if test -t 1; then exec zsh fi

  • Save/close Vim.

  • Restart the terminal

Get elements by attribute when querySelectorAll is not available without using libraries?


//find first element with "someAttr" attribute


//find all elements with "someAttr" attribute

to find elements by attribute. It's now supported in all relevant browsers (even IE8):

How do I run a single test using Jest?

You can also use f or x to focus or exclude a test. For example

fit('only this test will run', () => {

it('this test will not run', () => {

xit('this test will be ignored', () => {

How to fix missing dependency warning when using useEffect React Hook?

you try this way

const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      .then(rcvdBusinesses => {
        // some stuff
      .catch(err => {
        // some error handling


useEffect(() => {

it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:

useEffect(() => {
        const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      .then(rcvdBusinesses => {
        // some stuff
      .catch(err => {
        // some error handling
      }, []);

if you get data on the base of specific id then add in callback useEffect [id] then cannot show you warning React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array

Amazon S3 exception: "The specified key does not exist"

Step 1: Get the latest aws-java-sdk

<!-- -->

Step 2: The correct imports

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;

If you are sure the bucket exists, Specified key does not exists error would mean the bucketname is not spelled correctly ( contains slash or special characters). Refer the documentation for naming convention.

The document quotes:

If the requested object is available in the bucket and users are still getting the 404 NoSuchKey error from Amazon S3, check the following:

Confirm that the request matches the object name exactly, including the capitalization of the object name. Requests for S3 objects are case sensitive. For example, if an object is named myimage.jpg, but Myimage.jpg is requested, then requester receives a 404 NoSuchKey error. Confirm that the requested path matches the path to the object. For example, if the path to an object is awsexamplebucket/Downloads/February/Images/image.jpg, but the requested path is awsexamplebucket/Downloads/February/image.jpg, then the requester receives a 404 NoSuchKey error. If the path to the object contains any spaces, be sure that the request uses the correct syntax to recognize the path. For example, if you're using the AWS CLI to download an object to your Windows machine, you must use quotation marks around the object path, similar to: aws s3 cp "s3://awsexamplebucket/Backup Copy Job 4/3T000000.vbk". Optionally, you can enable server access logging to review request records in further detail for issues that might be causing the 404 error.

AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ObjectListing objects = s3Client.listObjects("bigdataanalytics");

Document directory path of Xcode Device Simulator

Despite the fact that here are many answers, none of them provides an understanding of how the folder structure of the iOS 8.3 simulators have changed and are not providing a quick way to find the App's Data (Documents folder).

Since iOS 8 the Data storage folder(s) of an App are separate from the App's executable files while the iOS 7 and below are having the same folder structure, the only difference being the fact that all the simulators (different types and versions) are now in one, big folder.

So, the path to an iOS 8,7,6 simulator is the following:


Every simulator is now contained in a folder named with an unique identifier which changes at every reset of a simulator.

You can find the Identifier for each of your devices & simulators by going to Xcode > Window > Devices (the first 3 or 4 characters of the identifier are more than enough to remember).

To find the one on which you have installed your app(s) on, take a look at your Run scheme > devices (screen 2).

screen 1

screen 2

Now, after you identify your simulator, depending on its version the folder structure is very different:

On iOS 8 the executable and the data folder of an app are in different folders:

Executable: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Bundle/Application/[appID]

Data Folder: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Data/Application/[appID]/

Documents Folder: ~/Library/Developer/CoreSimulator/Devices/[simID]/data/Containers/Data/Application/[appID]/Documents

On iOS 7 and below the folder structure is the same as before only remember that now every simulator is in the same folder (see above).

difference between variables inside and outside of __init__()

This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

VBA for clear value in specific range of cell and protected cell from being wash away formula

Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:

  1. Ctrl-G
  2. A1:X50 Enter
  3. Delete

Unless you have to do this very often, entering and then triggering the VBAcode is more effort.

And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S to select Goto Special and here select Formulas or Values.

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

convert pfx format to p12

Run this command to change .cert file to .p12:

openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt 

Where server.key is the server key and server.cert is a CA issue cert or a self sign cert file.

Import Libraries in Eclipse?

For the Android library projects, I do it as in the attached screenshot:

Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.

If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.

Adding a library

How to add a progress bar to a shell script?

Got an easy progress bar function that i wrote the other day:

# 1. Create ProgressBar function
# 1.1 Input is currentState($1) and totalState($2)
function ProgressBar {
# Process data
    let _progress=(${1}*100/${2}*100)/100
    let _done=(${_progress}*4)/10
    let _left=40-$_done
# Build progressbar string lengths
    _fill=$(printf "%${_done}s")
    _empty=$(printf "%${_left}s")

# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:                           
# Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"


# Variables

# This accounts as the "totalState" variable for the ProgressBar function

# Proof of concept
for number in $(seq ${_start} ${_end})
    sleep 0.1
    ProgressBar ${number} ${_end}
printf '\nFinished!\n'

Or snag it from,

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Mongoimport of json file

I was able to fix the error using the following query:

mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray

Hopefully this is helpful to someone.

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

Unresponsive KeyListener for JFrame

Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.

I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):

public class MyFrame extends JFrame {
    public MyFrame() {
        addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {

            public void keyReleased(KeyEvent e) {

            public void keyTyped(KeyEvent e) {

    public static void main(String[] args) {
        MyFrame f = new MyFrame();

Swift do-try-catch syntax

I suspect this just hasn’t been implemented properly yet. The Swift Programming Guide definitely seems to imply that the compiler can infer exhaustive matches 'like a switch statement'. It doesn’t make any mention of needing a general catch in order to be exhaustive.

You'll also notice that the error is on the try line, not the end of the block, i.e. at some point the compiler will be able to pinpoint which try statement in the block has unhandled exception types.

The documentation is a bit ambiguous though. I’ve skimmed through the ‘What’s new in Swift’ video and couldn’t find any clues; I’ll keep trying.


We’re now up to Beta 3 with no hint of ErrorType inference. I now believe if this was ever planned (and I still think it was at some point), the dynamic dispatch on protocol extensions probably killed it off.

Beta 4 Update:

Xcode 7b4 added doc comment support for Throws:, which “should be used to document what errors can be thrown and why”. I guess this at least provides some mechanism to communicate errors to API consumers. Who needs a type system when you have documentation!

Another update:

After spending some time hoping for automatic ErrorType inference, and working out what the limitations would be of that model, I’ve changed my mind - this is what I hope Apple implements instead. Essentially:

// allow us to do this:
func myFunction() throws -> Int

// or this:
func myFunction() throws CustomError -> Int

// but not this:
func myFunction() throws CustomErrorOne, CustomErrorTwo -> Int

Yet Another Update

Apple’s error handling rationale is now available here. There have also been some interesting discussions on the swift-evolution mailing list. Essentially, John McCall is opposed to typed errors because he believes most libraries will end up including a generic error case anyway, and that typed errors are unlikely to add much to the code apart from boilerplate (he used the term 'aspirational bluff'). Chris Lattner said he’s open to typed errors in Swift 3 if it can work with the resilience model.

check if variable empty

You can check if it's not set (or empty) in a number of ways.

if (!$var){ }


if ($var === null){ } // This checks if the variable, by type, IS null.


if (empty($var)){ }

You can check if it's declared with:

if (!isset($var)){ }

Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.

How to pick element inside iframe using document.getElementById

use contentDocument to achieve this

var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument) 
               ? iframe.contentDocument 
               : iframe.contentWindow.document;

var ulObj = innerDoc.getElementById("ID_TO_SEARCH");

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)

The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

What does the "More Columns than Column Names" error mean?

you have have strange characters in your heading # % -- or ,

What is the size of an enum in C?

Taken from the current C Standard (C99): Enumeration specifiers
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

Not that compilers are any good at following the standard, but essentially: If your enum holds anything else than an int, you're in deep "unsupported behavior that may come back biting you in a year or two" territory.

Update: The latest publicly available draft of the C Standard (C11): contains the same clauses. Hence, this answer still holds for C11.

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        error: function (textStatus, errorThrown) {
            Success = false;
    //done after here
    return Success;

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call


jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")

     function Callback(data)

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

How to download videos from youtube on java?

I know i am answering late. But this code may useful for some one. So i am attaching it here.

Use the following java code to download the videos from YouTube.

package com.mycompany.ytd;

import com.github.axet.vget.VGet;

 * @author Manindar
public class YTD {

    public static void main(String[] args) {
        try {
            String url = "";
            String path = "D:\\Manindar\\YTD\\";
            VGet v = new VGet(new URL(url), new File(path));
        } catch (Exception e) {
            throw new RuntimeException(e);

Add the below Dependency in your POM.XML file


Hope this will be useful.

How to add a title to a html select tag

With a default option having selected attribute

        <option value="" selected>Choose your city</option>
        <option value ="sydney">Sydney</option>
        <option value ="melbourne">Melbourne</option>
        <option value ="cromwell">Cromwell</option>
        <option value ="queenstown">Queenstown</option>

How to use JavaScript to change div backgroundColor

You can try this script. :)

    <title>Div BG color</title>
    <script type="text/javascript">
    function Off(idecko)
    document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
    function cOn(idecko)
    document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
    function hOn(idecko)
    document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->

    <div id="catestory">

        <div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
          <h2 id="h21">some title here</h2>
          <p>some content here</p>

        <div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
          <h2 id="h22">some title here</h2>
          <p>some content here</p>

        <div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
          <h2 id="h23">some title here</h2>
          <p>some content here</p>



View the change history of a file using Git versioning

I wrote git-playback for this exact purpose

pip install git-playback
git playback [filename]

This has the benefit of both displaying the results in the command line (like git log -p) while also letting you step through each commit using the arrow keys (like gitk).

Check if SQL Connection is Open or Closed

you can also use this

if (SQLCON.State == ConnectionState.Closed)

Entity Framework change connection at runtime

DbContext has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:

public class MyDbContext : DbContext
    public MyDbContext( string nameOrConnectionString ) 
        : base( nameOrConnectionString )

Then simply pass the name of a configured connection string or a connection string itself when you instantiate your DbContext

var context = new MyDbContext( "..." );

selectOneMenu ajax events

You could check whether the value of your selectOneMenu component belongs to the list of subjects.


public void subjectSelectionChanged() {
    // Cancel if subject is manually written
    if (!subjectList.contains(aktNachricht.subject)) { return; }
    // Write your code here in case the user selected (or wrote) an item of the list
    // ....

Supposedly subjectList is a collection type, like ArrayList. Of course here your code will run in case the user writes an item of your selectOneMenu list.

ng if with angular for string contains

Do checks like that in a controller function. Your HTML should be easy-to-read markup without logic.


    var self = this; = { /* ... */ };

    self.showFoo = function() {
        //Checks if contains the character '?'
        return'?') != -1;

Page example:

<div ng-app="myApp" ng-controller="myController as vm">
    <p ng-show="vm.showFoo()">Bar</p>

C#: Dynamic runtime cast

This should work:

public static dynamic Cast(dynamic obj, Type castTo)
    return Convert.ChangeType(obj, castTo);


I've written the following test code:

var x = "123";
var y = Cast(x, typeof(int));
var z = y + 7;
var w = Cast(z, typeof(string)); // w == "130"

It does resemble the kind of "typecasting" one finds in languages like PHP, JavaScript or Python (because it also converts the value to the desired type). I don't know if that's a good thing, but it certainly works... :-)

Python POST binary data

you need to add Content-Disposition header, smth like this (although I used mod-python here, but principle should be the same):

request.headers_out['Content-Disposition'] = 'attachment; filename=%s' % myfname

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

How to remove the underline for anchors(links)?

Sometime it will override by some rendering UI CSS. Better to use:

a.className {
    text-decoration: none !important;

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

  template: `
      <li *ngFor="let number of numbers">{{number}}</li>
export class SampleComponent {

Or shortly:

  template: `
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
export class SampleComponent {

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

Reading an Excel file in python using pandas

Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:

import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])

Since .sheet_names returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Conflict with dependency '' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Adding this to build.gradle (Module app) worked for me:
compile ''

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById


<div id = 'One' onclick = " = 'Two'; return false;">One</div>

You can see it here:

Tested with Mozilla Firefox 22 and Google Chrome 60.0

Does Java SE 8 have Pairs or Tuples?

Since Java 9, you can create instances of Map.Entry easier than before:

Entry<Integer, String> pair = Map.entry(1, "a");

Map.entry returns an unmodifiable Entry and forbids nulls.

How to read file using NPOI

Simple read example below:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;


private void button1_Click(object sender, EventArgs e)
    HSSFWorkbook hssfwb;
    using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
        hssfwb= new HSSFWorkbook(file);

    ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 0; row <= sheet.LastRowNum; row++)
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
            MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));

By the way: on NPOI website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet. :)

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

## [1] "\\["
## [1] "\\\\"

For more examples see:


Your problem can be solved this way:

grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

Turn off constraints temporarily (MS SQL)

Disabling and Enabling All Foreign Keys

CREATE PROCEDURE pr_Disable_Triggers_v2
    @disable BIT = 1
    DECLARE @sql VARCHAR(500)
        ,   @tableName VARCHAR(128)
        ,   @tableSchema VARCHAR(128)

    -- List of all tables
    DECLARE triggerCursor CURSOR FOR
        SELECT  t.TABLE_NAME AS TableName
            ,   t.TABLE_SCHEMA AS TableSchema

    OPEN    triggerCursor
    FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
    WHILE ( @@FETCH_STATUS = 0 )

        SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
        IF @disable = 1
            SET @sql = @sql + ' DISABLE TRIGGER ALL'
            SET @sql = @sql + ' ENABLE TRIGGER ALL'

        PRINT 'Executing Statement - ' + @sql
        EXECUTE ( @sql )

        FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema


    CLOSE triggerCursor
    DEALLOCATE triggerCursor

First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:

0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missing

Inside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.

see Disabling Constraints and Triggers from MSDN Magazine

Angular EXCEPTION: No provider for Http

Add HttpModule to imports array in app.module.ts file before you use it.

import { HttpModule } from '@angular/http';_x000D_
  declarations: [_x000D_
  imports: [_x000D_
 HttpModule  _x000D_
  providers: [],_x000D_
  bootstrap: [AppComponent]_x000D_
export class AppModule { }

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

for win xp


  1. [windows key] + R, type services.msc, search for the running instance of "Windows Presentation Foundation (WPF) Font Cache". For my case its 4.0. Stop the service.
  2. [windows key] + R, type C:\Documents and Settings\LocalService\Local Settings\Application Data\, delete all font cache files.
  3. Start the "Windows Presentation Foundation (WPF) Font Cache" service.

How to display JavaScript variables in a HTML page without document.write

Element.innerHTML is pretty much the way to go. Here are a few ways to use it:


<div class="results"></div>


// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';

// Using the jQuery library
$('.results').html('Hello World!');

If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.

<div class="content">Hello <span class='value'></span></div>

Then I'd use some code like this:

// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';

// Using the jQuery library
$(".content .value").html("World!");

Then the HTML/DOM would now contain:

<div class="content">Hello <span class='value'>World!</span></div>

Full example. Click run snippet to try it out.

// Plain Javascript Example_x000D_
var $jsName = document.querySelector('.name');_x000D_
var $jsValue = document.querySelector('.jsValue');_x000D_
$jsName.addEventListener('input', function(event){_x000D_
  $jsValue.innerHTML = $jsName.value;_x000D_
}, false);_x000D_
// JQuery example_x000D_
var $jqName = $('.name');_x000D_
var $jqValue = $('.jqValue');_x000D_
$jqName.on('input', function(event){_x000D_
html {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 16px;_x000D_
h1 {_x000D_
  margin: 1em 0 0.25em 0;_x000D_
input[type=text] {_x000D_
  padding: 0.5em;_x000D_
.jsValue, .jqValue {_x000D_
  color: red;_x000D_
<!DOCTYPE html>_x000D_
<script src=""></script>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>Setting HTML content example</title>_x000D_
  <!-- This <input> field is where I'm getting the name from -->_x000D_
  <label>Enter your name: <input class="name" type="text" value="World"/></label>_x000D_
  <!-- Plain Javascript Example -->_x000D_
  <h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>_x000D_
  <!-- jQuery Example -->_x000D_
  <h1>jQuery Example</h1>Hello <span class="jqValue">World</span>_x000D_

Example of Mockito's argumentCaptor

The two main differences are:

  • when you capture even a single argument, you are able to make much more elaborate tests on this argument, and with more obvious code;
  • an ArgumentCaptor can capture more than once.

To illustrate the latter, say you have:

final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);

verify(x, times(4)).someMethod(captor.capture()); // for instance

Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.

This or any number of arguments in fact, since a VerificationMode is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.

This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatchers -- particularly if you combine mockito with assertj.

Oh, and please consider using TestNG instead of JUnit.

Rotating videos with FFmpeg

Smartphone: Recored a video in vertical format

Want to send it to a webside it was 90° to the left (anti clockwise, landscape format) hmm.

ffmpeg -i input.mp4 -vf "rotate=0" output.mp4

does it. I got vertical format back again

debian buster: ffmpeg --version ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers

How do I get the collection of Model State Errors in ASP.NET MVC?

Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:

    var errors =
    from item in ModelState
    where item.Value.Errors.Count > 0
    select item.Key;
    var keys = errors.ToArray();


What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".

Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
  ... (more cards/collapsibles inside #accordion parent)

Bootstrap 3

See this issue on GitHub:

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">


As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (

Abstract variables in Java?

Change the code to:

public abstract class clsAbstractTable {
  protected String TAG;
  public abstract void init();

public class clsContactGroups extends clsAbstractTable {
  public String doSomething() {
    return TAG + "<something else>";

That way, all of the classes who inherit this class will have this variable. You can do 200 subclasses and still each one of them will have this variable.

Side note: do not use CAPS as variable name; common wisdom is that all caps identifiers refer to constants, i.e. non-changeable pieces of data.

How to add footnotes to GitHub-flavoured Markdown?

I wasn't able to get Surya's and Matteo's solutions to work. For example, "(#f1)" was just displayed as text, and didn't become a link. However, their solutions led me to slightly different solution. (I also formatted the footnote and the link back to the original superscript a bit differently.)

In the body of the text:

Yadda yadda<a href="#note1" id="note1ref"><sup>1</sup></a>

At the end of the document:

<a id="note1" href="#note1ref"><sup>1</sup></a>Here is the footnote text.

Clicking on the superscript in the footnote returns to the superscript in the original text.

How do I list loaded plugins in Vim?

The problem with :scriptnames, :commands, :functions, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.

To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.

Resize jqGrid when browser is resized?

If you:

  • have shrinkToFit: false (mean fixed width columns)
  • have autowidth: true
  • don't care about fluid height
  • have horizontal scrollbar

You can make grid with fluid width with following styles:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;

.ui-jqgrid-bdiv {
   width: auto !important;

Here is a demo

Bootstrap 4 - Glyphicons migration?

It is not shipped with bootstrap 4 yet, but now Bootstrap team is developing their icon library.

Best data type to store money values in MySQL

We use double.



Because it can represent any 15 digit number with no constraints on where the decimal point is. All for a measly 8 bytes!

So it can represent:

  • 0.123456789012345
  • 123456789012345.0

...and anything in between.

This is useful because we're dealing with global currencies, and double can store the various numbers of decimal places we'll likely encounter.

A single double field can represent 999,999,999,999,999s in Japanese yens, 9,999,999,999,999.99s in US dollars and even 9,999,999.99999999s in bitcoins

If you try doing the same with decimal, you need decimal(30, 15) which costs 14 bytes.


Of course, using double isn't without caveats.

However, it's not loss of accuracy as some tend to point out. Even though double itself may not be internally exact to the base 10 system, we can make it exact by rounding the value we pull from the database to its significant decimal places. If needed that is. (e.g. If it's going to be outputted, and base 10 representation is required.)

The caveats are, any time we perform arithmetic with it, we need to normalize the result (by rounding it to its significant decimal places) before:

  1. Performing comparisons on it.
  2. Writing it back to the database.

Another kind of caveat is, unlike decimal(m, d) where the database will prevent programs from inserting a number with more than m digits, no such validations exists with double. A program could insert a user inputted value of 20 digits and it'll end up being silently recorded as an inaccurate amount.

Svn switch from trunk to branch

In my case, I wanted to check out a new branch that has cut recently but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network

so I copped the previous branch that I already checked in

I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help)

svn switch ^/branches/newBranchName

go check svn info again you can see it is becoming the newBranchName go ahead and svn up

and this how I got the new branch easily, quickly with minimum data transmitting over the internet

hope sharing my case helps and speeds up your work

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.


B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at and you will be serving your application off of your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

How to create .ipa file using Xcode?

In Xcode-11.2.1

You might be see different pattern for uploading IPA

i) Add your apple developer id in xcode preference -> account

ii)Clean Build Folder :-

enter image description here

iii) Archive

enter image description here

iv) Tap on Distribute App

enter image description here

v) Choose Ad-hoc to distribute on designated device

enter image description here

6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)

enter image description here

enter image description here

7)Click on export and you get ipa.

enter image description here

8)Visit & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)

Gaussian fit for Python

Here is corrected code:

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')

enter image description here

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      <div class="modal-body">
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

If you're using Bootstrap 2, you'd follow the markup here:

How to use glyphicons in bootstrap 3.0

Include the fonts Copy over all the font files to a /fonts directory near your CSS.

  1. Include the CSS or LESS You have two options for enabling the fonts in your project: vanilla CSS or source LESS. For vanilla CSS, just include the compiled CSS file from the /css in the repository.
  2. For LESS, copy over the .less files from /less into your existing Bootstrap directory. Then import it into bootstrap.less via @import "bootstrap-glyphicons.less";. Recompile when ready.
  3. Add some icons! After you've added the fonts and CSS, you can get to using the icons. For example, <span class="glyphicon glyphicon-ok"></span>


Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

Creating a static class with no instances

Seems that you need classmethod:

class World(object):

    allAirports = []

    def initialize(cls):

        if not cls.allAirports:
            f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
            file_reader = csv.reader(f)

            for col in file_reader:

        return cls.allAirports

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

On MongoDB 4.4+ and on CentOS 8, I found the path by running:

grep dbPath /etc/mongod.conf

jQuery AJAX form data serialize using PHP

<script src=""></script>_x000D_
    var form=$("#myForm");_x000D_
            success: function(response){_x000D_
                console.log(response);  _x000D_

This is perfect code , there is no problem.. You have to check that in php script.

C char* to int conversion

atoi can do that for you


char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234

Where can I view Tomcat log files in Eclipse?

Another forum provided this answer:

Ahh, figured this out. The following system properties need to be set, so that the "" file can be picked up.

Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:


HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.


with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource


For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:


If you use npm and nodejs, you can install json package by running this command:

npm install -g json


curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson


curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.


curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json


curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools


curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils


curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy


curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file


curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

How to remove outliers from a dataset

data_clean <- data[data$attribute >=x[1] & data$attribute<=x[2],]

I find this very easy to remove outliers. In the above example I am just extracting 2 percentile to 98 percentile of attribute values.

Start index for iterating Python list

stdlib will hook you up son!



from collections import deque

a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])

Set environment variables from file of key/value pairs

The problem with source is that it requires the file to have a proper bash syntax, and some special characters will ruin it: =, ", ', <, >, and others. So in some cases you can't just

source development.env

This version, however, withstands every special character in values:

set -a
source <(cat development.env | \
    sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a


  • -a means that every bash variable would become an environment variable
  • /^#/d removes comments (strings that start with #)
  • /^\s*$/d removes empty strings, including whitespace
  • "s/'/'\\\''/g" replaces every single quote with '\'', which is a trick sequence in bash to produce a quote :)
  • "s/=\(.*\)/='\1'/g" converts every a=b into a='b'

As a result, you are able to use special characters :)

To debug this code, replace source with cat and you'll see what this command produces.

What's the Kotlin equivalent of Java's String[]?

you can use too:

val frases = arrayOf("texto01","texto02 ","anotherText","and ")

for example.

Android SDK Setup under Windows 7 Pro 64 bit

just press the back button and then next button...jdk found :D

Installing Python 2.7 on Windows 8

How to install Python / Pip on Windows Steps

  1. Visit the official Python download page and grab the Windows installer for the latest version of Python 3.
  2. Run the installer. Be sure to check the option to add Python to your PATH while installing.

  3. Open PowerShell as admin by right clicking on the PowerShell icon and selecting ‘Run as Admin’

  4. To solve permission issues, run the following command:

Set-ExecutionPolicy Unrestricted

  1. Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this: C:\Python35-32;C:\Python35-32\Lib\site-packages\;C:\Python35-32\Scripts\

  2. download the bootstrap scripts for easy_install and pip from

  3. Save both the files in Python Installed folder Go to Python folder and run following: Python Python

  4. To create a Virtual Environment, use the following commands:

cd c:\python pip install virtualenv virtualenv test .\test\Scripts\activate.ps1 pip install IPython ipython3 Now You can install any Python package with pip

That’s it !! happy coding Visit This link for Easy steps of Installation python and pip in windows

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

How to play a sound using Swift?

Swift 4, 4.2 and 5

Play audio from URL and from your project (Local File)

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
// call what ever function you want.

    private func playAudioFromURL() {
        guard let url = URL(string: "") else {
            print("error to get the mp3 file")
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")


JavaScript post request like a form submit

The easiest way is using Ajax Post Request:

    type: "POST",
    url: '',
    data: data,
    success: success,
    dataType: dataType


  • data is an object
  • dataType is the data expected by the server (xml, json, script, text, html)
  • url is the address of your RESt server or any function on the server side that accept the HTTP-POST.

Then in the success handler redirect the browser with something like window.location.

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.

readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;

        function receivedBinary() {
            showResult(fr, "Binary");

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).

* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

DateTimePicker time picker in 24 hour but displaying in 12hr?

You can also use the parameters "use24hours" and "language" to do this, as follows:

$(function () {_x000D_
        language: 'pt-br',_x000D_
        use24hours: true,_x000D_

What are native methods in Java and where should they be used?

Java native code necessities:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

How to set timer in android?

If you have delta time already.

public class Timer {
    private float lastFrameChanged;
    private float frameDuration;
    private Runnable r;

    public Timer(float frameDuration, Runnable r) {
        this.frameDuration = frameDuration;
        this.lastFrameChanged = 0;
        this.r = r;

    public void update(float dt) {
        lastFrameChanged += dt;

        if (lastFrameChanged > frameDuration) {
            lastFrameChanged = 0;

How can I split a string into segments of n characters?

var str = 'abcdefghijkl';_x000D_

Note: Use {1,3} instead of just {3} to include the remainder for string lengths that aren't a multiple of 3, e.g:

console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]

A couple more subtleties:

  1. If your string may contain newlines (which you want to count as a character rather than splitting the string), then the . won't capture those. Use /[\s\S]{1,3}/ instead. (Thanks @Mike).
  2. If your string is empty, then match() will return null when you may be expecting an empty array. Protect against this by appending || [].

So you may end up with:

var str = 'abcdef \t\r\nghijkl';_x000D_
var parts = str.match(/[\s\S]{1,3}/g) || [];_x000D_
console.log(''.match(/[\s\S]{1,3}/g) || []);

How do you get a timestamp in JavaScript?

var timestamp = Number(new Date()); // current time as number

Left Join With Where Clause

The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.

ID and NAME columns are from the right side table, so are returned.

Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".

The below would return the result you were expecting:

    SELECT  a.*, b.Score
FROM    @Table1 a
    LEFT JOIN @Table2 b
       ON a.ID = b.T1_ID 
AND a.Name = 'Flow'

The SQL applies a filter on the right hand table.

Favicon dimensions?

Wikipedia has this to say:

Additionally, such icon files can be either 16×16 or 32×32 pixels in size, and either 8-bit or 24-bit in color depth (note that GIF files have a limited, 256 color palette entries).

I think the best way is to use a 32x32 gif and test it with different browsers.

How to change ViewPager's page?

Supplemental answer

I was originally having trouble getting a reference to the ViewPager from other class methods because the addOnTabSelectedListener made an anonymous inner class, which in turn required the ViewPager variable to be declared final. The solution was to use a class member variable and not use the anonymous inner class.

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    protected void onCreate(Bundle savedInstanceState) {

        Toolbar toolbar = (Toolbar) findViewById(;

        tabLayout = (TabLayout) findViewById(;
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

        viewPager = (ViewPager) findViewById(;
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        // don't use an anonymous inner class here


    TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {

        public void onTabSelected(TabLayout.Tab tab) {

        public void onTabUnselected(TabLayout.Tab tab) {


        public void onTabReselected(TabLayout.Tab tab) {


    // The view pager can now be accessed here, too.
    public void someMethod() {


Reporting Services permissions on SQL Server R2 SSRS

This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.

To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.

A variable modified inside a while loop is not remembered

I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value

cat $f $g | \
while read -r s;
  echo $s > /dev/null;  # some work
  echo $i > 2
  let i++
read -r i < 2
echo $i

Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

while read -r s;
  echo $s > /dev/null
  let i++
done <<EOT
$(cat $f $g)
let i--
echo $i

How to install python-dateutil on Windows?

I followed several suggestions in this list without success. Finally got it installed on Windows using this method: I extracted the zip file and placed the folders under my python27 folder. In a DOS window, I navigated to the installed root folder from extracting the zip file (python-dateutil-2.6.0), then issued this command:

.\python install

Whammo-bammo it all worked.

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
    ColumnA = <bad value> /* or any other search conditions */

How to create a new branch from a tag?

I used the following steps to create a new hot fix branch from a Tag.


git checkout -b <New Branch Name> <TAG Name>

Steps to do it.

  1. git checkout -b NewBranchName v1.0
  2. Make changes to pom / release versions
  3. Stage changes
  4. git commit -m "Update pom versions for Hotfix branch"
  5. Finally push your newly created branch to remote repository.
git push -u origin NewBranchName

I hope this would help.

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

H?llo from 2020. Let me bring String.prototype.matchAll() to your attention:

let regexp = /(?:&|&amp;)?([^=]+)=([^&]+)/g;
let str = '1111342=Adam%20Franco&348572=Bob%20Jones';

for (let match of str.matchAll(regexp)) {
    let [full, key, value] = match;
    console.log(key + ' => ' + value);


1111342 => Adam%20Franco
348572 => Bob%20Jones

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Barcode scanner for mobile phone for Website in form

You can use the Android app Barcode Scanner Terminal (DISCLAIMER! I'm the developer). It can scan the barcode and send it to the PC and in your case enter it on the web form. More details here.

Creating and Update Laravel Eloquent

Here's a full example of what "lu cip" was talking about:

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');

Below is the updated link of the docs which is on the latest version of Laravel

Docs here: Updated link

ASP.NET file download from server

Making changes as below and redeploying on server content type as

Response.ContentType = "application/octet-stream";

This worked for me.

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
Response.AddHeader("Content-Length", file.Length.ToString()); 
Response.ContentType = "application/octet-stream"; 

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

The raw_json_encode() function above did not solve me the problem (for some reason, the callback function raised an error on my PHP 5.2.5 server).

But this other solution did actually work.

Credits should go to Marco Gasi. I just call his function instead of calling json_encode():

function jsonRemoveUnicodeSequences( $json_struct )
    return preg_replace( "/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode( $json_struct ) );

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In my instance of the problem, the solution was to replace german umlauts (äöü) with their HTML-equivalents...

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
string ErrMsg = string.Empty;
        int num = int.Parse("gagw");
    catch (Exception ex)
        ErrMsg = ex.Message;
return ErrMsg

Method two:

public void test(ref string ErrMsg )

    ErrMsg = string.Empty;
            int num = int.Parse("gagw");
        catch (Exception ex)
            ErrMsg = ex.Message;

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Make sure your email address variable is not blank. Check using


Java: Unresolved compilation problem

Your compiled classes may need to be recompiled from the source with the new jars.

Try running "mvn clean" and then rebuild

Duplicate Entire MySQL Database

This won't work for InnoDB. Use this workaround only if you are trying to copy MyISAM databases.

If locking the tables during backup, and, possibly, pausing MySQL during the database import is acceptable, mysqlhotcopy may work faster.



# mysqlhotcopy -u root -p password db_name /path/to/backup/directory


cp /path/to/backup/directory/* /var/lib/mysql/db_name

mysqlhotcopy can also transfer files over SSH (scp), and, possibly, straight into the duplicate database directory.


# mysqlhotcopy -u root -p password db_name /var/lib/mysql/duplicate_db_name

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

wampserver doesn't go green - stays orange

I have had this issue before and it turned out that Skype was interferring with port 80. So you may have to look at your system to see if you have another application utilizing this port.

Anyway under Skype, to change this setting it was: Tools->Options->Advanced->Connection->Use port 80 and 443 as alternatives for incoming connections. Untick this, restart Skype, restart wamp.

Related question

Best way to load module/class from lib folder in Rails 3?

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Source: Rails 3 Quicktip: Autoload lib directory including all subdirectories, avoid lazy loading

Please mind that files contained in the lib folder are only loaded when the server is started. If you want the comfort to autoreload those files, read: Rails 3 Quicktip: Auto reload lib folders in development mode. Be aware that this is not meant for a production environment since the permanent reload slows down the machine.

While, Do While, For loops in Assembly Language (emu8086)


For-loop in C:

for(int x = 0; x<=3; x++)
    //Do something!

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop


Do-while-loop in C:

int x=1;
    //Do something!

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal


While-loop in C:

    //Do something

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Undefined or null for AngularJS

lodash provides a shorthand method to check if undefined or null: _.isNil(yourVariable)

Check if string doesn't contain another string

WHERE NOT (someColumn LIKE '%Apples%')

Format XML string to print friendly XML string

You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.

string FormatXml(string xml)
         XDocument doc = XDocument.Parse(xml);
         return doc.ToString();
     catch (Exception)
         // Handle and throw if fatal exception here; don't just ignore them
         return xml;

[using statements are ommitted for brevity]

'pip install' fails for every package ("Could not find a version that satisfies the requirement")

Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.

Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?

This seems to be related to Unable to install Python libraries

See Dominique Barton's answer:

Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.

On Debian-based systems I'd try:

apt-get update && apt-get upgrade python-pip

On Red Hat Linux-based systems:

yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)

On Mac:

sudo easy_install -U pip

You can also try to update openssl separately.

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

Change Screen Orientation programmatically using a Button

Use this to set the orientation of the screen:




and don't forget to add this to your manifest:

android:configChanges = "orientation"

bootstrap datepicker setDate format dd/mm/yyyy

Try this

 format: 'DD/MM/YYYY hh:mm A'

As we all know JS is case-sensitive. So this will display

10/05/2016 12:00 AM

In your case is

format: 'DD/MM/YYYY'

Display : 10/05/2016

My bootstrap datetimepicker is based on eonasdan bootstrap-datetimepicker

Access denied for root user in MySQL command-line

navigate do C:\xampp\mysql\bin\ and make sure the file mysql.exe is in that folder.

mysql -uroot -p

if dont have a password just press enter.

the prompt changes to


do your mysql commands

Enumerations on PHP

Depending upon use case, I would normally use something simple like the following:

abstract class DaysOfWeek
    const Sunday = 0;
    const Monday = 1;
    // etc.

$today = DaysOfWeek::Sunday;

However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:

abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        return self::$constCacheArray[$calledClass];

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);

By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:

abstract class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false

As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).

Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.

How to validate phone number in laravel 5.2?

    'phone' => 'numeric|required',
    'body' => 'required',

Concatenating bits in VHDL

The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only

Assert equals between 2 Lists in Junit

Don't reinvent the wheel!

There's a Google Code library that does this for you: Hamcrest

[Hamcrest] Provides a library of matcher objects (also known as constraints or predicates) allowing 'match' rules to be defined declaratively, to be used in other frameworks. Typical scenarios include testing frameworks, mocking libraries and UI validation rules.

How do you store Java objects in HttpSession?

The request object is not the session.

You want to use the session object to store. The session is added to the request and is were you want to persist data across requests. The session can be obtained from

HttpSession session = request.getSession(true);

Then you can use setAttribute or getAttribute on the session.

A more up to date tutorial on jsp sessions is:

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    return false;

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
    return false;

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11

    # PASS: Ubuntu Oracle JDK11

    # PASS: Fedora OpenJDK JDK8

    #### FAIL: Fedora OpenJDK JDK8

How to get user name using Windows authentication in

This should work:


Identity returns an IPrincipal

Here is the link to the Microsoft documentation.

What's the maximum value for an int in PHP?

The size of PHP ints is platform dependent:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

PHP 6 adds "longs" (64 bit ints).

How to find the highest value of a column in a data frame in R?

Here's a dplyr solution:


# find max for each column
summarise_each(ozone, funs(max(., na.rm=TRUE)))

# sort by Solar.R, descending
arrange(ozone, desc(Solar.R))

UPDATE: summarise_each() has been deprecated in favour of a more featureful family of functions: mutate_all(), mutate_at(), mutate_if(), summarise_all(), summarise_at(), summarise_if()

Here is how you could do:

# find max for each column
ozone %>%
         summarise_if(is.numeric, funs(max(., na.rm=TRUE)))%>%


ozone %>%
         summarise_at(vars(1:6), funs(max(., na.rm=TRUE)))%>%

How do I use DateTime.TryParse with a Nullable<DateTime>?

DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;

(There might be more elegant solutions, but why don't you simply do something as above?)

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:


Difference between @click and v-on:click Vuejs

There is no difference between the two, one is just a shorthand for the second.

The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.

<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>

Source: official documentation.

How to sort an array of integers correctly

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

Insertion sort


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


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

Selection sort:


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


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

Have fun

Convert blob URL to normal URL

A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.

A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.

Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.

It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).

Here's an example:

var blob = new Blob(["Hello, world!"], { type: 'text/plain' });_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
var xhr = new XMLHttpRequest;_x000D_
xhr.responseType = 'blob';_x000D_
xhr.onload = function() {_x000D_
   var recoveredBlob = xhr.response;_x000D_
   var reader = new FileReader;_x000D_
   reader.onload = function() {_x000D_
     var blobAsDataUrl = reader.result;_x000D_
     window.location = blobAsDataUrl;_x000D_
_x000D_'GET', blobUrl);_x000D_

data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

Take a look at FileSaver.js. It provides a handy saveAs function which takes care of most browser specific quirks.

Upload artifacts to Nexus, without Maven

If you need a convenient command line interface or python API, look at repositorytools

Using it, you can upload artifact to nexus with command

artifact upload foo-1.2.3.ext releases com.fooware

To make it work, you will also need to set some environment variables

export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword

How to remove ASP.Net MVC Default HTTP Headers?

For the sake of completeness, there is another way to remove the Server header, using regedit.

See this MSDN blog.

Create a DWORD entry called DisableServerHeader in the following Registry key and set the value to 1.


I'd rather find a proper solution using the Web.config, but using <rewrite> is not good because it requires the rewrite module to be installed, and even then it won't really remove the header, just empty it.

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

How to pass parameters using ui-sref in ui-router to controller

You don't necessarily need to have the parameters inside the URL.

For instance, with:

.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

  params: {
    foo: null,
    bar: null

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

How to create our own Listener interface in android?

I have done it something like below for sending my model class from the Second Activity to First Activity. I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.

Second Activity

public static MutableLiveData<AudioListModel> getLiveSong() {
        MutableLiveData<AudioListModel> result = new MutableLiveData<>();
        return result;

"liveSong" is AudioListModel declared globally

Call this method in the First Activity

PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
            public void onChanged(AudioListModel audioListModel) {
                if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
                    Log.d("LiveSong--->Changes-->", audioListModel.getSongName());

May this help for new explorers like me.

Excel VBA - Pass a Row of Cell Values to an Array and then Paste that Array to a Relative Reference of Cells

When i Tried your Code i got en Error when i wanted to fill the Array.

you can try to fill the Array like This.

Sub Testing_Data()
Dim k As Long, S2 As Worksheet, VArray

Application.ScreenUpdating = False
Set S2 = ThisWorkbook.Sheets("Sheet1")
With S2
    VArray = .Range("A1:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
End With
For k = 2 To UBound(VArray, 1)
    S2.Cells(k, "B") = VArray(k, 1) / 100
    S2.Cells(k, "C") = VArray(k, 1) * S2.Cells(k, "B")

End Sub

Clicking a checkbox with ng-click does not update the model

It is kind of a hack but wrapping it in a timeout seems to accomplish what you are looking for:

angular.module('myApp', [])
    .controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $scope.todos = [{
        'text': "get milk",
        'done': true
    }, {
        'text': "get milk2",
            'done': false

    $scope.onCompleteTodo = function (todo) {
            console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
            $scope.doneAfterClick = todo.done;
            $scope.todoText = todo.text;

Unable to resolve host "<URL here>" No address associated with host name

Unable to resolve host “”; No address associated with hostname

you must have to check below code here on your manifest :

<uses-permission android:name="android.permission.INTERNET" />

and most important at least for me:-

enabled wifi connection or internet connection on your mobile device

UTC Date/Time String to Timezone

General purpose normalisation function to format any timestamp from any timezone to other. Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')

 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format

function datetimeconv($datetime, $from, $to)
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;


$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"

Android button font size

Another programmatically approach;

final Button btn = (Button) findViewById(;

        final float[] size = {12};

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                size[0] +=2;
                btn.setTextSize(size[0] +2);

Every time you click your button, Button text will be change (+2px size). You can add another button and change size -2px too. If you want to save size for another openings, you may use Shared Preference interface.

Java get month string from integer

Month enum

You could use the Month enum. This enum is defined as part of the new java.time framework built into Java 8 and later.

int monthNumber = 10;

The output would be:



Localize to a language beyond English by calling getDisplayName on the same Enum.

String output = Month.OCTOBER.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );



ipad safari: disable scrolling, and bounce effect?

Tested in iphone. Just use this css on target element container and it will change the scrolling behaviour, which stops when finger leaves the screen.

-webkit-overflow-scrolling: auto

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Remove property for all objects in array

var array = [{"bad": "something", "good":"something"},{"bad":"something", "good":"something"}];_x000D_
var results ={_x000D_
  return {good : item["good"]}_x000D_

How to iterate through range of Dates in Java?

Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate (or the equivalent Joda Time classes for Java 7 and older)

for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))

I would thoroughly recommend using java.time (or Joda Time) over the built-in Date/Calendar classes.

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code


Error: free(): invalid next size (fast):

I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.

Parse a URI String into Name-Value Collection

If you are using Spring, add an argument of type @RequestParam Map<String,String> to your controller method, and Spring will construct the map for you!

How to control the line spacing in UILabel

Swift 3 extension:

import UIKit
extension UILabel {
  func setTextWithLineSpacing(text: String, lineHeightMultiply: CGFloat = 1.3) {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineHeightMultiple = lineHeightMultiply
    paragraphStyle.alignment = .center
    let attributedString = NSMutableAttributedString(string: text)
    attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
    self.attributedText = attributedString

Count the number of times a string appears within a string

do this , please note that you will have to define the regex for 'test'!!!

string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string[] parts = (new Regex("")).Split(s);
//just do a count on parts

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

The correct format for IE8 is:

  $("#ActionBox").css({ 'margin-top': '10px' });  

with this work.

How to check the function's return value if true or false

false != 'false'

For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:

var result = ValidateForm();
if(result == false) {

No 'Access-Control-Allow-Origin' header in Angular 2 app

This a problem with the CORS configuration on the server. It is not clear what server are you using, but if you are using Node+express you can solve it with the following code

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware

that code was an answer of @jvandemo to a very similar question.

Why number 9 in kill -9 command in unix?

First you need to know what are Signals in Unix-like systems (It'll take just few minutes).

Signals, are software interrupts sent to a (running) program to indicate that an important event has occurred.

The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control.

There are several types of Signals we can use - to get a full list of all the available/possible Signals use "$ kill -l" command: enter image description here

In the above output it's clearly visible, that each Signal has a 'signal number' (e.g. 1, 2, 3) and a 'signal name' (e.g. SIGUP, SIGINT, SIGQUIT) associated with it. For a detailed look up what each and every Signal does, visit this link.

Finally, coming to the question "Why number 9 in kill -9 command":

There are several methods of delivering signals to a program or script. One of commonly used method for sending signal is to use the kill command - the basic syntax is:

$ kill -signal pid

Where signal is either the number or name of the signal, followed by the process Id (pid) to which the signal will be sent.

For example - -SIGKILL (or -9), signal kills the process immediately.

$ kill -SIGKILL 1001


$ kill -9 1001

both command are one the same thing i.e. above we have used the 'signal name', and later we have used 'signal number'.

Verdict: One has an open choice to whether use the 'signal name' or 'signal number' with the kill command.

Regex expressions in Java, \\s vs. \\s+

First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.

However x.replaceAll("\\s+", ""); will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+ matches 1 or more spaces at once and replaces them with empty string.

So even though you get the same output from both it is better to use:

x.replaceAll("\\s+", "");

SQL - using alias in Group By

Back in the day I found that Rdb, the former DEC product now supported by Oracle allowed the column alias to be used in the GROUP BY. Mainstream Oracle through version 11 does not allow the column alias to be used in the GROUP BY. Not sure what Postgresql, SQL Server, MySQL, etc will or won't allow. YMMV.

For Loop on Lua

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

Java Generics With a Class & an Interface - Together

Here's how you would do it in Kotlin

fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
    //your code here

Prevent direct access to a php include file

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  if (false !== strpos($url,'.php')) {
      die ("Direct access not premitted");

Pass correct "this" context to setTimeout callback?

EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object:

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){ that.tip.destroy() }, 1000);

In the ES5 spec, just released a year before that time, it introduced the bind method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:

if (this.options.destroyOnHide) {
     setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);

The bind function creates a new function with the this value pre-filled.

Now in modern JS, this is exactly the problem arrow functions solve in ES6:

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);

Arrow functions do not have a this value of its own, when you access it, you are accessing the this value of the enclosing lexical scope.

HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:

if (this.options.destroyOnHide) {
     setTimeout(function(that){ that.tip.destroy() }, 1000, this);

See also:

CSV file written with Python has blank lines between each row

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')

The "lineterminator='\r'" permit to pass to next row, without empty row between two.

How do you make sure email you send programmatically is not automatically marked as spam?

To allow DMARC checks for SPF to pass and also be aligned when using sendmail, make sure you are setting the envelope sender address (-f or -r parameter) to something that matches the domain in the From: header address.

With PHP:

Using PHP's built-in mail() function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the RFC5321.MailFrom / Return Path header.

For example, say you are hosting your website on the web server. If you do not set the additional parameters parameter:

mail($to,$subject,$message,$headers); // Wrong way

The email recipient will receive an email with the following mail headers:

Return-Path: <[email protected]>
From: <[email protected]>

Even though this passes SPF checks, it will be unaligned (since and do not match), which means that DMARC SPF check will fail as unaligned.

Instead, you must pass the envelope sender address to sendmail by including the 5th parameter in the PHP mail() function, for example:

mail($to,$subject,$message,$headers, '-r [email protected]'); // Right way

In this case, the email recipient will receive an email with the following mail headers:

Return-Path: <[email protected]>
From: <[email protected]>

Since both of these headers contain addresses from, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.