Programs & Examples On #Recursion

Recursion is a kind of function call in which a function calls itself. Such functions are also called recursive functions. Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.

find all subsets that sum to a particular value

RUBY

This code will reject the empty arrays and returns the proper array with values.

def find_sequence(val, num)
  b = val.length
  (0..b - 1).map {|n| val.uniq.combination(n).each.find_all {|value| value.reduce(:+) == num}}.reject(&:empty?)
end

val = [-10, 1, -1, 2, 0]
num = 2

Output will be [[2],[2,0],[-1,1,2],[-1,1,2,0]]

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

Method to get all files within folder and subfolders that will return a list

String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);

Java recursive Fibonacci sequence

You can also simplify your function, as follows:

public int fibonacci(int n)  {
    if (n < 2) return n;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

Finding height in Binary Search Tree

The problem lies in your base case.

"The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only a node (the root) has a height of zero." - Wikipedia

If there is no node, you want to return -1 not 0. This is because you are adding 1 at the end.

So if there isn't a node, you return -1 which cancels out the +1.

int findHeight(TreeNode<T> aNode) {
    if (aNode == null) {
        return -1;
    }

    int lefth = findHeight(aNode.left);
    int righth = findHeight(aNode.right);

    if (lefth > righth) {
        return lefth + 1;
    } else {
        return righth + 1;
    }
}

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

<?php

/**
 * code by Nk ([email protected])
 */

class filesystem
{
    public static function remove($path)
    {
        return is_dir($path) ? rmdir($path) : unlink($path);
    }

    public static function normalizePath($path)
    {
        return $path.(is_dir($path) && !preg_match('@/$@', $path) ? '/' : '');      
    }

    public static function rscandir($dir, $sort = SCANDIR_SORT_ASCENDING)
    {
        $results = array();

        if(!is_dir($dir))
        return $results;

        $dir = self::normalizePath($dir);

        $objects = scandir($dir, $sort);

        foreach($objects as $object)
        if($object != '.' && $object != '..')
        {
            if(is_dir($dir.$object))
            $results = array_merge($results, self::rscandir($dir.$object, $sort));
            else
            array_push($results, $dir.$object);
        }

        array_push($results, $dir);

        return $results;
    }

    public static function rrmdir($dir)
    {
        $files = self::rscandir($dir);

        foreach($files as $file)
        self::remove($file);

        return !file_exists($dir);
    }
}

?>

cleanup.php :

<?php

/* include.. */

filesystem::rrmdir('/var/log');
filesystem::rrmdir('./cache');

?>

Way to go from recursion to iteration

Well, in general, recursion can be mimicked as iteration by simply using a storage variable. Note that recursion and iteration are generally equivalent; one can almost always be converted to the other. A tail-recursive function is very easily converted to an iterative one. Just make the accumulator variable a local one, and iterate instead of recurse. Here's an example in C++ (C were it not for the use of a default argument):

// tail-recursive
int factorial (int n, int acc = 1)
{
  if (n == 1)
    return acc;
  else
    return factorial(n - 1, acc * n);
}

// iterative
int factorial (int n)
{
  int acc = 1;
  for (; n > 1; --n)
    acc *= n;
  return acc;
}

Knowing me, I probably made a mistake in the code, but the idea is there.

Regular expression to detect semi-colon terminated C++ for & while loops

As Frank suggested, this is best without regex. Here's (an ugly) one-liner:

match_string = orig_string[orig_string.index("("):len(orig_string)-orig_string[::-1].index(")")]

Matching the troll line est mentioned in his comment:

orig_string = "for (int i = 0; i < 10; doSomethingTo(\"(\"));"
match_string = orig_string[orig_string.index("("):len(orig_string)-orig_string[::-1].index(")")]

returns (int i = 0; i < 10; doSomethingTo("("))

This works by running through the string forward until it reaches the first open paren, and then backward until it reaches the first closing paren. It then uses these two indices to slice the string.

Searching for file in directories recursively

This returns all xml-files recursively :

var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);

Recursive Fibonacci

Why not use iterative algorithm?

int fib(int n)
{
    int a = 1, b = 1;
    for (int i = 3; i <= n; i++) {
        int c = a + b;
        a = b;
        b = c;
    }           
    return b;
}

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

What in layman's terms is a Recursive Function using PHP

Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

A solution that correctly handles all file names (including newlines) and extracts into a directory that is at the same location as the file, just with the extension removed:

find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';'

Note that you can easily make it handle more file types (such as .jar) by adding them using -o, e.g.:

find . '(' -iname '*.zip' -o -iname '*.jar' ')' -exec ...

How to find all combinations of coins when given some dollar value

Straightforward java solution:

public static void main(String[] args) 
{    
    int[] denoms = {4,2,3,1};
    int[] vals = new int[denoms.length];
    int target = 6;
    printCombinations(0, denoms, target, vals);
}


public static void printCombinations(int index, int[] denom,int target, int[] vals)
{
  if(target==0)
  {
    System.out.println(Arrays.toString(vals));
    return;
  }
  if(index == denom.length) return;   
  int currDenom = denom[index];
  for(int i = 0; i*currDenom <= target;i++)
  {
    vals[index] = i;
    printCombinations(index+1, denom, target - i*currDenom, vals);
    vals[index] = 0;
  }
}

What is tail recursion?

Using regular recursion, each recursive call pushes another entry onto the call stack. When the recursion is completed, the app then has to pop each entry off all the way back down.

With tail recursion, depending on language the compiler may be able to collapse the stack down to one entry, so you save stack space...A large recursive query can actually cause a stack overflow.

Basically Tail recursions are able to be optimized into iteration.

How to search by key=>value in a multidimensional array in PHP

And another version that returns the key value from the array element in which the value is found (no recursion, optimized for speed):

// if the array is 
$arr['apples'] = array('id' => 1);
$arr['oranges'] = array('id' => 2);

//then 
print_r(search_array($arr, 'id', 2);
// returns Array ( [oranges] => Array ( [id] => 2 ) ) 
// instead of Array ( [0] => Array ( [id] => 2 ) )

// search array for specific key = value
function search_array($array, $key, $value) {
  $return = array();   
  foreach ($array as $k=>$subarray){  
    if (isset($subarray[$key]) && $subarray[$key] == $value) {
      $return[$k] = $subarray;
      return $return;
    } 
  }
}

Thanks to all who posted here.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

Recursive sub folder search and return files in a list python

Its not the most pythonic answer, but I'll put it here for fun because it's a neat lesson in recursion

def find_files( files, dirs=[], extensions=[]):
    new_dirs = []
    for d in dirs:
        try:
            new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
        except OSError:
            if os.path.splitext(d)[1] in extensions:
                files.append(d)

    if new_dirs:
        find_files(files, new_dirs, extensions )
    else:
        return

On my machine I have two folders, root and root2

mender@multivax ]ls -R root root2
root:
temp1 temp2

root/temp1:
temp1.1 temp1.2

root/temp1/temp1.1:
f1.mid

root/temp1/temp1.2:
f.mi  f.mid

root/temp2:
tmp.mid

root2:
dummie.txt temp3

root2/temp3:
song.mid

Lets say I want to find all .txt and all .mid files in either of these directories, then I can just do

files = []
find_files( files, dirs=['root','root2'], extensions=['.mid','.txt'] )
print(files)

#['root2/dummie.txt',
# 'root/temp2/tmp.mid',
# 'root2/temp3/song.mid',
# 'root/temp1/temp1.1/f1.mid',
# 'root/temp1/temp1.2/f.mid']

Recursively list files in Java

Non-recursive BFS with a single list (particular example is searching for *.eml files):

    final FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory() || file.getName().endsWith(".eml");
        }
    };

    // BFS recursive search
    List<File> queue = new LinkedList<File>();
    queue.addAll(Arrays.asList(dir.listFiles(filter)));

    for (ListIterator<File> itr = queue.listIterator(); itr.hasNext();) {
        File file = itr.next();
        if (file.isDirectory()) {
            itr.remove();
            for (File f: file.listFiles(filter)) itr.add(f);
        }
    }

What is the most efficient/elegant way to parse a flat table into a tree?

This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works.

It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)

This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.

public class Node {

    private Node parent = null;

    private List<Node> children;

    private String name;

    private int id = -1;

    public Node(Node parent, int id, String name) {
        this.parent = parent;
        this.children = new ArrayList<Node>();
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void addChild(Node child) {
        children.add(child);
    }

    public List<Node> getChildren() {
        return children;
    }

    public boolean isRoot() {
        return (this.parent == null);
    }

    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", parent=" + parent;
    }
}

public class NodeBuilder {

    public static Node build(List<Map<String, String>> input) {

        // maps id of a node to it's Node object
        Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();

        // maps id of a node to the id of it's parent
        Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();

        // create special 'root' Node with id=0
        Node root = new Node(null, 0, "root");
        nodeMap.put(root.getId(), root);

        // iterate thru the input
        for (Map<String, String> map : input) {

            // expect each Map to have keys for "id", "name", "parent" ... a
            // real implementation would read from a SQL object or resultset
            int id = Integer.parseInt(map.get("id"));
            String name = map.get("name");
            int parent = Integer.parseInt(map.get("parent"));

            Node node = new Node(null, id, name);
            nodeMap.put(id, node);

            childParentMap.put(id, parent);
        }

        // now that each Node is created, setup the child-parent relationships
        for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
            int nodeId = entry.getKey();
            int parentId = entry.getValue();

            Node child = nodeMap.get(nodeId);
            Node parent = nodeMap.get(parentId);
            parent.addChild(child);
        }

        return root;
    }
}

public class NodePrinter {

    static void printRootNode(Node root) {
        printNodes(root, 0);
    }

    static void printNodes(Node node, int indentLevel) {

        printNode(node, indentLevel);
        // recurse
        for (Node child : node.getChildren()) {
            printNodes(child, indentLevel + 1);
        }
    }

    static void printNode(Node node, int indentLevel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indentLevel; i++) {
            sb.append("\t");
        }
        sb.append(node);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        // setup dummy data
        List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
        resultSet.add(newMap("1", "Node 1", "0"));
        resultSet.add(newMap("2", "Node 1.1", "1"));
        resultSet.add(newMap("3", "Node 2", "0"));
        resultSet.add(newMap("4", "Node 1.1.1", "2"));
        resultSet.add(newMap("5", "Node 2.1", "3"));
        resultSet.add(newMap("6", "Node 1.2", "1"));

        Node root = NodeBuilder.build(resultSet);
        printRootNode(root);

    }

    //convenience method for creating our dummy data
    private static Map<String, String> newMap(String id, String name, String parentId) {
        Map<String, String> row = new HashMap<String, String>();
        row.put("id", id);
        row.put("name", name);
        row.put("parent", parentId);
        return row;
    }
}

Recursively look for files with a specific extension

To find all the pom.xml files in your current directory and print them, you can use:

find . -name 'pom.xml' -print

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

Reversing a String with Recursion in Java

Because this is recursive your output at each step would be something like this:

  1. "Hello" is entered. The method then calls itself with "ello" and will return the result + "H"
  2. "ello" is entered. The method calls itself with "llo" and will return the result + "e"
  3. "llo" is entered. The method calls itself with "lo" and will return the result + "l"
  4. "lo" is entered. The method calls itself with "o" and will return the result + "l"
  5. "o" is entered. The method will hit the if condition and return "o"

So now on to the results:

The total return value will give you the result of the recursive call's plus the first char

To the return from 5 will be: "o"

The return from 4 will be: "o" + "l"

The return from 3 will be: "ol" + "l"

The return from 2 will be: "oll" + "e"

The return from 1 will be: "olle" + "H"

This will give you the result of "olleH"

Creating a recursive method for Palindrome

/**
     * Function to check a String is palindrome or not
     * @param s input String
     * @return true if Palindrome
     */
    public boolean checkPalindrome(String s) {

        if (s.length() == 1 || s.isEmpty())
            return true;

        boolean palindrome = checkPalindrome(s.substring(1, s.length() - 1));

        return palindrome && s.charAt(0) == s.charAt(s.length() - 1);

    }

Reversing a linked list in Java, recursively

private Node ReverseList(Node current, Node previous)
    {
        if (current == null) return null;
        Node originalNext = current.next;
        current.next = previous;
        if (originalNext == null) return current;
        return ReverseList(originalNext, current);
    }

Recursion or Iteration?

Recursion? Where do I start, wiki will tell you “it’s the process of repeating items in a self-similar way"

Back in day when I was doing C, C++ recursion was a god send, stuff like "Tail recursion". You'll also find many sorting algorithms use recursion. Quick sort example: http://alienryderflex.com/quicksort/

Recursion is like any other algorithm useful for a specific problem. Perhaps you mightn't find a use straight away or often but there will be problem you’ll be glad it’s available.

self referential struct definition?

I know this post is old, however, to get the effect you are looking for, you may want to try the following:

#define TAKE_ADVANTAGE

/* Forward declaration of "struct Cell" as type Cell. */
typedef struct Cell Cell;

#ifdef TAKE_ADVANTAGE
/*
   Define Cell structure taking advantage of forward declaration.
*/
struct Cell
{
   int isParent;
   Cell *child;
};

#else

/*
   Or...you could define it as other posters have mentioned without taking
   advantage of the forward declaration.
*/
struct Cell
{
   int isParent;
   struct Cell *child;
};

#endif

/*
    Some code here...
*/

/* Use the Cell type. */
Cell newCell;

In either of the two cases mentioned in the code fragment above, you MUST declare your child Cell structure as a pointer. If you do not, then you will get the "field 'child' has incomplete type" error. The reason is that "struct Cell" must be defined in order for the compiler to know how much space to allocate when it is used.

If you attempt to use "struct Cell" inside the definition of "struct Cell", then the compiler cannot yet know how much space "struct Cell" is supposed to take. However, the compiler already knows how much space a pointer takes, and (with the forward declaration) it knows that "Cell" is a type of "struct Cell" (although it doesn't yet know how big a "struct Cell" is). So, the compiler can define a "Cell *" within the struct that is being defined.

How to get all files under a specific directory in MATLAB?

I don't know a single-function method for this, but you can use genpath to recurse a list of subdirectories only. This list is returned as a semicolon-delimited string of directories, so you'll have to separate it using strread, i.e.

dirlist = strread(genpath('/path/of/directory'),'%s','delimiter',';')

If you don't want to include the given directory, remove the first entry of dirlist, i.e. dirlist(1)=[]; since it is always the first entry.

Then get the list of files in each directory with a looped dir.

filenamelist=[];
for d=1:length(dirlist)
    % keep only filenames
    filelist=dir(dirlist{d});
    filelist={filelist.name};

    % remove '.' and '..' entries
    filelist([strmatch('.',filelist,'exact');strmatch('..',filelist,'exact'))=[];
    % or to ignore all hidden files, use filelist(strmatch('.',filelist))=[];

    % prepend directory name to each filename entry, separated by filesep*
    for f=1:length(filelist)
        filelist{f}=[dirlist{d} filesep filelist{f}];
    end

    filenamelist=[filenamelist filelist];
end

filesep returns the directory separator for the platform on which MATLAB is running.

This gives you a list of filenames with full paths in the cell array filenamelist. Not the neatest solution, I know.

What is recursion and when should I use it?

Recursion in computing is a technique used to compute a result or side effect following the normal return from a single function (method, procedure or block) invocation.

The recursive function, by definition must have the ability to invoke itself either directly or indirectly (through other functions) depending on an exit condition or conditions not being met. If an exit condition is met the particular invocation returns to it's caller. This continues until the initial invocation is returned from, at which time the desired result or side effect will be available.

As an example, here's a function to perform the Quicksort algorithm in Scala (copied from the Wikipedia entry for Scala)

def qsort: List[Int] => List[Int] = {
  case Nil => Nil
  case pivot :: tail =>
    val (smaller, rest) = tail.partition(_ < pivot)
    qsort(smaller) ::: pivot :: qsort(rest)
}

In this case the exit condition is an empty list.

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

What is tail call optimization?

Look here:

http://tratt.net/laurie/tech_articles/articles/tail_call_optimization

As you probably know, recursive function calls can wreak havoc on a stack; it is easy to quickly run out of stack space. Tail call optimization is way by which you can create a recursive style algorithm that uses constant stack space, therefore it does not grow and grow and you get stack errors.

recursion versus iteration

To write an equivalent method using iteration, we must explicitly use a stack. The fact that the iterative version requires a stack for its solution indicates that the problem is difficult enough that it can benefit from recursion. As a general rule, recursion is most suitable for problems that cannot be solved with a fixed amount of memory and consequently require a stack when solved iteratively. Having said that, recursion and iteration can show the same outcome while they follow different pattern.To decide which method works better is case by case and best practice is to choose based on the pattern that problem follows.

For example, to find the nth triangular number of Triangular sequence: 1 3 6 10 15 … A program that uses an iterative algorithm to find the n th triangular number:

Using an iterative algorithm:

//Triangular.java
import java.util.*;
class Triangular {
   public static int iterativeTriangular(int n) {
      int sum = 0;
      for (int i = 1; i <= n; i ++)
         sum += i;
      return sum;
   }
   public static void main(String args[]) {
      Scanner stdin = new Scanner(System.in);
      System.out.print("Please enter a number: ");
      int n = stdin.nextInt();
      System.out.println("The " + n + "-th triangular number is: " + 
                            iterativeTriangular(n));
   }
}//enter code here

Using a recursive algorithm:

//Triangular.java
import java.util.*;
class Triangular {
   public static int recursiveTriangular(int n) {
      if (n == 1)
     return 1;  
      return recursiveTriangular(n-1) + n; 
   }

   public static void main(String args[]) {
      Scanner stdin = new Scanner(System.in);
      System.out.print("Please enter a number: ");
      int n = stdin.nextInt();
      System.out.println("The " + n + "-th triangular number is: " + 
                             recursiveTriangular(n)); 
   }
}

Node.js - Maximum call stack size exceeded

I thought of another approach using function references that limits call stack size without using setTimeout() (Node.js, v10.16.0):

testLoop.js

let counter = 0;
const max = 1000000000n  // 'n' signifies BigInteger
Error.stackTraceLimit = 100;

const A = () => {
  fp = B;
}

const B = () => {
  fp = A;
}

let fp = B;

const then = process.hrtime.bigint();

for(;;) {
  counter++;
  if (counter > max) {
    const now = process.hrtime.bigint();
    const nanos = now - then;

    console.log({ "runtime(sec)": Number(nanos) / (1000000000.0) })
    throw Error('exit')
  }
  fp()
  continue;
}

output:

$ node testLoop.js
{ 'runtime(sec)': 18.947094799 }
C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25
    throw Error('exit')
    ^

Error: exit
    at Object.<anonymous> (C:\Users\jlowe\Documents\Projects\clearStack\testLoop.js:25:11)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

List files recursively in Linux CLI with path relative to the current directory

Use tree, with -f (full path) and -i (no indentation lines):

tree -if --noreport .
tree -if --noreport directory/

You can then use grep to filter out the ones you want.


If the command is not found, you can install it:

Type following command to install tree command on RHEL/CentOS and Fedora linux:

# yum install tree -y

If you are using Debian/Ubuntu, Mint Linux type following command in your terminal:

$ sudo apt-get install tree -y

best way to get folder and file list in Javascript

Why to invent the wheel?

There is a very popular NPM package, that let you do things like that easy.

var recursive = require("recursive-readdir");

recursive("some/path", function (err, files) {
  // `files` is an array of file paths
  console.log(files);
});

Lear more:

Is log(n!) = T(n·log(n))?

enter image description here

Sorry, I don't know how to use LaTeX syntax on stackoverflow..

Determining complexity for recursive functions (Big O notation)

For the case where n <= 0, T(n) = O(1). Therefore, the time complexity will depend on when n >= 0.

We will consider the case n >= 0 in the part below.

1.

T(n) = a + T(n - 1)

where a is some constant.

By induction:

T(n) = n * a + T(0) = n * a + b = O(n)

where a, b are some constant.

2.

T(n) = a + T(n - 5)

where a is some constant

By induction:

T(n) = ceil(n / 5) * a + T(k) = ceil(n / 5) * a + b = O(n)

where a, b are some constant and k <= 0

3.

T(n) = a + T(n / 5)

where a is some constant

By induction:

T(n) = a * log5(n) + T(0) = a * log5(n) + b = O(log n)

where a, b are some constant

4.

T(n) = a + 2 * T(n - 1)

where a is some constant

By induction:

T(n) = a + 2a + 4a + ... + 2^(n-1) * a + T(0) * 2^n 
     = a * 2^n - a + b * 2^n
     = (a + b) * 2^n - a
     = O(2 ^ n)

where a, b are some constant.

5.

T(n) = n / 2 + T(n - 5)

where n is some constant

Rewrite n = 5q + r where q and r are integer and r = 0, 1, 2, 3, 4

T(5q + r) = (5q + r) / 2 + T(5 * (q - 1) + r)

We have q = (n - r) / 5, and since r < 5, we can consider it a constant, so q = O(n)

By induction:

T(n) = T(5q + r)
     = (5q + r) / 2 + (5 * (q - 1) + r) / 2 + ... + r / 2 +  T(r)
     = 5 / 2 * (q + (q - 1) + ... + 1) +  1 / 2 * (q + 1) * r + T(r)
     = 5 / 4 * (q + 1) * q + 1 / 2 * (q + 1) * r + T(r)
     = 5 / 4 * q^2 + 5 / 4 * q + 1 / 2 * q * r + 1 / 2 * r + T(r)

Since r < 4, we can find some constant b so that b >= T(r)

T(n) = T(5q + r)
     = 5 / 2 * q^2 + (5 / 4 + 1 / 2 * r) * q + 1 / 2 * r + b
     = 5 / 2 * O(n ^ 2) + (5 / 4 + 1 / 2 * r) * O(n) + 1 / 2 * r + b
     = O(n ^ 2)

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

What are the advantages and disadvantages of recursion?

We should use recursion in following scenarios:

  • when we don't know the finite number of iteration for example our fuction exit condition is based on dynamic programming (memoization)
  • when we need to perform operations on reverse order of the elements. Meaning we want to process last element first and then n-1, n-2 and so on till first element

Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:

int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
    if (n==N/2 + 1 || n==1) {
       return 1;
    }

    return process(n-1) + process(n-2);
}

In this case only half stacks will be allocated at any given time.

How to search a string in multiple files and return the names of files in Powershell?

I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:

Get-ChildItem `
        -Path "C:\data\path" -Filter "Example*.dat" -recurse | `
    Select-String -pattern "dummy" | `
    Select-Object -Property Path,LineNumber,Line | `
    Export-CSV "C:\ResultFile.csv"

I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.

How to recursively find and list the latest modified files in a directory with subdirectories and times

To find all files whose file status was last changed N minutes ago:

find -cmin -N

For example:

find -cmin -5

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Check recursion from command line:

php -r 'function foo() { static $x = 1; echo "foo ", $x++, "\n"; foo(); } foo();'

if result > 100 THEN check memory limit;

Real-world examples of recursion

  • Parsing an XML file.
  • Efficient search in multi-dimensional spaces. E. g. quad-trees in 2D, oct-trees in 3D, kd-trees, etc.
  • Hierarchical clustering.
  • Come to think of it, traversing any hierarchical structure naturally lends itself to recursion.
  • Template metaprogramming in C++, where there are no loops and recursion is the only way.

How can I build a recursive function in python?

Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:

For example a recursive class could be a binary tree (or any tree):

class tree():
    def __init__(self):
        '''Initialise the tree'''
        self.Data = None
        self.Count = 0
        self.LeftSubtree = None
        self.RightSubtree = None

    def Insert(self, data):
        '''Add an item of data to the tree'''
        if self.Data == None:
            self.Data = data
            self.Count += 1
        elif data < self.Data:
            if self.LeftSubtree == None:
                # tree is a recurive class definition
                self.LeftSubtree = tree()
            # Insert is a recursive function
            self.LeftSubtree.Insert(data)
        elif data == self.Data:
            self.Count += 1
        elif data > self.Data:
            if self.RightSubtree == None:
                self.RightSubtree = tree()
            self.RightSubtree.Insert(data)

if __name__ == '__main__':
    T = tree()
    # The root node
    T.Insert('b')
    # Will be put into the left subtree
    T.Insert('a')
    # Will be put into the right subtree
    T.Insert('c')

As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.

Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :

import sys
sys.getrecursionlimit()

and to set it :

import sys #(if you haven't already)
sys.setrecursionlimit()

edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how

How to [recursively] Zip a directory in PHP?

Great solution but for my Windows I need make a modifications. Below the modify code

function Zip($source, $destination){

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file));
        }
        else if (is_file($file) === true)
        {

            $str1 = str_replace($source . '/', '', '/'.$file);
            $zip->addFromString($str1, file_get_contents($file));

        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

Factorial using Recursion in Java

Using Java 8 and above, using recursion itself

  UnaryOperator<Long> fact = num -> num<1 ? 1 : num * this.fact.apply(num-1);

And use it like

  fact.apply(5); // prints 120

Internally it calculate like

5*(4*(3*(2*(1*(1)))))

List all the files and folders in a Directory with PHP recursive function

This solution did the job for me. The RecursiveIteratorIterator lists all directories and files recursively but unsorted. The program filters the list and sorts it.

I'm sure there is a way to write this shorter; feel free to improve it. It is just a code snippet. You may want to pimp it to your purposes.

<?php

$path = '/pth/to/your/directories/and/files';
// an unsorted array of dirs & files
$files_dirs = iterator_to_array( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),RecursiveIteratorIterator::SELF_FIRST) );

echo '<html><body><pre>';
// create a new associative multi-dimensional array with dirs as keys and their files
$dirs_files = array();
foreach($files_dirs as $dir){
 if(is_dir($dir) AND preg_match('/\/\.$/',$dir)){
  $d = preg_replace('/\/\.$/','',$dir);
  $dirs_files[$d] = array();
  foreach($files_dirs as $file){
   if(is_file($file) AND $d == dirname($file)){
    $f = basename($file);
    $dirs_files[$d][] = $f;
   }
  }
 }
}
//print_r($dirs_files);

// sort dirs
ksort($dirs_files);

foreach($dirs_files as $dir => $files){
 $c = substr_count($dir,'/');
 echo  str_pad(' ',$c,' ', STR_PAD_LEFT)."$dir\n";
 // sort files
 asort($files);
 foreach($files as $file){
  echo str_pad(' ',$c,' ', STR_PAD_LEFT)."|_$file\n";
 }
}
echo '</pre></body></html>';

?>

What is the maximum recursion depth in Python, and how to increase it?

Of course Fibonacci numbers can be computed in O(n) by applying the Binet formula:

from math import floor, sqrt

def fib(n):                                                     
    return int(floor(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))+0.5))

As the commenters note it's not O(1) but O(n) because of 2**n. Also a difference is that you only get one value, while with recursion you get all values of Fibonacci(n) up to that value.

Calling a javascript function recursively

Using Named Function Expressions:

You can give a function expression a name that is actually private and is only visible from inside of the function ifself:

var factorial = function myself (n) {
    if (n <= 1) {
        return 1;
    }
    return n * myself(n-1);
}
typeof myself === 'undefined'

Here myself is visible only inside of the function itself.

You can use this private name to call the function recursively.

See 13. Function Definition of the ECMAScript 5 spec:

The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).

Using arguments.callee:

Alternatively you could use arguments.callee to refer to the current function:

var factorial = function (n) {
    if (n <= 1) {
        return 1;
    }
    return n * arguments.callee(n-1);
}

The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:

(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.

Tower of Hanoi: Recursive Algorithm

Here goes the explanation. Look at the picture ->

enter image description here

By calling Movetower(3,a,b,c), you intend to move all the 3 discs from tower A to tower B. So the sequential calls are ->

1. Movetower(3,a,b,c)  // No Move needed
2. Movetower(2,a,c,b)  // No move needed
3. Movetower(1,a,b,c)  // Here is the time to move, move disc1 from a to b
4. Movetower(2,a,c,b)  // Returning to this call again, this is the time to move disc2 from a to c
5. Movetower(1,b,c,a)  // Again the time to move, this time disc1 from b to c
6. Movetower(3,a,b,c)  // Returning to this call again, this is the time to move disc3 from a to b
7. Movetower(2,c,b,a)  // Not the time to move
8. Movetower(1,c,a,b)  // Here is the time to move, move disc1 from c to a
9. Movetower(2,c,b,a)  // Returning to this call again, this is the time to move disc2 from c to b
10.Movetower(1,c,a,b)  // Here is the time to move, move disc1 from a to b

Hope it helps :)

For Animation : https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

Is recursion ever faster than looping?

Functional programming is more about "what" rather than "how".

The language implementors will find a way to optimize how the code works underneath, if we don't try to make it more optimized than it needs to be. Recursion can also be optimized within the languages that support tail call optimization.

What matters more from a programmer standpoint is readability and maintainability rather than optimization in the first place. Again, "premature optimization is root of all evil".

What is the shortest function for reading a cookie by name in JavaScript?

To truly remove as much bloat as possible, consider not using a wrapper function at all:

try {
    var myCookie = document.cookie.match('(^|;) *myCookie=([^;]*)')[2]
} catch (_) {
    // handle missing cookie
}

As long as you're familiar with RegEx, that code is reasonably clean and easy to read.

What are the rules for calling the superclass constructor?

In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:

class Sub : public Base
{
  Sub(int x, int y)
  : Base(x), member(y)
  {
  }
  Type member;
};

If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:

class Sub : public Base
{
  Sub(int x, int y)
  try : Base(x), member(y)
  {
    // function body goes here
  } catch(const ExceptionType &e) {
    throw kaboom();
  }
  Type member;
};

In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.

C++: Where to initialize variables in constructor

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.

Then you controller is probably like this:

@RequestMapping(value = "/patientdetails", method = RequestMethod.POST, 
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
    @RequestParam Map<String, String> name) {
   List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
   ...
   PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
   ...
   list = service.getPatient(patientProfileDto);
   return list;
}

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

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

It's a strict check test.

It's a good thing especially if you're checking between 0 and false and null.

For example, if you have:

$a = 0;

Then:

$a==0; 
$a==NULL;
$a==false;

All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.

So with the same thing as above, but a strict test:

$a = 0;

$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false

How do I install cURL on Windows?

You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.

Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.

Enable the extension

You're done :-)

DNS caching in linux

Here are two other software packages which can be used for DNS caching on Linux:

  • dnsmasq
  • bind

After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.

If your system is using NetworkManager you can either try using the dns=dnsmasq option in /etc/NetworkManager/NetworkManager.conf or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

cast a List to a Collection

Casting never needs a new:

Collection<T> collection = myList;

You don't even make the cast explicit, because Collection is a super-type of List, so it will work just like this.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If M2_HOME is configured to point to the Maven home directory then:

  1. Go to File -> Settings
  2. Search for Maven
  3. Select Runner
  4. Insert in the field VM Options the following string:

    Dmaven.multiModuleProjectDirectory=$M2_HOME
    

Click Apply and OK

How to create an empty file at the command line in Windows?

cd > filename.cfg 

worked when creating a file in C:/Program Files where you don't have the access to create files directly.

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

Struct with template variables in C++

Looks like @monkeyking is trying it to make it more obvious code as shown below

template <typename T> 
struct Array { 
  size_t x; 
  T *ary; 
};

typedef Array<int> iArray;
typedef Array<float> fArray;

How to get an absolute file path in Python

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

Note that expanduser is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/(the tilde refers to the user's home directory), and expandvars takes care of any other environment variables (like $HOME).

How to convert a byte array to a hex string in Java?

My solution is based on maybeWeCouldStealAVan's solution, but does not rely on any additionaly allocated lookup tables. It does not uses any 'int-to-char' casts hacks (actually, Character.forDigit() does it, performing some comparison to check what the digit truly is) and thus might be a bit slower. Please feel free to use it wherever you want. Cheers.

public static String bytesToHex(final byte[] bytes)
{
    final int numBytes = bytes.length;
    final char[] container = new char[numBytes * 2];

    for (int i = 0; i < numBytes; i++)
    {
        final int b = bytes[i] & 0xFF;

        container[i * 2] = Character.forDigit(b >>> 4, 0x10);
        container[i * 2 + 1] = Character.forDigit(b & 0xF, 0x10);
    }

    return new String(container);
}

Synchronizing a local Git repository with a remote one

Sounds like you want a mirror of the remote repository:

git clone --mirror url://to/remote.git local.git

That command creates a bare repository. If you don't want a bare repository, things get more complicated.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

you can use this:

 var list = new SelectList(countryList, "Id", "Name");
 ViewBag.countries=list;
 @Html.DropDownList("countries",ViewBag.countries as SelectList)

How to find char in string and get all the indexes?

As the rule of thumb, NumPy arrays often outperform other solutions while working with POD, Plain Old Data. A string is an example of POD and a character too. To find all the indices of only one char in a string, NumPy ndarrays may be the fastest way:

def find1(str, ch):
  # 0.100 seconds for 1MB str 
  npbuf = np.frombuffer(str, dtype=np.uint8) # Reinterpret str as a char buffer
  return np.where(npbuf == ord(ch))          # Find indices with numpy

def find2(str, ch):
  # 0.920 seconds for 1MB str 
  return [i for i, c in enumerate(str) if c == ch] # Find indices with python

How can I format a String number to have commas and round?

Once you've converted your String to a number, you can use

// format the number for the default locale
NumberFormat.getInstance().format(num)

or

// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)

Ruby/Rails: converting a Date to a UNIX timestamp

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".

Using Pairs or 2-tuples in Java

Another 2 cents : Starting with Java 7, there is now a class for this in standard Lib : javafx.util.Pair.

And Yes, It is standard Java, now that JavaFx is included in the JDK :)

on change event for file input element

For someone who want to use onchange event directly on file input, set onchange="somefunction(), example code from the link:

<html>
<body>
    <script language="JavaScript">
    function inform(){
        document.form1.msg.value = "Filename has been changed";
    }
    </script>
    <form name="form1">
    Please choose a file.
    <input type="file" name="uploadbox" size="35" onChange='inform()'>
    <br><br>
    Message:
    <input type="text" name="msg" size="40">
    </form>
</body>
</html>

How can I check the size of a file in a Windows batch script?

Another example

  FOR %I in (file1.txt) do @ECHO %~zI

Can I display the value of an enum with printf()?

enum A { foo, bar } a;
a = foo;
printf( "%d", a );   // see comments below

Get User's Current Location / Coordinates

Swift 3.0

If you don't want to show user location in map, but just want to store it in firebase or some where else then follow this steps,

import MapKit
import CoreLocation

Now use CLLocationManagerDelegate on your VC and you must override the last three methods shown below. You can see how the requestLocation() method will get you the current user location using these methods.

class MyVc: UIViewController, CLLocationManagerDelegate {

  let locationManager = CLLocationManager()

 override func viewDidLoad() {
    super.viewDidLoad()

    isAuthorizedtoGetUserLocation()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    }
}

 //if we have no permission to access user location, then ask user for permission.
func isAuthorizedtoGetUserLocation() {

    if CLLocationManager.authorizationStatus() != .authorizedWhenInUse     {
        locationManager.requestWhenInUseAuthorization()
    }
}


//this method will be called each time when a user change his location access preference.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedWhenInUse {
        print("User allowed us to access location")
        //do whatever init activities here.
    }
}


 //this method is called by the framework on         locationManager.requestLocation();
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print("Did location updates is called")
    //store the user location here to firebase or somewhere 
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Did location updates is called but failed getting location \(error)")
}

}

Now you can code the below call once user sign in to your app. When requestLocation() is invoked it will further invoke didUpdateLocations above and you can store the location to Firebase or anywhere else.

if CLLocationManager.locationServicesEnabled() {
            locationManager.requestLocation();
 }

if you are using GeoFire then in the didUpdateLocations method above you can store the location as below

geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation. 

Last but not least, go to your Info.plist and enable "Privacy -Location when in Use Usage Description."

When you use simulator to test it always give you one custom location that you configured in Simulator -> Debug -> Location.

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

How to use System.Net.HttpClient to post a complex type?

This is the code I wound up with, based upon the other answers here. This is for an HttpPost that receives and responds with complex types:

Task<HttpResponseMessage> response = httpClient.PostAsJsonAsync(
                       strMyHttpPostURL,
                       new MyComplexObject { Param1 = param1, Param2 = param2}).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
                    //debug:
                    //String s = response.Result.Content.ReadAsStringAsync().Result;
                    MyOtherComplexType moct = (MyOtherComplexType)JsonConvert.DeserializeObject(response.Result.Content.ReadAsStringAsync().Result, typeof(MyOtherComplexType));

WebAPI to Return XML

If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}

This is the quickest way to always return XML from Web API.

Redirect from asp.net web api post action

    [HttpGet]
    public RedirectResult Get()
    {
        return RedirectPermanent("https://www.google.com");
    }

Android sqlite how to check if a record exists

I have tried all methods mentioned in this page, but only below method worked well for me.

Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
 showMessage("Error", "Record exist");
}
else
{
 // Inserting record
}

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

Execute Shell Script after post build in Jenkins

You'd have to set up the post-build shell script as a separate Jenkins job and trigger it as a post-build step. It looks like you will need to use the Parameterized Trigger Plugin as the standard "Build other projects" option only works if your triggering build is successful.

fatal error LNK1169: one or more multiply defined symbols found in game programming

You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.

The #pragma once is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.

You could declare the variables as extern in the header file, and then define them in a single source file. Or you could declare the variables as const in the header file and then the compiler and linker will manage it.

How to delete a record in Django models?

you can delete the objects directly from the admin panel or else there is also an option to delete specific or selected id from an interactive shell by typing in python3 manage.py shell (python3 in Linux). If you want the user to delete the objects through the browser (with provided visual interface) e.g. of an employee whose ID is 6 from the database, we can achieve this with the following code, emp = employee.objects.get(id=6).delete()

THIS WILL DELETE THE EMPLOYEE WITH THE ID is 6.

If you wish to delete the all of the employees exist in the DB instead of get(), specify all() as follows: employee.objects.all().delete()

Center a button in a Linear layout

Center using a LinearLayout:

<LinearLayout
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/btnFindMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/findme" />
</LinearLayout>

Create instance of generic type in Java?

If you want not to type class name twice during instantiation like in:

new SomeContainer<SomeType>(SomeType.class);

You can use factory method:

<E> SomeContainer<E> createContainer(Class<E> class); 

Like in:

public class Container<E> {

    public static <E> Container<E> create(Class<E> c) {
        return new Container<E>(c);
    }

    Class<E> c;

    public Container(Class<E> c) {
        super();
        this.c = c;
    }

    public E createInstance()
            throws InstantiationException,
            IllegalAccessException {
        return c.newInstance();
    }

}

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

That method was introduced in Commons Codec 1.4. This exception indicates that you've an older version of Commons Codec somewhere else in the webapp's runtime classpath which got precedence in classloading. Check all paths covered by the webapp's runtime classpath. This includes among others the Webapp/WEB-INF/lib, YourAppServer/lib, JRE/lib and JRE/lib/ext. Finally remove or upgrade the offending older version.


Update: as per the comments, you can't seem to locate it. I can only suggest to outcomment the code using that newer method and then put the following line in place:

System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());

That should print the absolute path to the JAR file where it was been loaded from during runtime.


Update 2: this did seem to point to the right file. Sorry, I can't explain your problem anymore right now. All I can suggest is to use a different Base64 method like encodeBase64(byte[]) and then just construct a new String(bytes) yourself. Or you could drop that library and use a different Base64 encoder, for example this one.

jQuery SVG, why can't I addClass?

I wrote this in my project, and it works... probably;)

$.fn.addSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        if(attr.indexOf(className) < 0) {
            $(this).attr('class', attr+' '+className+ ' ')
        }
    })
};    

$.fn.removeSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        attr = attr.replace(className , ' ')
        $(this).attr('class' , attr)
    })
};    

examples

$('path').addSvgClass('fillWithOrange')
$('path').removeSvgClass('fillWithOrange')

Dynamically adding properties to an ExpandoObject

dynamic x = new ExpandoObject();
x.NewProp = string.Empty;

Alternatively:

var x = new ExpandoObject() as IDictionary<string, Object>;
x.Add("NewProp", string.Empty);

Calculate the number of business days between two dates?

I used the following code to also take in to account bank holidays:

public class WorkingDays
{
    public List<DateTime> GetHolidays()
    {
        var client = new WebClient();
        var json = client.DownloadString("https://www.gov.uk/bank-holidays.json");
        var js = new JavaScriptSerializer();
        var holidays = js.Deserialize <Dictionary<string, Holidays>>(json);
        return holidays["england-and-wales"].events.Select(d => d.date).ToList();
    }

    public int GetWorkingDays(DateTime from, DateTime to)
    {
        var totalDays = 0;
        var holidays = GetHolidays();
        for (var date = from.AddDays(1); date <= to; date = date.AddDays(1))
        {
            if (date.DayOfWeek != DayOfWeek.Saturday
                && date.DayOfWeek != DayOfWeek.Sunday
                && !holidays.Contains(date))
                totalDays++;
        }

        return totalDays;
    }
}

public class Holidays
{
    public string division { get; set; }
    public List<Event> events { get; set; }
}

public class Event
{
    public DateTime date { get; set; }
    public string notes { get; set; }
    public string title { get; set; }
}

And Unit Tests:

[TestClass]
public class WorkingDays
{
    [TestMethod]
    public void SameDayIsZero()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 12);

        Assert.AreEqual(0, service.GetWorkingDays(from, from));

    }

    [TestMethod]
    public void CalculateDaysInWorkingWeek()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 12);
        var to = new DateTime(2013, 8, 16);

        Assert.AreEqual(4, service.GetWorkingDays(from, to), "Mon - Fri = 4");

        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 13)), "Mon - Tues = 1");
    }

    [TestMethod]
    public void NotIncludeWeekends()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 9);
        var to = new DateTime(2013, 8, 16);

        Assert.AreEqual(5, service.GetWorkingDays(from, to), "Fri - Fri = 5");

        Assert.AreEqual(2, service.GetWorkingDays(from, new DateTime(2013, 8, 13)), "Fri - Tues = 2");
        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 12)), "Fri - Mon = 1");
    }

    [TestMethod]
    public void AccountForHolidays()
    {
        var service = new WorkingDays();

        var from = new DateTime(2013, 8, 23);

        Assert.AreEqual(0, service.GetWorkingDays(from, new DateTime(2013, 8, 26)), "Fri - Mon = 0");

        Assert.AreEqual(1, service.GetWorkingDays(from, new DateTime(2013, 8, 27)), "Fri - Tues = 1");
    }
}

WPF chart controls

Free tools supporting panning / zooming:

Free tools without built in pan / zoom support:

Paid tools with built in pan / zoom support:

Full Disclosure: I have been heavily involved in development of Visiblox, hence I know that library in much more detail than the others.

Fatal error: Namespace declaration statement has to be the very first statement in the script in

In my case, the file was created with UTF-8-BOM encoding. I have to save it into UTF-8 encoding, then everything works fine.

Get week number (in the year) from a date PHP

This get today date then tell the week number for the week

<?php
 $date=date("W");
 echo $date." Week Number";
 ?>

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

How to have css3 animation to loop forever

I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.

Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div is restored, forcing the animations to restart.

All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head> section of your page:

<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>

BTW, the closing </head> in your code is misplaced: it must be before the starting <body>.

A transport-level error has occurred when receiving results from the server

Was getting this, always after about 5 minutes of operation. Investigated and found that a warning from e1iexpress always occurred before the failure. This apparently is an error having to do with certain TCP/IP adapters. But changing from WiFi to hardwired didn't affect it.

So tried Plan B and restarted Visual Studio. Then it worked fine.

On closer study I noticed that, when working correctly, the message The Thread '<No Name>' has exited with code 0 occurred at almost exactly the time the run crashed in previous attempts. Some Googling reveals that that message comes up when (among other things) the server is trimming the thread pool.

Presumably there was a bogus thread in the thread pool and every time the server attempted to "trim" it it took the app down.

Is Tomcat running?

wget url or curl url where url is a url of the tomcat server that should be available, for example: wget http://localhost:8080. Then check the exit code, if it's 0 - tomcat is up.

Reading file from Workspace in Jenkins with Groovy script

If you already have the Groovy (Postbuild) plugin installed, I think it's a valid desire to get this done with (generic) Groovy instead of installing a (specialized) plugin.

That said, you can get the workspace using manager.build.workspace.getRemote(). Don't forget to add File.separator between path and file name.

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

Dropping Unique constraint from MySQL table

For WAMP 3.0 : Click Structure Below Add 1 Column you will see '- Indexes' Click -Indexes and drop whichever index you want.

Base64 length calculation?

For reference, the Base64 encoder's length formula is as follows:

Base64 encoder's length formula

As you said, a Base64 encoder given n bytes of data will produce a string of 4n/3 Base64 characters. Put another way, every 3 bytes of data will result in 4 Base64 characters. EDIT: A comment correctly points out that my previous graphic did not account for padding; the correct formula is Ceiling(4n/3).

The Wikipedia article shows exactly how the ASCII string Man encoded into the Base64 string TWFu in its example. The input string is 3 bytes, or 24 bits, in size, so the formula correctly predicts the output will be 4 bytes (or 32 bits) long: TWFu. The process encodes every 6 bits of data into one of the 64 Base64 characters, so the 24-bit input divided by 6 results in 4 Base64 characters.

You ask in a comment what the size of encoding 123456 would be. Keeping in mind that every every character of that string is 1 byte, or 8 bits, in size (assuming ASCII/UTF8 encoding), we are encoding 6 bytes, or 48 bits, of data. According to the equation, we expect the output length to be (6 bytes / 3 bytes) * 4 characters = 8 characters.

Putting 123456 into a Base64 encoder creates MTIzNDU2, which is 8 characters long, just as we expected.

Switch/toggle div (jQuery)

I used this way to do that for multiple blocks without conjuring new JavaScript code:

<a href="#" data-toggle="thatblock">Show/Hide Content</a>

<div id="thatblock" style="display: none">
  Here is some description that will appear when we click on the button
</div>

Then a JavaScript portion for all such cases:

$(function() {
  $('*[data-toggle]').click(function() {
    $('#'+$(this).attr('data-toggle')).toggle();
    return false;
  });
});

Is there a way to call a stored procedure with Dapper?

Same from above, bit more detailed

Using .Net Core

Controller

public class TestController : Controller
{
    private string connectionString;

    public IDbConnection Connection
    {
        get { return new SqlConnection(connectionString); }
    }

    public TestController()
    {
        connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
    }

    public JsonResult GetEventCategory(string q)
    {
        using (IDbConnection dbConnection = Connection)
        {
            var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
    commandType: CommandType.StoredProcedure).FirstOrDefault();

            return Json(categories);
        }
    }

    public class ResultTokenInput
    {
        public int ID { get; set; }
        public string name { get; set; }            
    }
}

Stored Procedure ( parent child relation )

create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
    BEGIN

    WITH CTE(Id, Name, IdHierarchy,parentId) AS
    (
      SELECT 
        e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
        cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
      FROM 
        EventCategory e  where e.Title like '%'+@keyword+'%'
     -- WHERE 
      --  parentid = @parentid

      UNION ALL

      SELECT 
        p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
        c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
      FROM 
        EventCategory p 
      JOIN  CTE c ON c.Id = p.parentid

        where p.Title like '%'+@keyword+'%'
    )
    SELECT 
      * 
    FROM 
      CTE
    ORDER BY 
      IdHierarchy

References in case

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;

Delete all documents from index/type without deleting type

You have these alternatives:

1) Delete a whole index:

curl -XDELETE 'http://localhost:9200/indexName'             

example:

curl -XDELETE 'http://localhost:9200/mentorz'

For more details you can find here -https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html

2) Delete by Query to those that match:

curl -XDELETE 'http://localhost:9200/mentorz/users/_query' -d                
    '{
        "query":
            {
                "match_all": {}
            }
    }'

*Here mentorz is an index name and users is a type

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

How to programmatically take a screenshot on Android?

For system applications only!

Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();

Note: System applications don't need to run "su" to execute this command.

removing bold styling from part of a header

<h1 style="font-weight: normal;"></h1>

try this?

How to get a float result by dividing two integer values using T-SQL?

I understand that CASTing to FLOAT is not allowed in MySQL and will raise an error when you attempt to CAST(1 AS float) as stated at MySQL dev.

The workaround to this is a simple one. Just do

(1 + 0.0)

Then use ROUND to achieve a specific number of decimal places like

ROUND((1+0.0)/(2+0.0), 3)

The above SQL divides 1 by 2 and returns a float to 3 decimal places, as in it would be 0.500.

One can CAST to the following types: binary, char, date, datetime, decimal, json, nchar, signed, time, and unsigned.

Unix epoch time to Java Date object

To convert seconds time stamp to millisecond time stamp. You could use the TimeUnit API and neat like this.

long milliSecondTimeStamp = MILLISECONDS.convert(secondsTimeStamp, SECONDS)

How do I type a TAB character in PowerShell?

In the Windows command prompt you can disable tab completion, by launching it thusly:

cmd.exe /f:off

Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.

The cmd.exe help page explains it:

You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar

    and/or

HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar

with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.

If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.

unix sort descending order

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

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

or

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

How to run a jar file in a linux commandline

sudo -sH
java -jar filename.jar

Keep in mind to never run executable file in as root.

When to use static methods

I found a nice description, when to use static methods:

There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :

  1. If a method doesn't modify state of object, or not using any instance variables.

  2. You want to call method without creating instance of that class.

  3. A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.

  4. Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.

  5. If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.

Source is here

Entity Framework rollback and remove bad migration

First, Update your last perfect migration via this command :

Update-Database –TargetMigration

Example:

Update-Database -20180906131107_xxxx_xxxx

And, then delete your unused migration manually.

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

Parse usable Street Address, City, State, Zip from a string

I've been working in the address processing domain for about 5 years now, and there really is no silver bullet. The correct solution is going to depend on the value of the data. If it's not very valuable, throw it through a parser as the other answers suggest. If it's even somewhat valuable you'll definitely need to have a human evaluate/correct all the results of the parser. If you're looking for a fully automated, repeatable solution, you probably want to talk to a address correction vendor like Group1 or Trillium.

Restore a deleted file in the Visual Studio Code Recycle Bin

who still facing the problem on linux and didnt find it on trash try this solution

https://github.com/Microsoft/vscode/issues/32078#issuecomment-434393058

find / -name "delete_file_name"

MySQL InnoDB not releasing disk space after deleting data rows from table

Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces

Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf

 #undo tablespace
  innodb_undo_directory =  /var/lib/mysql/
  innodb_rollback_segments = 128 
  innodb_undo_tablespaces = 3
  innodb_undo_logs = 128  
  innodb_max_undo_log_size=1G
  innodb_undo_log_truncate = ON

Start mysql service
store mysqldump backup

Problem resolved !!

document .click function for touch device

To trigger the function with click or touch, you could change this:

$(document).click( function () {

To this:

$(document).on('click touchstart', function () {

Or this:

$(document).on('click touch', function () {

The touchstart event fires as soon as an element is touched, the touch event is more like a "tap", i.e. a single contact on the surface. You should really try each of these to see what works best for you. On some devices, touch can be a little harder to trigger (which may be a good or bad thing - it prevents a drag being counted, but an accidental small drag may cause it to not be fired).

Easiest way to mask characters in HTML(5) text input

Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.

However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown event to block key input before it displays on the screen.

How to create a directory and give permission in single command

you can use following command to create directory and give permissions at the same time

mkdir -m777 path/foldername 

MySQL CONCAT returns NULL if any field contain NULL

To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)

Fade In Fade Out Android Animation in Java

As I believe in the power of XML (for layouts), this is the equivalent for the accepted answer, but purely as an animation resource:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:interpolator/accelerate_decelerate"
    android:fillAfter="true">
    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="1000" />
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0"
        android:duration="1000"
        android:startOffset="1000"/>
</set>

The fillAfter is for the fade to remain after completing the animation. The interpolator handles interpolation of the animations, as you can guess. You can also use other types of interpolators, like Linear or Overshoot.

Be sure to start your animation on your view:

yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.fade));

splitting a number into the integer and decimal parts

We can use a not famous built-in function; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

How to add new contacts in android

There are several good articles on the subject on dev2qa.com site, about Contacts Provider API:

How To Add Contact In Android Programmatically

How To Update Delete Android Contacts Programmatically

How To Get Contact List In Android Programmatically

Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure

Official Google documentation on Contacts Provider here

How to center buttons in Twitter Bootstrap 3?

I had this problem. I used

<div class = "col-xs-8 text-center">

On my div containing a few h3 lines, a couple h4 lines and a Bootstrap button. Everything besides the button jumped to the center after I used text-center so I went into my CSS sheet overriding Bootstrap and gave the button a

margin: auto;

which seems to have solved the problem.

Calculate execution time of a SQL query?

try this

DECLARE @StartTime DATETIME
SET @StartTime = GETDATE()

  SET @EndTime = GETDATE()
  PRINT 'StartTime = ' + CONVERT(VARCHAR(30),@StartTime,121)
  PRINT '  EndTime = ' + CONVERT(VARCHAR(30),@EndTime,121)
  PRINT ' Duration = ' + CONVERT(VARCHAR(30),@EndTime -@starttime,114)

If that doesn't do it, then try SET STATISTICS TIME ON

@ViewChild in *ngIf

An alternative to overcome this is running the change detector manually.

You first inject the ChangeDetectorRef:

constructor(private changeDetector : ChangeDetectorRef) {}

Then you call it after updating the variable that controls the *ngIf

show() {
        this.display = true;
        this.changeDetector.detectChanges();
    }

jquery function setInterval

// simple example using the concept of setInterval

$(document).ready(function(){
var g = $('.jumping');
function blink(){
  g.animate({ 'left':'50px' 
  }).animate({
     'left':'20px'
        },1000)
}
setInterval(blink,1500);
});

How can we draw a vertical line in the webpage?

That's no struts related problem but rather plain HMTL/CSS.

I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

You need to add this at start of your php page "login.php"

<?php header('Access-Control-Allow-Origin: *'); ?>

How to find the process id of a running Java process on Windows? And how to kill the process alone?

You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.

Then use the Windows task manager to terminate the process. If you want to do it on the command line, use

TASKKILL /PID %PID%

Python: Ignore 'Incorrect padding' error when base64 decoding

Incorrect padding error is caused because sometimes, metadata is also present in the encoded string If your string looks something like: 'data:image/png;base64,...base 64 stuff....' then you need to remove the first part before decoding it.

Say if you have image base64 encoded string, then try below snippet..

from PIL import Image
from io import BytesIO
from base64 import b64decode
imagestr = 'data:image/png;base64,...base 64 stuff....'
im = Image.open(BytesIO(b64decode(imagestr.split(',')[1])))
im.save("image.png")

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

Java: Insert multiple rows into MySQL with PreparedStatement

In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2

Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.

public Connection getConnection(boolean autoCommit) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(autoCommit);
    return conn;
}

private void testBatchInsert(int count, int maxBatchSize) {
    String querySql = "insert into batch_test(keyword) values(?)";
    try {
        Connection connection = getConnection(false);
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean success = true;
        int[] executeResult = null;
        try {
            pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < count; i++) {
                pstmt.setString(1, UUID.randomUUID().toString());
                pstmt.addBatch();
                if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
                    executeResult = pstmt.executeBatch();
                }
            }
            ResultSet ids = pstmt.getGeneratedKeys();
            for (int i = 0; i < executeResult.length; i++) {
                ids.next();
                if (executeResult[i] == 1) {
                    System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
                            + ids.getLong(1));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (connection != null) {
                if (success) {
                    connection.commit();
                } else {
                    connection.rollback();
                }
                connection.close();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

How to create a DB for MongoDB container on start up?

In case someone is looking for how to configure MongoDB with authentication using docker-compose, here is a sample configuration using environment variables:

version: "3.3"

services:

  db:
      image: mongo
      environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=<YOUR_PASSWORD>
      ports:
        - "27017:27017"

When running docker-compose up your mongo instance is run automatically with auth enabled. You will have a admin database with the given password.

Easily measure elapsed time

I needed to measure the execution time of individual functions within a library. I didn't want to have to wrap every call of every function with a time measuring function because its ugly and deepens the call stack. I also didn't want to put timer code at the top and bottom of every function because it makes a mess when the function can exit early or throw exceptions for example. So what I ended up doing was making a timer that uses its own lifetime to measure time.

In this way I can measure the wall-time a block of code took by just instantiating one of these objects at the beginning of the code block in question (function or any scope really) and then allowing the instances destructor to measure the time elapsed since construction when the instance goes out of scope. You can find the full example here but the struct is extremely simple:

template <typename clock_t = std::chrono::steady_clock>
struct scoped_timer {
  using duration_t = typename clock_t::duration;
  const std::function<void(const duration_t&)> callback;
  const std::chrono::time_point<clock_t> start;

  scoped_timer(const std::function<void(const duration_t&)>& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  scoped_timer(std::function<void(const duration_t&)>&& finished_callback) :
      callback(finished_callback), start(clock_t::now()) { }
  ~scoped_timer() { callback(clock_t::now() - start); }
};

The struct will call you back on the provided functor when it goes out of scope so you can do something with the timing information (print it or store it or whatever). If you need to do something even more complex you could even use std::bind with std::placeholders to callback functions with more arguments.

Here's a quick example of using it:

void test(bool should_throw) {
  scoped_timer<> t([](const scoped_timer<>::duration_t& elapsed) {
    auto e = std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(elapsed).count();
    std::cout << "took " << e << "ms" << std::endl;
  });

  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (should_throw)
    throw nullptr;

  std::this_thread::sleep_for(std::chrono::seconds(1));
}

If you want to be more deliberate, you can also use new and delete to explicitly start and stop the timer without relying on scoping to do it for you.

How to mock location on device?

I've created a simple Handler simulating a moving position from an initial position.

Start it in your connection callback :

private final GoogleApiClient.ConnectionCallbacks mConnectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
    @Override
    public void onConnected(Bundle bundle) {
        if (BuildConfig.USE_MOCK_LOCATION) {
            LocationServices.FusedLocationApi.setMockMode(mGoogleApiClient, true);
            new MockLocationMovingHandler(mGoogleApiClient).start(48.873399, 2.342911);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }
};

The Handler class :

   private static class MockLocationMovingHandler extends Handler {

    private final static int SET_MOCK_LOCATION = 0x000001;
    private final static double STEP_LATITUDE =  -0.00005;
    private final static double STEP_LONGITUDE = 0.00002;
    private final static long FREQUENCY_MS = 1000;
    private GoogleApiClient mGoogleApiClient;
    private double mLatitude;
    private double mLongitude;

    public MockLocationMovingHandler(final GoogleApiClient googleApiClient) {
        super(Looper.getMainLooper());
        mGoogleApiClient = googleApiClient;
    }

    public void start(final double initLatitude, final double initLongitude) {
        if (hasMessages(SET_MOCK_LOCATION)) {
            removeMessages(SET_MOCK_LOCATION);
        }
        mLatitude = initLatitude;
        mLongitude = initLongitude;
        sendEmptyMessage(SET_MOCK_LOCATION);
    }

    public void stop() {
        if (hasMessages(SET_MOCK_LOCATION)) {
            removeMessages(SET_MOCK_LOCATION);
        }
    }

    @Override
    public void handleMessage(Message message) {
        switch (message.what) {
            case SET_MOCK_LOCATION:
                Location location = new Location("network");
                location.setLatitude(mLatitude);
                location.setLongitude(mLongitude);
                location.setTime(System.currentTimeMillis());
                location.setAccuracy(3.0f);
                location.setElapsedRealtimeNanos(System.nanoTime());
                LocationServices.FusedLocationApi.setMockLocation(mGoogleApiClient, location);

                mLatitude += STEP_LATITUDE;
                mLongitude += STEP_LONGITUDE;
                sendEmptyMessageDelayed(SET_MOCK_LOCATION, FREQUENCY_MS);
                break;
        }
    }
}

Hope it can help..

How can I uninstall an application using PowerShell?

I will make my own little contribution. I needed to remove a list of packages from the same computer. This is the script I came up with.

$packages = @("package1", "package2", "package3")
foreach($package in $packages){
  $app = Get-WmiObject -Class Win32_Product | Where-Object {
    $_.Name -match "$package"
  }
  $app.Uninstall()
}

I hope this proves to be useful.

Note that I owe David Stetler the credit for this script since it is based on his.

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

CSS: On hover show and hide different div's at the same time?

Have you tried somethig like this?

.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}

<div class="showhim">HOVER ME
  <div class="showme">hai</div>
  <div class="hideme">bye</div>
</div>

I dont know any reason why it shouldn't be possible.

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

Android: show/hide a view using an animation

Try to use TranslateAnimation class, which creates the animation for position changes. Try reading this for help - http://developer.android.com/reference/android/view/animation/TranslateAnimation.html

Update: Here's the example for this. If you have the height of your view as 50 and in the hide mode you want to show only 10 px. The sample code would be -

TranslateAnimation anim=new TranslateAnimation(0,0,-40,0);
anim.setFillAfter(true);
view.setAnimation(anim);

PS: There are lot's or other methods there to help you use the animation according to your need. Also have a look at the RelativeLayout.LayoutParams if you want to completely customize the code, however using the TranslateAnimation is easier to use.

EDIT:-Complex version using LayoutParams

RelativeLayout relParam=new RelativeLayout.LayoutParam(RelativeLayout.LayoutParam.FILL_PARENT,RelativeLayout.LayoutParam.WRAP_CONTENT); //you can give hard coded width and height here in (width,height) format.
relParam.topMargin=-50; //any number that work.Set it to 0, when you want to show it.
view.setLayoutParams(relparam);

This example code assumes you are putting your view in RelativeLayout, if not change the name of Layout, however other layout might not work. If you want to give an animation effect on them, reduce or increase the topMargin slowly. You can consider using Thread.sleep() there too.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

I dealt with this before & had posted in the spring forums.

http://forum.spring.io/forum/spring-projects/data/123129-frustrated-with-emptyresultdataaccessexception

The advice we received was to use a type of SQlQuery. Here's an example of what we did when trying to get a value out of a DB that might not be there.

@Component
public class FindID extends MappingSqlQuery<Long> {

        @Autowired
        public void setDataSource(DataSource dataSource) {

                String sql = "Select id from address where id = ?";

                super.setDataSource(dataSource);

                super.declareParameter(new SqlParameter(Types.VARCHAR));

                super.setSql(sql);

                compile();
        }

        @Override
        protected Long mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong(1);
        }

In the DAO then we just call...

Long id = findID.findObject(id);

Not clear on performance, but it works and is neat.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

If you're instantiating an android.support.v4.app.Fragment class, the you have to call getActivity().getSupportFragmentManager() to get rid of the cannot-resolve problem. However the official Android docs on Fragment by Google tends to over look this simple problem and they still document it without the getActivity() prefix.

How to change PHP version used by composer

I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.

PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)

export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH

jQuery click events firing multiple times

I had a problem because of markup.

HTML:

<div class="myclass">
 <div class="inner">

  <div class="myclass">
   <a href="#">Click Me</a>
  </div>

 </div>
</div>

jQuery

$('.myclass').on('click', 'a', function(event) { ... } );

You notice I have the same class 'myclass' twice in html, so it calls click for each instance of div.

convert float into varchar in SQL server without scientific notation

Below is an example where we can convert float value without any scientific notation.

DECLARE @Floater AS FLOAT = 100000003.141592653

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SET @Floater = @Floater * 10

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SET @Floater = @Floater * 100

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SELECT LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
      ,FORMAT(@Floater, '')

In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.

How to close off a Git Branch?

We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).

My fingers have memorized our process:

git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.

Finding the mode of a list

Perhaps try the following. It is O(n) and returns a list of floats (or ints). It is thoroughly, automatically tested. It uses collections.defaultdict, but I'd like to think you're not opposed to using that. It can also be found at https://stromberg.dnsalias.org/~strombrg/stddev.html

def compute_mode(list_: typing.List[float]) -> typing.List[float]:
    """                       
    Compute the mode of list_.

    Note that the return value is a list, because sometimes there is a tie for "most common value".
                                                                        
    See https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
    """                                                                                                        
    if not list_:
        raise ValueError('Empty list')
    if len(list_) == 1:           
        raise ValueError('Single-element list')
    value_to_count_dict: typing.DefaultDict[float, int] = collections.defaultdict(int)
    for element in list_:
        value_to_count_dict[element] += 1
    count_to_values_dict = collections.defaultdict(list)
    for value, count in value_to_count_dict.items():   
        count_to_values_dict[count].append(value)                           
    counts = list(count_to_values_dict)
    if len(counts) == 1:                                                                            
        raise ValueError('All elements in list are the same')          
    maximum_occurrence_count = max(counts)
    if maximum_occurrence_count == 1:
        raise ValueError('No element occurs more than once')
    minimum_occurrence_count = min(counts)
    if maximum_occurrence_count <= minimum_occurrence_count:
        raise ValueError('Maximum count not greater than minimum count')
    return count_to_values_dict[maximum_occurrence_count]

How do I set path while saving a cookie value in JavaScript?

For access cookie in whole app (use path=/):

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/"; 
}

Note:

If you set path=/,
Now the cookie is available for whole application/domain. If you not specify the path then current cookie is save just for the current page you can't access it on another page(s).

For more info read- http://www.quirksmode.org/js/cookies.html (Domain and path part)

If you use cookies in jquery by plugin jquery-cookie:

$.cookie('name', 'value', { expires: 7, path: '/' });
//or
$.cookie('name', 'value', { path: '/' });

What is the difference between XAMPP or WAMP Server & IIS?

WAMP stands for Windows,Apache,Mysql,Php

XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)

Advantages of XAMPP:

  • It is cross-platform software

  • It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.

  • it is easy to configure and use.

Advantages of WAMP:

  • It is easy to Use. (Changing Configuration)

  • WAMP is Available for both 64 bit and 32-bit system.

if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.

i suggest using laragon :

Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.

Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.

Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.

Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.

Advantages of Laragon:

  • Pretty URLs
    Use app.test instead of localhost/app.

  • Portable
    You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.

  • Isolated
    Laragon has an isolated environment with your OS - it will keep your system clean.

  • Easy Operation

    Unlike others which pre-config for you, Laragon auto-configsall the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.

  • Modern & Powerful
    Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed. Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.

How do you get an iPhone's device name

In Unity, using C#:

SystemInfo.deviceName;

How can I close a window with Javascript on Mozilla Firefox 3?

For security reasons, your script cannot close a window/tab that it did not open.

The solution is to present the age prompt at an earlier point in the navigation history. Then, you can choose to allow them to enter your site or not based on their input.

Instead of closing the page that presents the prompt, you can simply say, "Sorry", or perhaps redirect the user to their homepage.

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

How to run a shell script on a Unix console or Mac terminal?

Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.

As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.

#!./php7.2
<?php

echo "Hello!"; 

To run it:

./hello

Which behave just as equal as:

./php7.2 hello

The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.

Converting json results to a date

You need to extract the number from the string, and pass it into the Date constructor:

var x = [{
    "id": 1,
    "start": "\/Date(1238540400000)\/"
}, {
    "id": 2,
    "start": "\/Date(1238626800000)\/"
}];

var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/\d+/)[0]                - extract the numeric part
x[0].start.match(/\d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object

Get my phone number in android

As Answered here

Use below code :

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

In AndroidManifest.xml, give the following permission:

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

But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.

Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!

Suggested Workaround:

  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.

Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

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

Primary key is a subset of super key. Which is uniquely define and other field are depend on it. In a table their can be just one primary key and rest sub set are candidate key or alternate keys.

How can I add JAR files to the web-inf/lib folder in Eclipse?

From the ToolBar to go Project> Properties>Java Build Path > Add External Jars. Locate the File on the local disk or web Directory and Click Open.

This will automatically add the required Jar files to the Library.

Google Chrome redirecting localhost to https

Open Chrome Developer Tools -> go to Network -> select Disable Cache -> reload

Find the paths between two given nodes?

What you're trying to do is essentially to find a path between two vertices in a (directed?) graph check out Dijkstra's algorithm if you need shortest path or write a simple recursive function if you need whatever paths exist.

How do you access the element HTML from within an Angular attribute directive?

So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element.

What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML.

Which will lead to the answer to your original question:

let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element

Update for better approach:

Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.

The best way to manipulate DOM Elements programmatically is using the Renderer:

constructor(private _elemRef: ElementRef, private _renderer: Renderer) { 
    this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}

Edit

Since Renderer is deprecated now, use Renderer2 instead with setProperty


Update:

This question with its answer explained the console.log behavior.

Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation.


Hope this helped.

Using mysql concat() in WHERE clause?

There's a few things that could get in the way - is your data clean?

It could be that you have spaces at the end of the first name field, which then means you have two spaces between the firstname and lastname when you concat them? Using trim(first_name)/trim(last_name) will fix this - although the real fix is to update your data.

You could also this to match where two words both occur but not necessarily together (assuming you are in php - which the $search_term variable suggests you are)

$whereclauses=array();
$terms = explode(' ', $search_term);
foreach ($terms as $term) {
    $term = mysql_real_escape_string($term);
    $whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

git: fatal unable to auto-detect email address

I get this error when running git stash. Fixed with:

git config --global user.email {emailaddress}
git config --global user.name {name}

Maven Unable to locate the Javac Compiler in:

I am able to resolved by doing following steps :

Right click on project select Build path -> Configure build path -> select Libraries Tab -> then select JRE System Library[version you have for me its JavaSE-1.7] - > click Edit button -> In JRE System Library window select Execution environment - In drop down you can select the JDK listed for me its JavaSE-1.7 -> next to this click to Environments button -> In Execution Environments window you have to again select your java SE for me its JavaSE-1.7 -> just select it, you will have options in Compatible JREs tab, so select JDK that you want to have in my case its jdk1.7.0_25.


Click ok and finish the rest windows by doing appropriate action Ok/Finish.

Lastly do Maven Clean and Maven Install.

What is the attribute property="og:title" inside meta tag?

Probably part of Open Graph Protocol for Facebook.

Edit: guess not only Facebook - that's only one example of using it.

What does AND 0xFF do?

Anding an integer with 0xFF leaves only the least significant byte. For example, to get the first byte in a short s, you can write s & 0xFF. This is typically referred to as "masking". If byte1 is either a single byte type (like uint8_t) or is already less than 256 (and as a result is all zeroes except for the least significant byte) there is no need to mask out the higher bits, as they are already zero.

See tristopiaPatrick Schlüter's answer below when you may be working with signed types. When doing bitwise operations, I recommend working only with unsigned types.

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

This may help someone else facing similar issue.

Instead of putting the file floating in the same directory as the Dockerfile, create a dir and place the file to copy and then try.

COPY mydir/test.json /home/test.json
COPY mydir/test.json /home/test.json

How do you read CSS rule values with JavaScript?

Here is code to iterate through all rules in a page:

_x000D_
_x000D_
function iterateCSS(f) {_x000D_
  for (const styleSheet of window.document.styleSheets) {_x000D_
    const classes = styleSheet.rules || styleSheet.cssRules;_x000D_
    if (!classes) continue;_x000D_
_x000D_
    for (const cssRule of classes) {_x000D_
      if (cssRule.type !== 1 || !cssRule.style) continue;_x000D_
      const selector = cssRule.selectorText, style=cssRule.style;_x000D_
      if (!selector || !style.cssText) continue;_x000D_
      for (let i=0; i<style.length; i++) {_x000D_
        const propertyName=style.item(i);_x000D_
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {_x000D_
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');_x000D_
});
_x000D_
_x000D_
_x000D_

Replace String in all files in Eclipse

I have tried the following option in Helios Version of Eclipse. Simply press CTRL+F you will get the "Find/Replace" Window on your screen

enter image description here

JQuery string contains check

You can use javascript's indexOf function.

_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

How to check all checkboxes using jQuery?

    <p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3

And jquery

$(document).on('click','#checkAll',function () {
     $('.checkItem').not(this).prop('checked', this.checked);
 });

Is it possible to log all HTTP request headers with Apache?

mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.

Here is how to use it.

LoadModule log_forensic_module /usr/lib64/httpd/modules/mod_log_forensic.so 
<IfModule log_forensic_module> 
ForensicLog /var/log/httpd/forensic_log 
</IfModule> 

cd into directory without having permission

I know this post is old, but what i had to do in the case of the above answers on Linux machine was:

sudo chmod +x directory

HTTP client timeout and server timeout

There's many forms of timeout, are you after the connection timeout, request timeout or time to live (time before TCP connection stops).

The default TimeToLive on Firefox is 115s (network.http.keep-alive.timeout)

The default connection timeout on Firefox is 250s (network.http.connection-retry-timeout)

The default request timeout for Firefox is 30s (network.http.pipelining.read-timeout).

The time it takes to do an HttpRequest depends on if a connection has been made this has to be within 250s which I'm guessing you're not after. You're probably after the request timeout which I think is 30,000ms (30s) so to conclude I'd say it's timing out with a connection time out that's why you got a response back after ~150s though I haven't really tested this.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is rather verbose and don't like it but it's the only thing that worked for me:

if (inputFile && inputFile.current) {
        ((inputFile.current as never) as HTMLInputElement).click()
}

only

if (inputFile && inputFile.current) {
        inputFile.current.click() // also with ! or ? didn't work
}

didn't work for me. Typesript version: 3.9.7 with eslint and recommended rules.

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

How can I break from a try/catch block without throwing an exception in Java

Various ways:

  • return
  • break or continue when in a loop
  • break to label when in a labeled statement (see @aioobe's example)
  • break when in a switch statement.

...

  • System.exit() ... though that's probably not what you mean.

In my opinion, "break to label" is the most natural (least contorted) way to do this if you just want to get out of a try/catch. But it could be confusing to novice Java programmers who have never encountered that Java construct.

But while labels are obscure, in my opinion wrapping the code in a do ... while (false) so that you can use a break is a worse idea. This will confuse non-novices as well as novices. It is better for novices (and non-novices!) to learn about labeled statements.


By the way, return works in the case where you need to break out of a finally. But you should avoid doing a return in a finally block because the semantics are a bit confusing, and liable to give the reader a headache.

Difference between BYTE and CHAR in column datatypes

Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.

If you define the field as VARCHAR2(11 BYTE), Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters.

By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.

Please initialize the log4j system properly. While running web service

Those messages are something tricky, enough so that people created this to make it clearer: https://issues.apache.org/bugzilla/show_bug.cgi?id=25747

What's tricky about them is that the warnings are written if Log4j can't find its log4j.properties (or log4j.xml) file, but also if the file is fine and dandy but its content is not complete from a configuration point of view.

The following paragraph is taken from here: http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_9/docs/TROUBLESHOOT.html

Logging output is written to a target by using an appender. If no appenders are attached to a category nor to any of its ancestors, you will get the following message when trying to log:

log4j: No appenders could be found for category (some.category.name).
log4j: Please initialize the log4j system properly.

Log4j does not have a default logging target. It is the user's responsibility to ensure that all categories can inherit an appender. This can be easily achieved by attaching an appender to the root category.

You can find info on how to configure the root logger (log4j.rootLogger) in the log4j documentation, basically adding something as simple as this at the beginning of the file:

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

This should clear those WARN messages you get on startup (make sure you don't already have an appender named stdout; also be carefull of what level you give the root logger, debug will be very verbose and every library in your app will start writing stuff to the console).

As about the log4j.properties/log4j.xml, I suggest you place this file in /WEB-INF/classes as it is important to have it exposed for different tweaks (activating/deactivating logs, changing log levels etc). You can have it inside a JAR in the classpath also (as you specified in your comment), but it will be enclosed in the archive (hopefully in the right place inside the archive) and won't be as easy to handle as if it were in /WEB-INF/classes.

How to change title of Activity in Android?

Try setTitle by itself, like this:

setTitle("Hello StackOverflow");

Catching errors in Angular HttpClient

The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor (hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.

To do this you will need to generate a stack in an extended HttpClient, so its not advisable to do this in a production environment.

/**
 * Extended HttpClient that generates a stack trace on error when not in a production build.
 */
@Injectable()
export class TraceHttpClient extends HttpClient {
  constructor(handler: HttpHandler) {
    super(handler);
  }

  request(...args: [any]): Observable<any> {
    const stack = environment.production ? null : Error().stack;
    return super.request(...args).pipe(
      catchError((err) => {
        // tslint:disable-next-line:no-console
        if (stack) console.error('HTTP Client error stack\n', stack);
        return throwError(err);
      })
    );
  }
}

Check if a string is a valid date using DateTime.TryParse

So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.

string dateString = "198101";

if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
     //do stuff
}

The output is stored in Temp and not needed afterwards, datestring is the input string to be tested.

Express: How to pass app-instance to routes from a different file?

For database separate out Data Access Service that will do all DB work with simple API and avoid shared state.

Separating routes.setup looks like overhead. I would prefer to place a configuration based routing instead. And configure routes in .json or with annotations.

Passing additional variables from command line to make

The simplest way is:

make foo=bar target

Then in your makefile you can refer to $(foo). Note that this won't propagate to sub-makes automatically.

If you are using sub-makes, see this article: Communicating Variables to a Sub-make

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

Plotting categorical data with pandas and matplotlib

To plot multiple categorical features as bar charts on the same plot, I would suggest:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    {
        "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
        "direction": ["up", "up", "down", "left", "right", "down", "down"],
    }
)

categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
    df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()

enter image description here

Query to check index on a table

Most modern RDBMSs support the INFORMATION_SCHEMA schema. If yours supports that, then you want either INFORMATION_SCHEMA.TABLE_CONSTRAINTS or INFORMATION_SCHEMA.KEY_COLUMN_USAGE, or maybe both.

To see if yours supports it is as simple as running

select count(*) from INFORMATION_SCHEMA.TABLE_CONSTRAINTS

EDIT: SQL Server does have INFORMATION_SCHEMA, and it's easier to use than their vendor-specific tables, so just go with it.

How do I launch a Git Bash window with particular working directory using a script?

Try the --cd= option. Assuming your GIT Bash resides in C:\Program Files\Git it would be:

"C:\Program Files\Git\git-bash.exe" --cd="e:\SomeFolder"

If used inside registry key, folder parameter can be provided with %1:

"C:\Program Files\Git\git-bash.exe" --cd="%1"

How do I call paint event?

Call control.invalidate and the paint event will be raised.

How do I read a date in Excel format in Python?

xlrd.xldate_as_tuple is nice, but there's xlrd.xldate.xldate_as_datetime that converts to datetime as well.

import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

How to create a inner border for a box in html?

IE doesn't support outline-offset so another solution would be to create 2 div tags, one nested into the other one. The inner one would have a border and be slightly smaller than the container.

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 400px;_x000D_
  height: 100px;_x000D_
  background: #000000;_x000D_
  padding: 10px;_x000D_
}_x000D_
.inner {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: #000000;_x000D_
  border: 1px dashed #ffffff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="inner"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

resize2fs: Bad magic number in super-block while trying to open

In Centos 7 default filesystem is xfs.

xfs file system support only extend not reduce. So if you want to resize the filesystem use xfs_growfs rather than resize2fs.

xfs_growfs /dev/root_vg/root 

Note: For ext4 filesystem use

resize2fs /dev/root_vg/root

Java: String - add character n-times

Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).

Something like:

StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
    b.append("other_string");
}
return b.toString();

Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.

How do I make a transparent border with CSS?

hey this is the best solution I ever experienced.. this is CSS3

use following property to your div or anywhere you wanna put border trasparent

e.g.

div_class { 
 border: 10px solid #999;
 background-clip: padding-box; /* Firefox 4+, Opera, for IE9+, Chrome */
}

this will work..

builder for HashMap

Here's one I wrote

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class MapBuilder<K, V> {

    private final Map<K, V> map;

    /**
     * Create a HashMap builder
     */
    public MapBuilder() {
        map = new HashMap<>();
    }

    /**
     * Create a HashMap builder
     * @param initialCapacity
     */
    public MapBuilder(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

    /**
     * Create a Map builder
     * @param mapFactory
     */
    public MapBuilder(Supplier<Map<K, V>> mapFactory) {
        map = mapFactory.get();
    }

    public MapBuilder<K, V> put(K key, V value) {
        map.put(key, value);
        return this;
    }

    public Map<K, V> build() {
        return map;
    }

    /**
     * Returns an unmodifiable Map. Strictly speaking, the Map is not immutable because any code with a reference to
     * the builder could mutate it.
     *
     * @return
     */
    public Map<K, V> buildUnmodifiable() {
        return Collections.unmodifiableMap(map);
    }
}

You use it like this:

Map<String, Object> map = new MapBuilder<String, Object>(LinkedHashMap::new)
    .put("event_type", newEvent.getType())
    .put("app_package_name", newEvent.getPackageName())
    .put("activity", newEvent.getActivity())
    .build();

What are ABAP and SAP?

  • SAP SE is a German multinational that makes enterprise software. It is best known for SAP ERP and its predecessors (SAP R/2 & SAP R/3). As the name suggests, SAP ERP is an ERP system, which basically means that it supports a wide range of business processes from warehouse management and sales to HR, business intelligence, etc.

    Although SAP ERP isn't the only software sold by SAP, people are typically refering to SAP ERP when they say "they're using SAP at work". It's important to note, though, that SAP is the name of the company and no software is sold or licensed as just "SAP".

  • ABAP is a 4GL programming language created by SAP, and commonly compared with OpenEdge ABL or COBOL. Much of SAP's software is written in ABAP. SAP provides an ABAP Workbench, which is a collection of tools that allows third party developers to develop, test and run custom ABAP programs within the SAP ERP system. The ABAP Workbench is typically used only when business logic cannot be implemented in SAP ERP by means of mere configuration.

Converting strings to floats in a DataFrame

In a newer version of pandas (0.17 and up), you can use to_numeric function. It allows you to convert the whole dataframe or just individual columns. It also gives you an ability to select how to treat stuff that can't be converted to numeric values:

import pandas as pd
s = pd.Series(['1.0', '2', -3])
pd.to_numeric(s)
s = pd.Series(['apple', '1.0', '2', -3])
pd.to_numeric(s, errors='ignore')
pd.to_numeric(s, errors='coerce')

Oracle - Insert New Row with Auto Incremental ID

There is no built-in auto_increment in Oracle.

You need to use sequences and triggers.

Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")

SELECT with a Replace()

SELECT *
FROM Contacts
WHERE ContactId IN
    (SELECT a.ContactID
    FROM
        (SELECT ContactId, Replace(Postcode, ' ', '') AS P
        FROM Contacts
        WHERE Postcode LIKE '%N%W%1%0%1%') a
    WHERE a.P LIKE 'NW101%')

Sort a List of objects by multiple fields

You have to write your own compareTo() method that has the Java code needed to perform the comparison.

If we wanted for example to compare two public fields, campus, then faculty, we might do something like:

int compareTo(GraduationCeremony gc)
{
    int c = this.campus.compareTo(gc.campus);

    if( c != 0 )
    {
        //sort by campus if we can
        return c;
    }
    else
    {
        //campus equal, so sort by faculty
        return this.faculty.compareTo(gc.faculty);
    }
}

This is simplified but hopefully gives you an idea. Consult the Comparable and Comparator docs for more info.

PHP Checking if the current date is before or after a set date

if(strtotime($db_date) > time()) {
  echo $db_date;
} else {
  echo 'go ahead';
}

How to convert String object to Boolean Object?

Visit http://msdn.microsoft.com/en-us/library/system.boolean.parse.aspx

This will give you an idea of what to do.

This is what I get from the Java documentation:

Method Detail

parseBoolean

public static boolean parseBoolean(String s)

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Parameters:

s - the String containing the boolean representation to be parsed

Returns: the boolean represented by the string argument

Since: 1.5

How do I remove javascript validation from my eclipse project?

Window -> Preferences -> JavaScript -> Validator (also per project settings possible)

or

Window -> Preferences -> Validation (disable validations and configure their settings)

Creating multiple log files of different content with log4j

This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...


# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...

log4j.logger.com.yourpackage.yourclazz=TRACE

How do I check if a column is empty or null in MySQL?

You can test whether a column is null or is not null using WHERE col IS NULL or WHERE col IS NOT NULL e.g.

SELECT myCol 
FROM MyTable 
WHERE MyCol IS NULL 

In your example you have various permutations of white space. You can strip white space using TRIM and you can use COALESCE to default a NULL value (COALESCE will return the first non-null value from the values you suppy.

e.g.

SELECT myCol
FROM MyTable
WHERE TRIM(COALESCE(MyCol, '')) = '' 

This final query will return rows where MyCol is null or is any length of whitespace.

If you can avoid it, it's better not to have a function on a column in the WHERE clause as it makes it difficult to use an index. If you simply want to check if a column is null or empty, you may be better off doing this:

SELECT myCol
FROM MyTable
WHERE MyCol IS NULL OR MyCol =  '' 

See TRIM COALESCE and IS NULL for more info.

Also Working with null values from the MySQL docs

Evenly distributing n points on a sphere

@robert king It's a really nice solution but has some sloppy bugs in it. I know it helped me a lot though, so never mind the sloppiness. :) Here is a cleaned up version....

from math import pi, asin, sin, degrees
halfpi, twopi = .5 * pi, 2 * pi
sphere_area = lambda R=1.0: 4 * pi * R ** 2

lat_dist = lambda lat, R=1.0: R*(1-sin(lat))

#A = 2*pi*R^2(1-sin(lat))
def sphere_latarea(lat, R=1.0):
    if -halfpi > lat or lat > halfpi:
        raise ValueError("lat must be between -halfpi and halfpi")
    return 2 * pi * R ** 2 * (1-sin(lat))

sphere_lonarea = lambda lon, R=1.0: \
        4 * pi * R ** 2 * lon / twopi

#A = 2*pi*R^2 |sin(lat1)-sin(lat2)| |lon1-lon2|/360
#    = (pi/180)R^2 |sin(lat1)-sin(lat2)| |lon1-lon2|
sphere_rectarea = lambda lat0, lat1, lon0, lon1, R=1.0: \
        (sphere_latarea(lat0, R)-sphere_latarea(lat1, R)) * (lon1-lon0) / twopi


def test_sphere(n_lats=10, n_lons=19, radius=540.0):
    total_area = 0.0
    for i_lons in range(n_lons):
        lon0 = twopi * float(i_lons) / n_lons
        lon1 = twopi * float(i_lons+1) / n_lons
        for i_lats in range(n_lats):
            lat0 = asin(2 * float(i_lats) / n_lats - 1)
            lat1 = asin(2 * float(i_lats+1)/n_lats - 1)
            area = sphere_rectarea(lat0, lat1, lon0, lon1, radius)
            print("{:} {:}: {:9.4f} to  {:9.4f}, {:9.4f} to  {:9.4f} => area {:10.4f}"
                    .format(i_lats, i_lons
                    , degrees(lat0), degrees(lat1)
                    , degrees(lon0), degrees(lon1)
                    , area))
            total_area += area
    print("total_area = {:10.4f} (difference of {:10.4f})"
            .format(total_area, abs(total_area) - sphere_area(radius)))

test_sphere()

What is __pycache__?

A __pycache__ folder is created when you use the line:

import file_name

or try to get information from another file you have created. This makes it a little faster when running your program the second time to open the other file.

post checkbox value

There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Single check box

HTML code:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

PHP Code:

<?php

if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    

?>

Check box group

<form action="checkbox-form.php" method="post">
    Which buildings do you want access to?<br />
    <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
    <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
    <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
    <input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
    <input type="checkbox" name="formDoor[]" value="E" />Elliot House

    <input type="submit" name="formSubmit" value="Submit" />
 /form>

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);

    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

C#: easiest way to populate a ListBox from a List

Try :

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

listBox1.DataSource = MyList;

Have a look at ListControl.DataSource Property

How do I use LINQ Contains(string[]) instead of Contains(string)

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

namespace StringExtensionMethods
{
    public static class StringExtension
    {
        public static bool Contains(this string[] stringarray, string pat)
        {
            bool result = false;

            foreach (string s in stringarray)
            {
                if (s == pat)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}

mysqldump with create database line

Here is how to do dump the database (with just the schema):

mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql

If you also want the data, remove the --no-data option.

Java collections convert a string to a list of characters

The most straightforward way is to use a for loop to add elements to a new List:

String abc = "abc";
List<Character> charList = new ArrayList<Character>();

for (char c : abc.toCharArray()) {
  charList.add(c);
}

Similarly, for a Set:

String abc = "abc";
Set<Character> charSet = new HashSet<Character>();

for (char c : abc.toCharArray()) {
  charSet.add(c);
}

Google Maps V3 marker with label

If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..

<script type="text/javascript">
    var point = { lat: 22.5667, lng: 88.3667 };
    var markerSize = { x: 22, y: 40 };


    google.maps.Marker.prototype.setLabel = function(label){
        this.label = new MarkerLabel({
          map: this.map,
          marker: this,
          text: label
        });
        this.label.bindTo('position', this, 'position');
    };

    var MarkerLabel = function(options) {
        this.setValues(options);
        this.span = document.createElement('span');
        this.span.className = 'map-marker-label';
    };

    MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
        onAdd: function() {
            this.getPanes().overlayImage.appendChild(this.span);
            var self = this;
            this.listeners = [
            google.maps.event.addListener(this, 'position_changed', function() { self.draw();    })];
        },
        draw: function() {
            var text = String(this.get('text'));
            var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
            this.span.innerHTML = text;
            this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
            this.span.style.top = (position.y - markerSize.y + 40) + 'px';
        }
    });
    function initialize(){
        var myLatLng = new google.maps.LatLng(point.lat, point.lng);
        var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
            zoom: 5,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var myMarker = new google.maps.Marker({
            map: gmap,
            position: myLatLng,
            label: 'Hello World!',
            draggable: true
        });
    }
</script>
<style>
    .map-marker-label{
        position: absolute;
    color: blue;
    font-size: 16px;
    font-weight: bold;
    }
</style>

This will work.

Adding blank spaces to layout

Agree with all the answers......also,

    <TextView android:text=""
              android:layout_width="match_parent"
              android:layout_height="30dp"
              android:layout_weight="2" />

should work :) I am just messing with others as TextView is my favourite (waste of memory though!)

The Role Manager feature has not been enabled

I found 2 suggestions elsewhere via Google that suggested a) making sure your db connectionstring (the one that Roles is using) is correct and that the key to it is spelled correctly, and b) that the Enabled flag on RoleManager is set to true. Hope one of those helps. It did for me.

Did you try checking Roles.Enabled? Also, you can check Roles.Providers to see how many providers are available and you can check the Roles.Provider for the default provider. If it is null then there isn't one.

Set focus to field in dynamically loaded DIV

$(function (){
    $('body').on('keypress','.sobitie_snses input',function(e){
        if(e.keyCode==13){
            $(this).blur();
            var new_fild =  $(this).clone().val('');
            $(this).parent().append(new_fild);
            $(new_fild).focus();
        }
    });
});

most of error are because U use wrong object to set the prorepty or function. Use console.log(new_fild); to see to what object U try to set the prorepty or function.

Is there a Subversion command to reset the working copy?

svn revert . -R

to reset everything.

svn revert path/to/file

for a single file

Is there an alternative sleep function in C to milliseconds?

Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

How to Right-align flex item?

Add the following CSS class to your stylesheet:

.my-spacer {
    flex: 1 1 auto;
}

Place an empty element between the element on the left and the element you wish to right-align:

<span class="my-spacer"></span>

Select SQL results grouped by weeks

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

Create a simple 10 second countdown

This does it in text.

_x000D_
_x000D_
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
    var timeleft = 10;_x000D_
    var downloadTimer = setInterval(function(){_x000D_
    timeleft--;_x000D_
    document.getElementById("countdowntimer").textContent = timeleft;_x000D_
    if(timeleft <= 0)_x000D_
        clearInterval(downloadTimer);_x000D_
    },1000);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

bash string equality

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

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

"Input string was not in a correct format."

it was my problem too .. in my case i changed the PERSIAN number to LATIN number and it worked. AND also trime your string before converting.

PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

I like to make use of the css :before and a data-* attribute for the list

HTML:

<ul data-header="heading"> 
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>

CSS:

ul:before{
    content:attr(data-header);
    font-size:120%;
    font-weight:bold;
    margin-left:-15px;
}

This will make a list with the header on it that is whatever text is specified as the list's data-header attribute. You can then easily style it to your needs.

Docker error: invalid reference format: repository name must be lowercase

In my case DockerFile contained the image name in mixed case instead of lower case.

Earlier line in my DockerFile

FROM CentOs

and when I changed above to FROM centos, it worked smoothly.

Best way to format multiple 'or' conditions in an if statement (Java)

No you cannot do that in Java. you can however write a method as follows:

boolean isContains(int i, int ... numbers) {
    // code to check if i is one of the numbers
    for (int n : numbers) {
        if (i == n) return true;
    }
    return false;
}

Parse date without timezone javascript

simple solution

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

What is the difference between a token and a lexeme?

Let's see the working of a lexical analyser ( also called Scanner )

Let's take an example expression :

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

not the actual output though .

SCANNER SIMPLY LOOKS REPEATEDLY FOR A LEXEME IN SOURCE-PROGRAM TEXT UNTIL INPUT IS EXHAUSTED

Lexeme is a substring of input that forms a valid string-of-terminals present in grammar . Every lexeme follows a pattern which is explained at the end ( the part that reader may skip at last )

( Important rule is to look for the longest possible prefix forming a valid string-of-terminals until next whitespace is encountered ... explained below )

LEXEMES :

  1. cout
  2. <<

( although "<" is also valid terminal-string but above mentioned rule shall select the pattern for lexeme "<<" in order to generate token returned by scanner )

  1. 3
  2. +
  3. 2
  4. ;

TOKENS : Tokens are returned one at a time ( by Scanner when requested by Parser ) each time Scanner finds a (valid) lexeme. Scanner creates ,if not already present, a symbol-table entry ( having attributes : mainly token-category and few others ) , when it finds a lexeme, in order to generate it's token

'#' denotes a symbol table entry . I have pointed to lexeme number in above list for ease of understanding but it technically should be actual index of record in symbol table.

The following tokens are returned by scanner to parser in specified order for above example.

  1. < identifier , #1 >

  2. < Operator , #2 >

  3. < Literal , #3 >

  4. < Operator , #4 >

  5. < Literal , #5 >

  6. < Operator , #4 >

  7. < Literal , #3 >

  8. < Punctuator , #6 >

As you can see the difference , a token is a pair unlike lexeme which is a substring of input.

And first element of the pair is the token-class/category

Token Classes are listed below:

  • KEYWORDS
  • IDENTIFIERS
  • LITERALS
  • PUNCTUATORS
  • OPERATORS
  • And one more thing , Scanner detects whitespaces , ignores them and does not form any token for a whitespace at all. Not all delimiters are whitespaces, a whitespace is one form of delimiter used by scanners for it's purpose . Tabs , Newlines , Spaces , Escaped Characters in input all are collectively called Whitespace delimiters. Few other delimiters are ';' ',' ':' etc, which are widely recognised as lexemes that form token.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`
    

    How to make a GridLayout fit screen size

    Starting in API 21 the notion of weight was added to GridLayout.

    To support older android devices, you can use the GridLayout from the v7 support library.

    compile 'com.android.support:gridlayout-v7:22.2.1'
    

    The following XML gives an example of how you can use weights to fill the screen width.

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.GridLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:grid="http://schemas.android.com/apk/res-auto"
    
        android:id="@+id/choice_grid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:padding="4dp"
    
        grid:alignmentMode="alignBounds"
        grid:columnCount="2"
        grid:rowOrderPreserved="false"
        grid:useDefaultMargins="true">
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            grid:layout_columnWeight="1"
            grid:layout_gravity="fill_horizontal"
            android:gravity="center"
            android:background="#FF33B5E5"
            android:text="Tile1" />
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            grid:layout_columnWeight="1"
            grid:layout_gravity="fill_horizontal"
            android:gravity="center"
            android:background="#FF33B5E5"
            android:text="Tile2" />
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            grid:layout_columnWeight="1"
            grid:layout_gravity="fill_horizontal"
            android:gravity="center"
            android:background="#FF33B5E5"
            android:text="Tile3" />
    
        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            grid:layout_columnWeight="1"
            grid:layout_gravity="fill_horizontal"
            android:gravity="center"
            android:background="#FF33B5E5"
            android:text="Tile4" />
    
    </android.support.v7.widget.GridLayout>
    

    Filter df when values matches part of a string in pyspark

    Spark 2.2 onwards

    df.filter(df.location.contains('google.com'))
    

    Spark 2.2 documentation link


    Spark 2.1 and before

    You can use plain SQL in filter

    df.filter("location like '%google.com%'")
    

    or with DataFrame column methods

    df.filter(df.location.like('%google.com%'))
    

    Spark 2.1 documentation link

    curl POST format for CURLOPT_POSTFIELDS

    EDIT: From php5 upwards, usage of http_build_query is recommended:

    string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                              string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
    

    Simple example from the manual:

    <?php
    $data = array('foo'=>'bar',
                  'baz'=>'boom',
                  'cow'=>'milk',
                  'php'=>'hypertext processor');
    
    echo http_build_query($data) . "\n";
    
    /* output:
    foo=bar&baz=boom&cow=milk&php=hypertext+processor
    */
    
    ?>
    

    before php5:

    From the manual:

    CURLOPT_POSTFIELDS

    The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

    So something like this should work perfectly (with parameters passed in a associative array):

    function preparePostFields($array) {
      $params = array();
    
      foreach ($array as $key => $value) {
        $params[] = $key . '=' . urlencode($value);
      }
    
      return implode('&', $params);
    }
    

    Formatting a number with leading zeros in PHP

    echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
    

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

    ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
    ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
        ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;
    

    Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

    HTML5 Email Validation

    I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

    Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

    var validations ={
        email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
    };
    $(document).ready(function(){
        // Check all the input fields of type email. This function will handle all the email addresses validations
        $("input[type=email]").change( function(){
            // Set the regular expression to validate the email 
            validation = new RegExp(validations['email'][0]);
            // validate the email value against the regular expression
            if (!validation.test(this.value)){
                // If the validation fails then we show the custom error message
                this.setCustomValidity(validations['email'][1]);
                return false;
            } else {
                // This is really important. If the validation is successful you need to reset the custom error message
                this.setCustomValidity('');
            }
        });
    })
    

    ImportError: No module named requests

    I have installed python2.7 and python3.6

    Open Command Line to ~/.bash_profile I find that #Setting PATH for Python 3.6 , So I change the path to PATH="/usr/local/Cellar/python/2.7.13/bin:${PATH}" , (please make sure your python2.7's path) ,then save. It works for me.

    Understanding repr( ) function in Python

    >>> x = 'foo'
    >>> x
    'foo'
    

    So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

    >>> repr(x)
    "'foo'"
    >>> x.__repr__()
    "'foo'"
    

    repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

    >>> eval("'foo'")
    'foo'
    

    When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

    >>> eval('foo')
    
    Traceback (most recent call last):
      File "<pyshell#5>", line 1, in <module>
        eval('foo')
      File "<string>", line 1, in <module>
    NameError: name 'foo' is not defined
    

    If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

    >>> str(x)
    'foo'
    >>> x.__str__()
    'foo'
    >>> 
    

    str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

    >>> str(5)
    '5'
    

    String representation of integer 5 is '5'.

    >>> str('foo')
    'foo'
    

    And string representation of string 'foo' is the same string 'foo'.