Programs & Examples On #Shred

Shredding refers to the decomposition of XML data structures into the columns of a relational database. It can also refer to overwriting the contents of a file in an attempt to prevent recovery of deleted data.

How to start nginx via different port(other than 80)

You will need to change the configure port of either Apache or Nginx. After you do this you will need to restart the reconfigured servers, using the 'service' command you used.


Apache

Edit

sudo subl /etc/apache2/ports.conf 

and change the 80 on the following line to something different :

Listen 80

If you just change the port or add more ports here, you will likely also have to change the VirtualHost statement in

sudo subl /etc/apache2/sites-enabled/000-default.conf

and change the 80 on the following line to something different :

<VirtualHost *:80>

then restart by :

sudo service apache2 restart

Nginx

Edit

/etc/nginx/sites-enabled/default

and change the 80 on the following line :

listen 80;

then restart by :

sudo service nginx restart

How can I make my website's background transparent without making the content (images & text) transparent too?

Make the background image transparent/semi-transparent. If it's a solid coloured background just create a 1px by 1px image in fireworks or whatever and adjust its opacity...

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

CMake unable to determine linker language with C++

Confusing as it might be, the error also happens when a cpp file included in the project does not exist.

If you list your source files in CMakeLists.txt and mistakenly type a file name then you get this error.

How to print from Flask @app.route to python console

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

How to match "any character" in regular expression?

Specific Solution to the example problem:-

Try [A-Z]*123$ will match 123, AAA123, ASDFRRF123. In case you need at least a character before 123 use [A-Z]+123$.

General Solution to the question (How to match "any character" in the regular expression):

  1. If you are looking for anything including whitespace you can try [\w|\W]{min_char_to_match,}.
  2. If you are trying to match anything except whitespace you can try [\S]{min_char_to_match,}.

Get checkbox values using checkbox name using jquery

$('[name="CheckboxName"]:checked').each(function () {
    // do stuff
});

How can I initialize base class member variables in derived class constructor?

If you don't specify visibility for a class member, it defaults to "private". You should make your members private or protected if you want to access them in a subclass.

python list by value not by reference

If you want to copy a one-dimensional list, use

b = a[:]

However, if a is a 2-dimensional list, this is not going to work for you. That is, any changes in a will also be reflected in b. In that case, use

b = [[a[x][y] for y in range(len(a[0]))] for x in range(len(a))]

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

How to call a REST web service API from JavaScript?

Your Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

Your Button action::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)

splitting a string into an array in C++ without using vector

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    string line = "test one two three.";
    string arr[4];
    int i = 0;
    stringstream ssin(line);
    while (ssin.good() && i < 4){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < 4; i++){
        cout << arr[i] << endl;
    }
}

Why can't a text column have a default value in MySQL?

As the main question:

Anybody know why this is not allowed?

is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:

[17 Mar 2017 15:11] Ståle Deraas

Posted by developer:

This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.

This is no definite answer, but at least a starting point for the why question.

In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default '') value for each insert from the application code...

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Base64 encoding and decoding in client-side Javascript

The php.js project has JavaScript implementations of many of PHP's functions. base64_encode and base64_decode are included.

Node.js fs.readdir recursive directory search

Using async/await, this should work:

const FS = require('fs');
const readDir = promisify(FS.readdir);
const fileStat = promisify(FS.stat);

async function getFiles(dir) {
    let files = await readDir(dir);

    let result = files.map(file => {
        let path = Path.join(dir,file);
        return fileStat(path).then(stat => stat.isDirectory() ? getFiles(path) : path);
    });

    return flatten(await Promise.all(result));
}

function flatten(arr) {
    return Array.prototype.concat(...arr);
}

You can use bluebird.Promisify or this:

/**
 * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
 *
 * @param {Function} nodeFunction
 * @returns {Function}
 */
module.exports = function promisify(nodeFunction) {
    return function(...args) {
        return new Promise((resolve, reject) => {
            nodeFunction.call(this, ...args, (err, data) => {
                if(err) {
                    reject(err);
                } else {
                    resolve(data);
                }
            })
        });
    };
};

Node 8+ has Promisify built-in

See my other answer for a generator approach that can give results even faster.

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

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

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

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

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

Creating a chart in Excel that ignores #N/A or blank cells

One solution is that the chart/graph doesn't show the hidden rows.

You can test this features doing: 1)right click on row number 2)click on hide.

For doing it automatically, this is the simple code:

For Each r In worksheet.Range("A1:A200")
   If r.Value = "" Then 
      r.EntireRow.Hidden = True 
   Else: 
      r.EntireRow.Hidden = False
Next

Checking if a variable is an integer

You can use the is_a? method

>> 1.is_a? Integer
=> true
>> "[email protected]".is_a? Integer
=> false
>> nil.is_a? Integer
=> false

Install numpy on python3.3 - Install pip for python3

On fedora/rhel/centos you need to

sudo yum install -y python3-devel

before

mkvirtualenv -p /usr/bin/python3.3 test-3.3
pip install numpy

otherwise you'll get

SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Python: finding an element in a list

The best way is probably to use the list method .index.

For the objects in the list, you can do something like:

def __eq__(self, other):
    return self.Value == other.Value

with any special processing you need.

You can also use a for/in statement with enumerate(arr)

Example of finding the index of an item that has value > 100.

for index, item in enumerate(arr):
    if item > 100:
        return index, item

Source

How do you get the index of the current iteration of a foreach loop?

Why foreach ?!

The simplest way is using for instead of foreach if you are using List:

for (int i = 0 ; i < myList.Count ; i++)
{
    // Do something...
}

Or if you want use foreach:

foreach (string m in myList)
{
     // Do something...
}

You can use this to know the index of each loop:

myList.indexOf(m)

Sorting an array of objects by property values

A simple code :

_x000D_
_x000D_
    var homes = [_x000D_
        {_x000D_
            "h_id": "3",_x000D_
            "city": "Dallas",_x000D_
            "state": "TX",_x000D_
            "zip": "75201",_x000D_
            "price": "162500"_x000D_
        }, {_x000D_
            "h_id": "4",_x000D_
            "city": "Bevery Hills",_x000D_
            "state": "CA",_x000D_
            "zip": "90210",_x000D_
            "price": "319250"_x000D_
        }, {_x000D_
            "h_id": "5",_x000D_
            "city": "New York",_x000D_
            "state": "NY",_x000D_
            "zip": "00010",_x000D_
            "price": "962500"_x000D_
        }_x000D_
    ];_x000D_
_x000D_
    let sortByPrice = homes.sort(function (a, b) _x000D_
    {_x000D_
      return parseFloat(b.price) - parseFloat(a.price);_x000D_
    });_x000D_
_x000D_
    for (var i=0; i<sortByPrice.length; i++)_x000D_
    {_x000D_
      document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' '_x000D_
       +sortByPrice[i].state+' '_x000D_
       +sortByPrice[i].zip+' '+sortByPrice[i].price);_x000D_
      document.write("<br>");_x000D_
    }
_x000D_
_x000D_
_x000D_

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

How to iterate (keys, values) in JavaScript?

WELCOME TO 2020 *Drools in ES6*

Theres some pretty old answers in here - take advantage of destructuring. In my opinion this is without a doubt the nicest (very readable) way to iterate an object.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

Object.entries(myObject).forEach(([k,v]) => {
    console.log("The key: ",k)
    console.log("The value: ",v)
})
_x000D_
_x000D_
_x000D_

Edit:

As mentioned by Lazerbeak, map allows you to cycle an object and use the key and value to make an array.

_x000D_
_x000D_
const myObject = {
    nick: 'cage',
    phil: 'murray',
};

const myArray = Object.entries(myObject).map(([k, v]) => {
    return `The key '${k}' has a value of '${v}'`;
});

console.log(myArray);
_x000D_
_x000D_
_x000D_

Android textview outline text

Here is the simplest way I could find by extending TextView

public class CustomTextView extends androidx.appcompat.widget.AppCompatTextView {

float mStroke;

public CustomTextView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs,
            R.styleable.CustomTextView);
    mStroke=a.getFloat(R.styleable.CustomTextView_stroke,1.0f);
    a.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    TextPaint paint = this.getPaint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(mStroke);
    
    super.onDraw(canvas);
}
}

then you only need to add the following to the attrs.xml file

<declare-styleable name="CustomTextView">
    <attr name="stroke" format="float"/>
</declare-styleable>

and now you will be able to set the stroke widht by app:stroke while retaining all other desirable properties of TextView. my solution only draws the stroke w/o a fill. this makes it a bit simpler than the others. bellow a screencapture with the result while setting a custom font to my customtextview.

enter image description here

Java Read Large Text File With 70million line of text

1) I am sure there is no difference speedwise, both use FileInputStream internally and buffering

2) You can take measurements and see for yourself

3) Though there's no performance benefits I like the 1.7 approach

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
    for (String line = null; (line = br.readLine()) != null;) {
        //
    }
}

4) Scanner based version

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    }

5) This may be faster than the rest

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
    ByteBuffer bb = ByteBuffer.allocateDirect(1000);
    for(;;) {
        StringBuilder line = new StringBuilder();
        int n = ch.read(bb);
        // add chars to line
        // ...
    }
}

it requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying

6) Parallel processing would definitely increase speed. Make a big byte buffer, run several tasks that read bytes from file into that buffer in parallel, when ready find first end of line, make a String, find next...

Angular routerLink does not navigate to the corresponding component

I'm aware this question is fairly old by now, and you've most likely fixed it by now, but I'd like to post here as reference for anyone that finds this post while troubleshooting this issue is that this sort of thing won't work if your Anchor tags are in the Index.html. It needs to be in one of the components

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

How do I list all cron jobs for all users?

Since it is a matter of looping through a file (/etc/passwd) and performing an action, I am missing the proper approach on How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

while IFS=":" read -r user _
do
   echo "crontab for user ${user}:"
   crontab -u "$user" -l
done < /etc/passwd

This reads /etc/passwd line by line using : as field delimiter. By saying read -r user _, we make $user hold the first field and _ the rest (it is just a junk variable to ignore fields).

This way, we can then call crontab -u using the variable $user, which we quote for safety (what if it contains spaces? It is unlikely in such file, but you can never know).

How to read multiple text files into a single RDD?

In PySpark, I have found an additional useful way to parse files. Perhaps there is an equivalent in Scala, but I am not comfortable enough coming up with a working translation. It is, in effect, a textFile call with the addition of labels (in the below example the key = filename, value = 1 line from file).

"Labeled" textFile

input:

import glob
from pyspark import SparkContext
SparkContext.stop(sc)
sc = SparkContext("local","example") # if running locally
sqlContext = SQLContext(sc)

for filename in glob.glob(Data_File + "/*"):
    Spark_Full += sc.textFile(filename).keyBy(lambda x: filename)

output: array with each entry containing a tuple using filename-as-key and with value = each line of file. (Technically, using this method you can also use a different key besides the actual filepath name- perhaps a hashing representation to save on memory). ie.

[('/home/folder_with_text_files/file1.txt', 'file1_contents_line1'),
 ('/home/folder_with_text_files/file1.txt', 'file1_contents_line2'),
 ('/home/folder_with_text_files/file1.txt', 'file1_contents_line3'),
 ('/home/folder_with_text_files/file2.txt', 'file2_contents_line1'),
  ...]

You can also recombine either as a list of lines:

Spark_Full.groupByKey().map(lambda x: (x[0], list(x[1]))).collect()

[('/home/folder_with_text_files/file1.txt', ['file1_contents_line1', 'file1_contents_line2','file1_contents_line3']),
 ('/home/folder_with_text_files/file2.txt', ['file2_contents_line1'])]

Or recombine entire files back to single strings (in this example the result is the same as what you get from wholeTextFiles, but with the string "file:" stripped from the filepathing.):

Spark_Full.groupByKey().map(lambda x: (x[0], ' '.join(list(x[1])))).collect()

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

If you have a wamp setup that won't send emails, there is only a couple of things to do. 1. find out what the smtp server name is for your isp. The gmail thing is most likely unnecessary complication 2. create a phpsetup.php file in your 'www' folder and edit like this:

<?php
   phpinfo();
?>

this will give you a handle on what wamp is using. 3. search for the php.ini file. there may be serveral. The one you want is the one that effects the output of the file above. 4. find the smtp address in the most likely php.ini. 5. Type in your browser localhost/phpsetup.php and scroll down to smtp setting. it should say 'localhost' 6. edit the php.ini file smtp setting to the name of your ISPs smtp server. check if it changes for you phpsetup.php. if it works your done, if not you are working the wrong file.

this issue should be on the Wordpress site but they are way too up-them-selves or trying to get clients.;)

$location / switching between html5 and hashbang mode / link rewriting

I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).

URL for accessing my app:

http://myapp.com/amazing_url?token=super_token

Then when the user loads the page:

http://myapp.com/amazing_url?token=super_token#/amazing_url

Then when the user navigates:

http://myapp.com/amazing_url?token=super_token#/another_url

With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.

So don't enable the HTML5 mode and then add this controller:

.config ($stateProvider)->
    $stateProvider.state('home-loading', {
         url: '/',
         controller: 'homeController'
    })
.controller 'homeController', ($state, $location)->
    if window.location.pathname != '/'
        $location.url(window.location.pathname+window.location.search).replace()
    else
        $state.go('home', {}, { location: 'replace' })

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

Command-line tool for finding out who is locking a file

enter image description here

Computer Management->Shared Folders->Open Files

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

How to print to console in pytest?

According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

Does calling clone() on an array also clone its contents?

If I invoke clone() method on array of Objects of type A, how will it clone its elements?

The elements of the array will not be cloned.

Will the copy be referencing to the same objects?

Yes.

Or will it call (element of type A).clone() for each of them?

No, it will not call clone() on any of the elements.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1 and 10 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).

Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
 @echo off
 CLS
 ECHO.
 ECHO =============================
 ECHO Running Admin shell
 ECHO =============================

:init
 setlocal DisableDelayedExpansion
 set cmdInvoke=1
 set winSysFolder=System32
 set "batchPath=%~0"
 for %%k in (%0) do set batchName=%%~nk
 set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
 setlocal EnableDelayedExpansion

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
  if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
  ECHO.
  ECHO **************************************
  ECHO Invoking UAC for Privilege Escalation
  ECHO **************************************

  ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
  ECHO args = "ELEV " >> "%vbsGetPrivileges%"
  ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
  ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
  ECHO Next >> "%vbsGetPrivileges%"

  if '%cmdInvoke%'=='1' goto InvokeCmd 

  ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
  goto ExecElevation

:InvokeCmd
  ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
  ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"

:ExecElevation
 "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
 exit /B

:gotPrivileges
 setlocal & cd /d %~dp0
 if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

 ::::::::::::::::::::::::::::
 ::START
 ::::::::::::::::::::::::::::
 REM Run shell as admin (example) - put here code as you like
 ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
 cmd /k

The script takes advantage of the fact that NET FILE requires administrator privilege and returns errorlevel 1 if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.

I have tested it with Windows 7, 8, 8.1, 10 and with Windows XP - it works fine for all. The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.


If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. &
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be on the same line. It is displayed here in multiple lines for better readability!


On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!. It doesn't contain any double quotes, so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)

checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Update:

  • To avoid having to register the .vbs extension in Windows 10, I have replaced the line
    "%temp%\OEgetPrivileges.vbs"
    by
    "%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
    in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.

  • Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.

  • According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter

  • Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.

  • Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)

  • In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
    set cmdInvoke=0
    set winSysFolder=System32
    Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
    Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).

  • To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".

  • If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).

Useful links:

Specify an SSH key for git push for a given domain

You might need to remove (or comment out) default Host configuration .ssh/config

Create an Oracle function that returns a table

  CREATE OR REPLACE PACKAGE BODY TEST AS 

   FUNCTION GET_UPS(
   TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
   STARTING_DATE_IN DATE,
   ENDING_DATE_IN DATE
   )RETURN MEASURE_TABLE IS

    T MEASURE_TABLE;

 BEGIN

    **SELECT   MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
             PERIOD,VALUE )  BULK COLLECT  INTO    T
    FROM    ...**

  ;

   RETURN T;

   END GET_UPS;

END TEST;

How to replace part of string by position?

string myString = "ABCDEFGHIJ";
string modifiedString = new StringBuilder(myString){[3]='Z', [4]='X'}.ToString();

Let me explain my solution.
Given the problem statement of altering a string in its two specific position (“position 4 to position 5”) with two character ‘Z’ and ‘X’ and the ask is to use the position index to alter the string and not string Replace() method(may be because of the possibility of repetition of some characters in the actual string), I would prefer to use minimalist approach to achieve the goal over using Substring() and string Concat() or string Remove() and Insert() approach. Though all those solutions will serve the purpose in attaining the same goal, but it just depends on personal choice and philosophy of settling with minimalist approach.
Coming back to my solution mention above, if we take a closer look of string and StringBuilder, both of them internally treats a given string as an array of characters. If we look at the implementation of StringBuilder it maintains an internal variable something like “internal char[] m_ChunkChars;” to capture the given string. Now since this is an internal variable, we cannot directly access the same. For external world, to be able to access and alter that character array, StringBuilder exposes them through indexer property which looks something like below

    [IndexerName("Chars")]
    public char this[int index]
    {
      get
      {
        StringBuilder stringBuilder = this;
        do
        {
          // … some code
            return stringBuilder.m_ChunkChars[index1];
          // … some more code
        }
      }
      set
      {
        StringBuilder stringBuilder = this;
        do
        {
            //… some code
            stringBuilder.m_ChunkChars[index1] = value;
            return;
            // …. Some more code
        }
      }
    }

My solution mentioned above leverage this indexer capability to directly alter the internally maintained character array which IMO is efficient and minimalist.

BTW; we can rewrite the above solution more elaborately something like below

 string myString = "ABCDEFGHIJ";
 StringBuilder tempString = new StringBuilder(myString);
 tempString[3] = 'Z';
 tempString[4] = 'X';
 string modifiedString = tempString.ToString();

In this context also would like to mention that in case of string it also have indexer property as a means to expose its internal character array, but in this case it only has Getter property (and no Setter) as string is immutable in nature. And that is why we need to use StringBuilder to alter the character array.

[IndexerName("Chars")]
public extern char this[int index] { [SecuritySafeCritical, __DynamicallyInvokable, MethodImpl(MethodImplOptions.InternalCall)] get; }

And last but not the least this solution is only best fit for this specific problem where the ask is to replace only few characters with a known position index upfront. It may not be the best fit when the requirement is to alter a fairly lengthy string i.e. number of characters to alter are large in numbers.

Exit while loop by user hitting ENTER key

user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):    
   print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
   import sys        #import
   sys.exit(0)       #exit program 
'''
#(not user_input) checks if user has pressed enter key without entering  
# number.
#(int(user_input)<=0) checks if user has entered any number less than or 
#equal to zero.
'''

How do I get the YouTube video ID from a URL?

i wrote a function for that below:

function getYoutubeUrlId (url) {
    const urlObject = new URL(url);
    let urlOrigin = urlObject.origin;
    let urlPath = urlObject.pathname;

    if (urlOrigin.search('youtu.be') > -1) {
        return urlPath.substr(1);
    }

    if (urlPath.search('embed') > -1) {
        // Örnegin "/embed/wCCSEol8oSc" ise "wCCSEol8oSc" return eder.
        return urlPath.substr(7);
    }

   
    return urlObject.searchParams.get('v');
},

https://gist.github.com/semihkeskindev/8a4339c27203c5fabaf2824308c7868f

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

How to Get True Size of MySQL Database?

From S. Prakash, found at the MySQL forum:

SELECT table_schema "database name",
    sum( data_length + index_length ) / 1024 / 1024 "database size in MB",
    sum( data_free )/ 1024 / 1024 "free space in MB"
FROM information_schema.TABLES
GROUP BY table_schema; 

Or in a single line for easier copy-pasting:

SELECT table_schema "database name", sum( data_length + index_length ) / 1024 / 1024 "database size in MB", sum( data_free )/ 1024 / 1024 "free space in MB" FROM information_schema.TABLES GROUP BY table_schema; 

How do I clear the std::queue efficiently?

You could create a class that inherits from queue and clear the underlying container directly. This is very efficient.

template<class T>
class queue_clearable : public std::queue<T>
{
public:
    void clear()
    {
        c.clear();
    }
};

Maybe your a implementation also allows your Queue object (here JobQueue) to inherit std::queue<Job> instead of having the queue as a member variable. This way you would have direct access to c.clear() in your member functions.

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

Android ListView Text Color

You have to define the text color in the layout *simple_list_item_1* that defines the layout of each of your items.

You set the background color of the LinearLayout and not of the ListView. The background color of the child items of the LinearLayout are transparent by default (in most cases).

And you set the black text color for the TextView that is not part of your ListView. It is an own item (child item of the LinearLayout) here.

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

I had the same issue because the XML file I was uploading was encoded using UTF-8-BOM (UTF-8 byte-order mark).

Switched the encoding to UTF-8 in Notepad++ and was able to load the XML file in code.

How can I submit form on button click when using preventDefault()?

Ok, first e.preventDefault(); it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this

$('#subscription_order_form').submit(function(e){
    $.ajax({
     url: $(this).attr('action'),
     data : $(this).serialize(),
     success : function (data){

      }
   });
    e.preventDefault();
});

Insert picture into Excel cell

You can do it in a less than a minute with Google Drive (and free, no hassles)

• Bulk Upload all your images on imgur.com

• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.

• Use http://TextMechanic.co to prepend and append each line with this: Prefix : =image(" AND Suffix : ", 1)

So that it looks like this =image("URL", 1)

• Copy All

• Paste it in Google Spreadsheet

• Voila!

References :

http://www.labnol.org/internet/images-in-google-spreadsheet/18167/

https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1

Cannot delete or update a parent row: a foreign key constraint fails

The main problem with this erorr Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails is that it doesn't let you know which table contains the FK failure, so it is difficult to solve the conflict.

If you use MySQL or similar, I found out that you can create an ER diagram for your database, then you can review and safely remove any conflicts triggering the error.

  1. Use MySQL workbench
  2. Click on Database -> Reverse Engineering
  3. Select a correct connection
  4. Next till the end, remember to select database & tables that need examine
  5. Now you have the ER diagram, you can see which table have FK conflict

Android getting value from selected radiobutton

Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            RadioButton rb= (RadioButton) findViewById(checkedId);
            team = rb.getText().toString();
        }
    });

Splitting dataframe into multiple dataframes

In [28]: df = DataFrame(np.random.randn(1000000,10))

In [29]: df
Out[29]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Data columns (total 10 columns):
0    1000000  non-null values
1    1000000  non-null values
2    1000000  non-null values
3    1000000  non-null values
4    1000000  non-null values
5    1000000  non-null values
6    1000000  non-null values
7    1000000  non-null values
8    1000000  non-null values
9    1000000  non-null values
dtypes: float64(10)

In [30]: frames = [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]

In [31]: %timeit [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]
1 loops, best of 3: 849 ms per loop

In [32]: len(frames)
Out[32]: 16667

Here's a groupby way (and you could do an arbitrary apply rather than sum)

In [9]: g = df.groupby(lambda x: x/60)

In [8]: g.sum()    

Out[8]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16667 entries, 0 to 16666
Data columns (total 10 columns):
0    16667  non-null values
1    16667  non-null values
2    16667  non-null values
3    16667  non-null values
4    16667  non-null values
5    16667  non-null values
6    16667  non-null values
7    16667  non-null values
8    16667  non-null values
9    16667  non-null values
dtypes: float64(10)

Sum is cythonized that's why this is so fast

In [10]: %timeit g.sum()
10 loops, best of 3: 27.5 ms per loop

In [11]: %timeit df.groupby(lambda x: x/60)
1 loops, best of 3: 231 ms per loop

How do I run a batch file from my Java Application?

The executable used to run batch scripts is cmd.exe which uses the /c flag to specify the name of the batch file to run:

Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});

Theoretically you should also be able to run Scons in this manner, though I haven't tested this:

Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});

EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.

Codeigniter - multiple database connections

It works fine for me...

This is default database :

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Add another database at the bottom of database.php file

$db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

In autoload.php config file

$autoload['libraries'] = array('database', 'email', 'session');

The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...

<?php
    class Seconddb_model extends CI_Model {
        function __construct(){
            parent::__construct();
            //load our second db and put in $db2
            $this->db2 = $this->load->database('second', TRUE);
        }

        public function getsecondUsers(){
            $query = $this->db2->get('members');
            return $query->result(); 
        }

    }
?>

Read file As String

It's very easy if you use Kotlin:

val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)

From readText() docs:

Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.

Str_replace for multiple items

In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.

<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

How to resolve Nodejs: Error: ENOENT: no such file or directory

92% additional asset processing scripts-webpack-plugin× ?wdm?: Error: ENOENT: no such file or directory, open....==> if anyone faced to such error, you should do followings: 1) you should check the if the file path is correct in angular.json file.

 "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/bootstrap/dist/js/bootstrap.js"
        ],

2) you should press crtl+c and re run the project.

What's the difference between event.stopPropagation and event.preventDefault?

event.preventDefault(); Stops the default action of an element from happening.

event.stopPropagation(); Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Spring CORS No 'Access-Control-Allow-Origin' header is present

I have found the solution in spring boot by using @CrossOrigin annotation.

@RestController
@CrossOrigin
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Better way of getting time in milliseconds in javascript?

If you have date object like

var date = new Date('2017/12/03');

then there is inbuilt method in javascript for getting date in milliseconds format which is valueOf()

date.valueOf(); //1512239400000 in milliseconds format

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

Rotating x axis labels in R for barplot

You can use ggplot2 to rotate the x-axis label adding an additional layer

theme(axis.text.x = element_text(angle = 90, hjust = 1))

How to concat two ArrayLists?

for a lightweight list that does not copy the entries, you may use sth like this:

List<Object> mergedList = new ConcatList<>(list1, list2);

here the implementation:

public class ConcatList<E> extends AbstractList<E> {

    private final List<E> list1;
    private final List<E> list2;

    public ConcatList(final List<E> list1, final List<E> list2) {
        this.list1 = list1;
        this.list2 = list2;
    }

    @Override
    public E get(final int index) {
        return getList(index).get(getListIndex(index));
    }

    @Override
    public E set(final int index, final E element) {
        return getList(index).set(getListIndex(index), element);
    }

    @Override
    public void add(final int index, final E element) {
        getList(index).add(getListIndex(index), element);
    }

    @Override
    public E remove(final int index) {
        return getList(index).remove(getListIndex(index));
    }

    @Override
    public int size() {
        return list1.size() + list2.size();
    }

    @Override
    public void clear() {
        list1.clear();
        list2.clear();
    }

    private int getListIndex(final int index) {
        final int size1 = list1.size();
        return index >= size1 ? index - size1 : index;
    }

    private List<E> getList(final int index) {
        return index >= list1.size() ? list2 : list1;
    }

}

How to add Class in <li> using wp_nav_menu() in Wordpress?

<?php
    echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
            wp_nav_menu(
                    array(
                        'menu' => $nav_menu, 
                        'container'  => false,
                        'container_class'   => false,
                        'menu_class'        => false,
                        'items_wrap'        => '%3$s',
                                            'depth'             => 1,
                                            'echo'              => false
                            )
                    )
            );
?>

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

How to stop C++ console application from exiting immediately?

Add the following lines before any exit() function or before any returns in main():

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

Mapping many-to-many association table with extra column(s)

I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.

Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).

First here is the Java objects.

public class A implements Serializable{  

    protected int id;
    // put some others fields if needed ...   
    private Set<AC> ac = new HashSet<AC>();

    public A(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Set<AC> getAC() {
        return ac;
    }

    public void setAC(Set<AC> ac) {
        this.ac = ac;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 97;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof A))
            return false;
        final A other = (A) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

public class C implements Serializable{

    protected int id;
    // put some others fields if needed ...    

    public C(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    /** {@inheritDoc} */
    @Override
    public int hashCode() {
        final int prime = 98;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    /** {@inheritDoc} */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof C))
            return false;
        final C other = (C) obj;
        if (id != other.getId())
            return false;
        return true;
    }

}

Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).

public class ACId implements Serializable{

    private A a;
    private C c;

    public ACId() {
        super();
    }

    public A getA() {
        return a;
    }
    public void setA(A a) {
        this.a = a;
    }
    public C getC() {
        return c;
    }
    public void setC(C c) {
        this.c = c;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((a == null) ? 0 : a.hashCode());
        result = prime * result
                + ((c == null) ? 0 : c.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ACId other = (ACId) obj;
        if (a == null) {
            if (other.a != null)
                return false;
        } else if (!a.equals(other.a))
            return false;
        if (c == null) {
            if (other.c != null)
                return false;
        } else if (!c.equals(other.c))
            return false;
        return true;
    }
}

Now let's create the association object itself.

public class AC implements java.io.Serializable{

    private ACId id = new ACId();
    private String extra;

    public AC(){

    }

    public ACId getId() {
        return id;
    }

    public void setId(ACId id) {
        this.id = id;
    }

    public A getA(){
        return getId().getA();
    }

    public C getC(){
        return getId().getC();
    }

    public void setC(C C){
        getId().setC(C);
    }

    public void setA(A A){
        getId().setA(A);
    }

    public String getExtra() {
        return extra;
    }

    public void setExtra(String extra) {
        this.extra = extra;
    }

    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        AC that = (AC) o;

        if (getId() != null ? !getId().equals(that.getId())
                : that.getId() != null)
            return false;

        return true;
    }

    public int hashCode() {
        return (getId() != null ? getId().hashCode() : 0);
    }
}

At this point, it's time to map all our classes with hibernate xml configuration.

A.hbm.xml and C.hxml.xml (quiete the same).

<class name="A" table="a">
        <id name="id" column="id_a" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">a_id_seq</param>
            </generator>
        </id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
    <set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
        <key>
            <column name="id_a" not-null="true" />
        </key>
        <one-to-many class="AC" />
    </set>
</class>

<class name="C" table="c">
        <id name="id" column="id_c" unsaved-value="0">
            <generator class="identity">
                <param name="sequence">c_id_seq</param>
            </generator>
        </id>
</class>

And then association mapping file, a_c.hbm.xml.

<class name="AC" table="a_c">
    <composite-id name="id" class="ACId">
        <key-many-to-one name="a" class="A" column="id_a" />
        <key-many-to-one name="c" class="C" column="id_c" />
    </composite-id>
    <property name="extra" type="string" column="extra" />
</class>

Here is the code sample to test.

A = ADao.get(1);
C = CDao.get(1);

if(A != null && C != null){
    boolean exists = false;
            // just check if it's updated or not
    for(AC a : a.getAC()){
        if(a.getC().equals(c)){
            // update field
            a.setExtra("extra updated");
            exists = true;
            break;
        }
    }

    // add 
    if(!exists){
        ACId idAC = new ACId();
        idAC.setA(a);
        idAC.setC(c);

        AC AC = new AC();
        AC.setId(idAC);
        AC.setExtra("extra added"); 
        a.getAC().add(AC);
    }

    ADao.save(A);
}

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

Send File Attachment from Form Using phpMailer and PHP

This will work perfectly

    <form method='post' enctype="multipart/form-data">
    <input type='file' name='uploaded_file' id='uploaded_file' multiple='multiple' />
    <input type='submit' name='upload'/> 
    </form>

    <?php
           if(isset($_POST['upload']))
        {
             if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK)
                {
                     if (array_key_exists('uploaded_file', $_FILES))
                        { 
                            $mail->Subject = "My Subject";
                            $mail->Body = 'This is the body';
                            $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['uploaded_file']['name']));
                        if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile))
                             $mail->addAttachment($uploadfile,$_FILES['uploaded_file']['name']); 
                            $mail->send();
                            echo 'Message has been sent';
                        }       
                else
                    echo "The file is not uploaded. please try again.";
                }
                else
                    echo "The file is not uploaded. please try again";
        }
    ?>

How to get PID by process name?

Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():

>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)

Also, since Python 3.7, you can use the capture_output=true parameter to capture stdout and stderr:

>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)

How to click a browser button with JavaScript automatically?

this will work ,simple and easy

 `<form method="POST">
<input  type="submit" onclick="myFunction()" class="save" value="send" name="send" id="send" style="width:20%;">
</form>
<script language ="javascript" >
function myFunction() {
setInterval(function() {document.getElementById("send").click();}, 10000);    
}
</script>

`

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".

How to make an authenticated web request in Powershell?

For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.

Its a slightly modified version of this SO answer:
How to obtain numeric HTTP status codes in PowerShell

$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain); 
try
{
    $res = $req.GetResponse()
}
catch [System.Net.WebException]
{
    $res = $_.Exception.Response
}

$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"

How do I remove the height style from a DIV using jQuery?

maybe something like

$('div#someDiv').css("height", "auto");

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

here is another solution I started using after being fed up with the copy and paste issue:

  1. Download MRemote (for pc). this is an alternative to remote desktop manager. You can use remote desktop manager if you like.
  2. Change the VMNet settings to NAT or add another VMNet and set it to NAT.
  3. Configure the vm ip address with an ip in the same network as you host machine. if you want to keep networks separated use a second vmnet and set it's ip address in the same network as the host. that's what I use.
  4. Enable RDP connections on the guest (I only use windows guests)
  5. Create a batch file with this command. add your guest machines:

vmrun start D:\VM\MySuperVM1\vm1.vmx nogui vmrun start D:\VM\MySuperVM2\vm2.vmx nogui

save the file to startmyvms.cmd

create another batch file and add your vms

vmrun stop D:\VM\MySuperVM1\vm1.vmx nogui vmrun stop D:\VM\MySuperVM2\vm2.vmx nogui

save the file to stopmyvms.cmd

  1. Open Mremote go to tools => External tools Add external tool => filename will be the startmyvms.cmd file Add external tool => filename will be the stopmyvms.cmd file So to start working with your vms:

  2. Create you connections to your VMs in mremote

Now to work with your vm 1. You open mremote 2. You go to tools => external tools 3. You click the startmyvms tool when you're done 1. You go to tools => external tools 2. You click the stopmyvms external tool

you could add the vmrun start on the connection setting => external tool before connection and add the vmrun stop in the connection settings => external tool after

Voilà !

Showing the same file in both columns of a Sublime Text window

View -> Layout -> Choose one option or use shortcut

Layout        Shortcut

Single        Alt + Shift + 1
Columns: 2    Alt + Shift + 2
Columns: 3    Alt + Shift + 3
Columns: 4    Alt + Shift + 4
Rows: 2       Alt + Shift + 8
Rows: 3       Alt + Shift + 9
Grid: 4       Alt + Shift + 5

enter image description here

JQuery addclass to selected div, remove class if another div is selected

You can use a single line to add and remove class on a div. Please remove a class first to add a new class.

$('div').on('click',function(){
  $('div').removeClass('active').addClass('active');     
});

Displaying one div on top of another

Have the style for the parent div and the child divs' set as following. It worked for my case, hope it helps you as well..

<div id="parentDiv">
  <div id="backdrop"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

in your JS:

document.getElementById('parentDiv').style.position = 'relative';
document.getElementById('backdrop').style.position = 'absolute';
document.getElementById('curtain').style.position = 'absolute';
document.getElementById('curtain').style.zIndex= '2';//this number has to be greater than the zIndex of 'backdrop' if you are setting any

or in your CSS as in this working example:::

_x000D_
_x000D_
#parentDiv{_x000D_
  background: yellow;_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  position: relative;_x000D_
}_x000D_
#backdrop{_x000D_
  background: red;_x000D_
  height: 300px;_x000D_
  width: 300px;_x000D_
  position: absolute;_x000D_
}_x000D_
#curtain{_x000D_
  background: green;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  position: absolute;_x000D_
  z-index: 2;_x000D_
  margin: 100px 0px 150px 100px;_x000D_
}
_x000D_
<div id="parentDiv"><h2>_x000D_
  THIS IS PARENT DIV_x000D_
  </h2>_x000D_
  <div id="backdrop"><h4>_x000D_
  THIS IS BACKDROP DIV_x000D_
  </h4></div>_x000D_
  <div id="curtain"><h6>_x000D_
  THIS IS CURTAIN DIV_x000D_
  </h6></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

How to get out of while loop in java with Scanner method "hasNext" as condition?

I had the same problem and I solved it by reading the full line from the console with one scanner object, and then parsing the resulting string using a second scanner object.

Scanner console = new Scanner(System.in);
System.out.println("Enter input here:");
String inputLine = console.nextLine();

Scanner input = new Scanner(inputLine);
List<String> arg = new ArrayList<>();

while (input.hasNext()) {
    arg.add(input.next().toLowerCase());
}

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

I meet same error when start a new project. Use command line works for me.

./gradlew bootRun

equals vs Arrays.equals in Java

The Arrays.equals(array1, array2) :

check if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.

The array1.equals(array2) :

compare the object to another object and return true only if the reference of the two object are equal as in the Object.equals()

Is putting a div inside an anchor ever correct?

There's a DTD for HTML 4 at http://www.w3.org/TR/REC-html40/sgml/dtd.html . This DTD is the machine-processable form of the spec, with the limitation that a DTD governs XML and HTML 4, especially the "transient" flavor, permits a lot of things that are not "legal" XML. Still, I consider it comes close to codifying the intent of the specifiers.

<!ELEMENT A - - (%inline;)* -(A)       -- anchor -->

<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">

<!ENTITY % fontstyle "TT | I | B | BIG | SMALL">

<!ENTITY % phrase "EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >

<!ENTITY % special "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">

<!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">

I would interpret the tags listed in this hierarchy to be the total of tags allowed.

While the spec may say "inline elements," I'm pretty sure it's not intended that you can get around the intent by declaring the display type of a block element to be inline. Inline tags have different semantics no matter how you may abuse them.

On the other hand, I find it intriguing that the inclusion of special seems to allow nesting A elements. There's probably some strong wording in the spec that disallows this even if it's XML-syntactically correct but I won't pursue this further as it's not the topic of the question.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

There is no such tool till now to print the heap memory in the format as you requested The Only and only way to print is to write a java program with the help of Runtime Class,

public class TestMemory {

public static void main(String [] args) {

    int MB = 1024*1024;

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    //Print used memory
    System.out.println("Used Memory:" 
        + (runtime.totalMemory() - runtime.freeMemory()) / MB);

    //Print free memory
    System.out.println("Free Memory:" 
        + runtime.freeMemory() / mb);

    //Print total available memory
    System.out.println("Total Memory:" + runtime.totalMemory() / MB);

    //Print Maximum available memory
    System.out.println("Max Memory:" + runtime.maxMemory() / MB);
}

}

reference:https://viralpatel.net/blogs/getting-jvm-heap-size-used-memory-total-memory-using-java-runtime/

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

You can transfer those (simply by adding a remote to a GitHub repo and by pushing them)

  • create an empty repo on GitHub
  • git remote add github https://[email protected]/yourLogin/yourRepoName.git
  • git push --mirror github

The history will be the same.

But you will loose the access control (teams defined in GitLab with specific access rights on your repo)

If you facing any issue with the https URL of the GitHub repo:

The requested URL returned an error: 403

All you need to do is to enter your GitHub password, but the OP suggests:

Then you might need to push it the ssh way. You can read more on how to do it here.

See "Pushing to Git returning Error Code 403 fatal: HTTP request failed".

How to create a custom exception type in Java?

Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exeception*/
  throw new Exception("My one time exception with some message!");
}

Insert array into MySQL database with PHP

Insert array data into mysql php

I Have array data.. I want post that data in database

1: this is my array data:

stdClass Object
(
    [questions] => Array
        (
            [0] => stdClass Object
                (
                    [question_id] => 54
                    [question] => Which%20of%20the%20following%20is%20a%20rational%20number%20(s)%3F%3Cbr%20%2F%3E%0D%0A%3Cbr%20%2F%3E
                    [option_1] => %3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F010779c34ce28fee25778247e127b82d.png%22%20alt%3D%22%22%20%2F%3E%3Cspan%20class%3D%22Apple-tab-span%22%20style%3D%22white-space%3A%20pre%3B%20%22%3E%09%3C%2Fspan%3E
                    [option_2] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F3af35a16c371ffaaf9ea6891fb732478.png%22%20alt%3D%22%22%20%2F%3E
                    [option_3] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F4a57d5766a79f0ddf659d63c7443982b.png%22%20alt%3D%22%22%20%2F%3E
                    [option_4] => %26nbsp%3BAll%20the%20above%26nbsp%3B
                    [iscorrect] => yes
                    [answerGiven] => D
                    [marksobtain] => 2
                    [timetaken] => 3
                    [difficulty_levelval] => 2
                )


   [1] => stdClass Object
                (
                    [question_id] => 58
                    [question] => %3Cdiv%3EIf%20A%20%26nbsp%3B%3A%20Every%20whole%20number%20is%20a%20natural%20number%20and%3C%2Fdiv%3E%0D%0A%3Cdiv%3E%26nbsp%3B%20%26nbsp%3BR%20%3A%200%20is%20not%20a%20natural%20number%2C%3C%2Fdiv%3E%0D%0A%3Cdiv%3EThen%20which%20of%20the%20following%20statement%20is%20true%3F%3C%2Fdiv%3E
                    [option_1] => %26nbsp%3BA%20is%20False%20and%20R%20is%20true.
                    [option_2] => A%20is%20True%20and%20R%20is%20the%20correct%20explanation%20of%20A
                    [option_3] => %26nbsp%3BA%20is%20True%20and%20R%20is%20false
                    [option_4] => %26nbsp%3BBoth%20A%20and%20R%20are%20True
                    [iscorrect] => no
                    [answerGiven] => D
                    [marksobtain] => 0
                    [timetaken] => 2
                    [difficulty_levelval] => 2
                )

        )

)

code used i used to insert that data:

Code ::

<?php 
 //require_once("config_new2012.php");

require("codelibrary/fb/facebook.php");
include("codelibrary/inc/variables.php");
include_once(INC."functions.php");
include_once(CLASSES."frontuser_class.php");
include_once(CLASSES."testdetails_class.php");



$data = file_get_contents('php://input');
$arr_data = explode("=",$data);
$final_data = urldecode($arr_data[1]);
$final_data2 = json_decode($final_data);


 //print_r ($final_data2);



 if(is_array($final_data2)){
echo 'i am in array ';
    $sql = "INSERT INTO p_user_test_details(question_id, question, option_1, option_2, option_3, option_4,iscorrect,answerGiven,marksobtain,timetaken,difficulty_levelval) values ";

    $valuesArr = array();
    foreach($final_data2 as $row){

        $question_id = (int) $row['question_id'];
        $question = mysql_real_escape_string( $row['question'] );
        $option_1 = mysql_real_escape_string( $row['option_1'] );
    $option_2 = mysql_real_escape_string( $row['option_2'] );
    $option_3 = mysql_real_escape_string( $row['option_3'] );
    $option_4 = mysql_real_escape_string( $row['option_4'] );
    $iscorrect = mysql_real_escape_string( $row['iscorrect'] );
    $answerGiven = mysql_real_escape_string( $row['answerGiven'] );
        $marksobtain = mysql_real_escape_string( $row['marksobtain'] );
        $timetaken = mysql_real_escape_string( $row['timetaken'] );
        $difficulty_levelval = mysql_real_escape_string( $row['difficulty_levelval'] );
        $valuesArr[] = "('$question_id', '$question', '$option_1','$option_2','$option_3','$option_4','$iscorrect','$answerGiven','$marksobtain','$timetaken','$difficulty_levelval')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}
else{

echo 'no one is there ';
}

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:

enter image description here

  • Note 1: clientLeft also includes the width of the vertical scroll bar if the direction of the text is set to right-to-left (since the bar is displayed to the left in that case)

  • Note 2: the outermost line represents the closest positioned parent (an element whose position property is set to a value different than static or initial). Thus, if the direct container isn’t a positioned element, then the line doesn’t represent the first container in the hierarchy but another element higher in the hierarchy. If no positioned parent is found, the browser will take the html or body element as reference


Hope somebody finds it useful, just my 2 cents ;)

How to mock private method for testing using PowerMock?

I don't see a problem here. With the following code using the Mockito API, I managed to do just that :

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

And here's the JUnit test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        CodeWithPrivateMethod spy = PowerMockito.spy(new CodeWithPrivateMethod());

        when(spy, method(CodeWithPrivateMethod.class, "doTheGamble", String.class, int.class))
                .withArguments(anyString(), anyInt())
                .thenReturn(true);

        spy.meaningfulPublicApi();
    }
}

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step

geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx

Setting background colour of Android layout element

If you want to change a color quickly (and you don't have Hex numbers memorized) android has a few preset colors you can access like this:

android:background="@android:color/black"

There are 15 colors you can choose from which is nice for testing things out quickly, and you don't need to set up additional files.

Setting up a values/colors.xml file and using straight Hex like explained above will still work.

multiple packages in context:component-scan, spring config

The following approach is correct:

<context:component-scan base-package="x.y.z.service, x.y.z.controller" /> 

Note that the error complains about x.y.z.dao.daoservice.LoginDAO, which is not in the packages mentioned above, perhaps you forgot to add it:

<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" /> 

Fatal error: Call to a member function fetch_assoc() on a non-object

Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.

CakePHP select default value in SELECT input

 $this->Form->input('Leaf.id', array(
'type'=>'select',
'label'=>'Leaf',
'options'=>$leafs,
'value'=>2
));

This will select default second index position value from list of option in $leafs.

executing a function in sql plus

As another answer already said, call select myfunc(:y) from dual; , but you might find declaring and setting a variable in sqlplus a little tricky:

sql> var y number

sql> begin
  2  select 7 into :y from dual;
  3  end;
  4  /

PL/SQL procedure successfully completed.

sql> print :y

         Y
----------
         7

sql> select myfunc(:y) from dual;

Hide/Show components in react native

In your render function:

{ this.state.showTheThing && 
  <TextInput/>
}

Then just do:

this.setState({showTheThing: true})  // to show it  
this.setState({showTheThing: false}) // to hide it

Angular 2 execute script after template render

I've used this method (reported here )

export class AppComponent {

  constructor() {
    if(document.getElementById("testScript"))
      document.getElementById("testScript").remove();
    var testScript = document.createElement("script");
    testScript.setAttribute("id", "testScript");
    testScript.setAttribute("src", "assets/js/test.js");
    document.body.appendChild(testScript);
  }
}

it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.

How can I start PostgreSQL on Windows?

The easiest way to enable pg_ctl command is to go to your PostgreSQL directory ~\PostgreSQL\version\bin\ and execute the pg_ctl.exe. Afterwards the pg_ctl commands will be available.

What is the best way to check for Internet connectivity using .NET?

Does not solve the problem of network going down between checking and running your code but is fairly reliable

public static bool IsAvailableNetworkActive()
{
    // only recognizes changes related to Internet adapters
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
    {
        // however, this will include all adapters -- filter by opstatus and activity
        NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
        return (from face in interfaces
                where face.OperationalStatus == OperationalStatus.Up
                where (face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) && (face.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                select face.GetIPv4Statistics()).Any(statistics => (statistics.BytesReceived > 0) && (statistics.BytesSent > 0));
    }

    return false;
}

How do I check if a variable is of a certain type (compare two types) in C?

As others have mentioned, you can't extract the type of a variable at runtime. However, you could construct your own "object" and store the type along with it. Then you would be able to check it at runtime:

typedef struct {
   int  type;     // or this could be an enumeration
   union {
      double d;
      int i;
   } u;
} CheesyObject;

Then set the type as needed in the code:

CheesyObject o;
o.type = 1;  // or better as some define, enum value...
o.u.d = 3.14159;

How to add new item to hash

If you want to add new items from another hash - use merge method:

hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}

In your specific case it could be:

hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}

but it's not wise to use it when you should to add just one element more.

Pay attention that merge will replace the values with the existing keys:

hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}

exactly like hash[:item1] = 2

Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}

Find the files that have been changed in last 24 hours

You can do that with

find . -mtime 0

From man find:

[The] time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

"Caused by: java.util.concurrent.ExecutionException: java.lang.RuntimeException: The forked VM terminated without properly saying goodbye. VM crash or System.exit called?"

This issue can be occur if you use non compatible version of java. Like uses new version of java while code support some other version.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

If your data changes a lot, you can use

 mAdapter.notifyItemRangeChanged(0, yourData.size());

or some single items in your data set changes, your can use

 mAdapter.notifyItemChanged(pos);

For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged().

How do I count occurrence of duplicate items in array

If you have a multi-dimensional array you can use on PHP 5.5+ this:

array_count_values(array_column($array, 'key'))

which returns e.g.

 [
   'keyA' => 4,
   'keyB' => 2,
 ]

Where are the Properties.Settings.Default stored?

thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.

I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.

Passing properties by reference in C#

without duplicating the property

void Main()
{
    var client = new Client();
    NullSafeSet("test", s => client.Name = s);
    Debug.Assert(person.Name == "test");

    NullSafeSet("", s => client.Name = s);
    Debug.Assert(person.Name == "test");

    NullSafeSet(null, s => client.Name = s);
    Debug.Assert(person.Name == "test");
}

void NullSafeSet(string value, Action<string> setter)
{
    if (!string.IsNullOrEmpty(value))
    {
        setter(value);
    }
}

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

How can I take a screenshot with Selenium WebDriver?

C# code

IWebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((ITakesScreenshot)driver).GetScreenshotAs(OutputType.FILE);

// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Since Java 8, we can achieve this as follows:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

The output will be : "07/25/2017"

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

Check if all values of array are equal

I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.

given an array data[], then you can use:

for(x=0;x<data.length - 1;x++){
    if (data[x] != data[x+1]){
        isEqual = false;            
    }
}
alert("All elements are equal is " + isEqual);

How to shrink temp tablespace in oracle?

The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).

So, it could be as simple as this command, which will shrink your tablespace to 128 meg...

alter tablespace <your_temp_ts> shrink space keep 128M;

The Oracle online documentation is pretty good. Find out more.

edit

It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...

select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/

select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/ 

Then use that path in this command:

alter database datafile '/full/file/path/temp01.dbf'  resize 128m
/

How to convert a string Date to long millseconds

Try below code

        SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
        Date d = null;
        try {
            d = f.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timeInMillis = d.getTime();

How to fix 'android.os.NetworkOnMainThreadException'?

Although above there is a huge solution pool, no one mentioned com.koushikdutta.ion: https://github.com/koush/ion

It's also asynchronous and very simple to use:

Ion.with(context)
.load("http://example.com/thing.json")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

Add days to JavaScript Date

Correct Answer:

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Incorrect Answer:

This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.

// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example

Check this JsFiddle

_x000D_
_x000D_
// Correct_x000D_
function addDays(date, days) {_x000D_
    var result = new Date(date);_x000D_
    result.setDate(result.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad Year/Month_x000D_
function addDaysWRONG(date, days) {_x000D_
    var result = new Date();_x000D_
    result.setDate(date.getDate() + days);_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Bad during DST_x000D_
function addDaysDstFail(date, days) {_x000D_
    var dayms = (days * 24 * 60 * 60 * 1000);_x000D_
    return new Date(date.getTime() + dayms);    _x000D_
}_x000D_
_x000D_
// TEST_x000D_
function formatDate(date) {_x000D_
    return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();_x000D_
}_x000D_
_x000D_
$('tbody tr td:first-child').each(function () {_x000D_
    var $in = $(this);_x000D_
    var $out = $('<td/>').insertAfter($in).addClass("answer");_x000D_
    var $outFail = $('<td/>').insertAfter($out);_x000D_
    var $outDstFail = $('<td/>').insertAfter($outFail);_x000D_
    var date = new Date($in.text());_x000D_
    var correctDate = formatDate(addDays(date, 1));_x000D_
    var failDate = formatDate(addDaysWRONG(date, 1));_x000D_
    var failDstDate = formatDate(addDaysDstFail(date, 1));_x000D_
_x000D_
    $out.text(correctDate);_x000D_
    $outFail.text(failDate);_x000D_
    $outDstFail.text(failDstDate);_x000D_
    $outFail.addClass(correctDate == failDate ? "right" : "wrong");_x000D_
    $outDstFail.addClass(correctDate == failDstDate ? "right" : "wrong");_x000D_
});
_x000D_
body {_x000D_
    font-size: 14px;_x000D_
}_x000D_
_x000D_
table {_x000D_
    border-collapse:collapse;_x000D_
}_x000D_
table, td, th {_x000D_
    border:1px solid black;_x000D_
}_x000D_
td {_x000D_
    padding: 2px;_x000D_
}_x000D_
_x000D_
.wrong {_x000D_
    color: red;_x000D_
}_x000D_
.right {_x000D_
    color: green;_x000D_
}_x000D_
.answer {_x000D_
    font-weight: bold;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th colspan="4">DST Dates</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>03/10/2013</td></tr>_x000D_
        <tr><td>11/03/2013</td></tr>_x000D_
        <tr><td>03/09/2014</td></tr>_x000D_
        <tr><td>11/02/2014</td></tr>_x000D_
        <tr><td>03/08/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2013</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2013</td></tr>_x000D_
        <tr><td>02/01/2013</td></tr>_x000D_
        <tr><td>03/01/2013</td></tr>_x000D_
        <tr><td>04/01/2013</td></tr>_x000D_
        <tr><td>05/01/2013</td></tr>_x000D_
        <tr><td>06/01/2013</td></tr>_x000D_
        <tr><td>07/01/2013</td></tr>_x000D_
        <tr><td>08/01/2013</td></tr>_x000D_
        <tr><td>09/01/2013</td></tr>_x000D_
        <tr><td>10/01/2013</td></tr>_x000D_
        <tr><td>11/01/2013</td></tr>_x000D_
        <tr><td>12/01/2013</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2014</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2014</td></tr>_x000D_
        <tr><td>02/01/2014</td></tr>_x000D_
        <tr><td>03/01/2014</td></tr>_x000D_
        <tr><td>04/01/2014</td></tr>_x000D_
        <tr><td>05/01/2014</td></tr>_x000D_
        <tr><td>06/01/2014</td></tr>_x000D_
        <tr><td>07/01/2014</td></tr>_x000D_
        <tr><td>08/01/2014</td></tr>_x000D_
        <tr><td>09/01/2014</td></tr>_x000D_
        <tr><td>10/01/2014</td></tr>_x000D_
        <tr><td>11/01/2014</td></tr>_x000D_
        <tr><td>12/01/2014</td></tr>_x000D_
        <tr>_x000D_
            <th colspan="4">2015</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th>Input</th>_x000D_
            <th>+1 Day</th>_x000D_
            <th>+1 Day Fail</th>_x000D_
            <th>+1 Day DST Fail</th>_x000D_
        </tr>_x000D_
        <tr><td>01/01/2015</td></tr>_x000D_
        <tr><td>02/01/2015</td></tr>_x000D_
        <tr><td>03/01/2015</td></tr>_x000D_
        <tr><td>04/01/2015</td></tr>_x000D_
        <tr><td>05/01/2015</td></tr>_x000D_
        <tr><td>06/01/2015</td></tr>_x000D_
        <tr><td>07/01/2015</td></tr>_x000D_
        <tr><td>08/01/2015</td></tr>_x000D_
        <tr><td>09/01/2015</td></tr>_x000D_
        <tr><td>10/01/2015</td></tr>_x000D_
        <tr><td>11/01/2015</td></tr>_x000D_
        <tr><td>12/01/2015</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

In my case I had to wait for a user interaction, so I set a click or touchend listener.

const isMobile = navigator.maxTouchPoints || "ontouchstart" in document.documentElement;

function play(){
    audioEl.play()
}


document.body.addEventListener(isMobile ? "touchend" : "click", play, { once: true });

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

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

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

Capturing standard out and error with Start-Process

To get both stdout and stderr, I use:

Function GetProgramOutput([string]$exe, [string]$arguments)
{
    $process = New-Object -TypeName System.Diagnostics.Process
    $process.StartInfo.FileName = $exe
    $process.StartInfo.Arguments = $arguments

    $process.StartInfo.UseShellExecute = $false
    $process.StartInfo.RedirectStandardOutput = $true
    $process.StartInfo.RedirectStandardError = $true
    $process.Start()

    $output = $process.StandardOutput.ReadToEnd()   
    $err = $process.StandardError.ReadToEnd()

    $process.WaitForExit()

    $output
    $err
}

$exe = "cmd"
$arguments = '/c echo hello 1>&2'   #this writes 'hello' to stderr

$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]

[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)

Html.HiddenFor value property not getting set

Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For and take a lambda expression cannot work with weakly typed structures such as ViewData.

Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.

For example in your case I would define a view model:

public class MyViewModel
{
    [HiddenInput(DisplayValue = false)]
    public string CRN { get; set; }
}

have my controller action populate this view model:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        CRN = "foo bar"
    };
    return View(model);
}

and then have my strongly typed view simply use an EditorFor helper:

@model MyViewModel
@Html.EditorFor(x => x.CRN)

which would generate me:

<input id="CRN" name="CRN" type="hidden" value="foo bar" />

in the resulting HTML.

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

How to silence output in a Bash script?

Note: This answer is related to the question "How to turn off echo while executing a shell script Linux" which was in turn marked as duplicated to this one.

To actually turn off the echo the command is:

stty -echo

(this is, for instance; when you want to enter a password and you don't want it to be readable. Remember to turn echo on at the end of your script, otherwise the person that runs your script won't see what he/she types in from then on. To turn echo on run:

stty echo

Error in launching AVD with AMD processor

You need to read (and post) the output of

sc query intelhaxm

as stated on http://developer.android.com/tools/devices/emulator.html#accel-vm

You open a command prompt window by right click on the start menu, choose execute and write 'cmd'.

See also Android Emulator Doesn't Use HAXM .

If you cannot get the emulator to work you might want to try out an easier alternative: Genymotion - http://genymotion.com/

cocoapods - 'pod install' takes forever

Just go through the below step-by-step:

Download https://github.com/CocoaPods/Specs/archive/master.zip

RUN the Below commands in terminal:

pod setup --verbose

Open new tab in the terminal and RUN

mv ~/.cocoapods/repos/master/.git ~/tempSpecsGitFolder

open master.zip (unzipping it)

mv Specs-master ~/.cocoapods/repos/master

mv ~/tempSpecsGitFolder ~/.cocoapods/repos/master/.git

cd [project folder]

pod install --no-repo-update

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

How can you detect the version of a browser?

<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

How to install lxml on Ubuntu

Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.

apt-get install libxml2-dev libxslt1-dev python-dev

If you're happy with a possibly older version of lxml altogether though, you could try

apt-get install python-lxml

and be done with it. :)

Placeholder in IE9

A bit late to the party but I use my tried and trusted JS that takes advantage of Modernizr. Can be copy/pasted and applied to any project. Works every time:

// Placeholder fallback
if(!Modernizr.input.placeholder){

    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

}

Vue equivalent of setTimeout?

Add bind(this) to your setTimeout callback function

setTimeout(function () {
    this.basketAddSuccess = false
}.bind(this), 2000)

iPad WebApp Full Screen in Safari

Looks like most of the answers on this thread have not kept up. iOS Safari on iPads have fullscreen support now and it's very easy to implement using javascript.

Here's my full article on how to implement fullscreen capability on your web app.

C# error: Use of unassigned local variable

A couple of different ways to solve the problem:

Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}

Please add a @Pipe/@Directive/@Component annotation. Error

In my case, I accidentally added the package in the declaration but it should be in imports.

What does the "assert" keyword do?

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.

JavaDoc

Angular2 disable button

Yes you can

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
 </div>

https://angular.io/docs/ts/latest/api/common/NgClass-directive.html

Why does my 'git branch' have no master?

I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add . and then git commit and the master branch will be created.

Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

CONVERT Image url to Base64

In todays JavaScript, this will work as well..

_x000D_
_x000D_
const getBase64FromUrl = async (url) => {
  const data = await fetch(url);
  const blob = await data.blob();
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob); 
    reader.onloadend = function() {
      const base64data = reader.result;   
      resolve(base64data);
    }
  });
}

getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
_x000D_
_x000D_
_x000D_

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

How do I do redo (i.e. "undo undo") in Vim?

Practically speaking, the :undolist is hard to use and Vim’s :earlier and :later time tracking of changes is only usable for course-grain fixes.

Given that, I resort to a plug-in that combines these features to provide a visual tree of browsable undos, called “Gundo.”

Obviously, this is something to use only when you need a fine-grained fix, or you are uncertain of the exact state of the document you wish to return to. See: Gundo. Graph your Vim undo tree in style

How can I extract the folder path from file path in Python?

The built-in submodule os.path has a function for that very task.

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

Error in MySQL when setting default value for DATE or DATETIME

I've tested a fix as follow:

1). On the file "system/library/db/mysqli.php" search and comment the line: 
"$this->connection->query("SET SESSION sql_mode = 'NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION'");"

2) Add the following line above the one you just commented:
// Correction by Added by A.benkorich
$this->connection->query("SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY'");

Where does Anaconda Python install on Windows?

If you installed as admin ( and meant for all users )

C:\ProgramData\Anaconda3\Scripts\anaconda.exe

If you install as a normal user

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

jQuery Event : Detect changes to the html/text of a div

You can store the old innerHTML of the div in a variable. Set an interval to check if the old content matches the current content. When this isn't true do something.

How to detect Esc Key Press in React and how to handle it

If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):

class ActionPanel extends React.Component {
  constructor(props){
    super(props);
    this.escFunction = this.escFunction.bind(this);
  }
  escFunction(event){
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }
  componentDidMount(){
    document.addEventListener("keydown", this.escFunction, false);
  }
  componentWillUnmount(){
    document.removeEventListener("keydown", this.escFunction, false);
  }
  render(){
    return (   
      <input/>
    )
  }
}

Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.

EDIT: If you are using hooks, you can use this useEffect structure to produce a similar effect:

const ActionPanel = (props) => {
  const escFunction = useCallback((event) => {
    if(event.keyCode === 27) {
      //Do whatever when esc is pressed
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", escFunction, false);

    return () => {
      document.removeEventListener("keydown", escFunction, false);
    };
  }, []);

  return (   
    <input />
  )
};

Populating a ListView using an ArrayList?

Here's an example of how you could implement a list view:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //We have our list view
    final ListView dynamic = findViewById(R.id.dynamic);

    //Create an array of elements
    final ArrayList<String> classes = new ArrayList<>();
    classes.add("Data Structures");
    classes.add("Assembly Language");
    classes.add("Calculus 3");
    classes.add("Switching Systems");
    classes.add("Analysis Tools");

    //Create adapter for ArrayList
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);

    //Insert Adapter into List
    dynamic.setAdapter(adapter);

    //set click functionality for each list item
    dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("User clicked ", classes.get(position));
        }
    });



}

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

How can I open a popup window with a fixed size using the HREF tag?

You might want to consider using a div element pop-up window that contains an iframe.

jQuery Dialog is a simple way to get started. Just add an iframe as the content.

How to include External CSS and JS file in Laravel 5

At first, you have to put your .css or .js files in the public folder of your project. You may create subfolders to it and move the files into the subfolder. Then you have to do the followings

<link rel="stylesheet" href="{{asset('css/your_css_file.css')}}">
<script src="{{asset('js/your_js_file.js')}}"></script>

In my example, I have created two subfolders called css and js. I put all of the .css and .js files in corresponding folders and use them where ever I want them. Thank you and hope this helps you.

How do I execute a stored procedure in a SQL Agent job?

As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.

Cannot attach the file *.mdf as database

Ran into this issue. Caused in my case by deleting the .mdf while iispexress was still running and therefor still using the DB. Right click on iisexpress in system tray and click exit THEN delete the MDF to prevent this error from actually occurring.

To fix this error simply within VS right click the App-Data folder add new item > SQL Server Database. Name: [use the database name provided by the update-database error] Click Add.

How to concatenate strings in twig

In Symfony you can use this for protocol and host:

{{ app.request.schemeAndHttpHost }}

Though @alessandro1997 gave a perfect answer about concatenation.

How can I explicitly free memory in Python?

If you don't care about vertex reuse, you could have two output files--one for vertices and one for triangles. Then append the triangle file to the vertex file when you are done.

port 8080 is already in use and no process using 8080 has been listed

Open eclipse go to Servers panel, right click or press F3 to open Overview window and go to Ports (Modify the server ports). You will get the following:

tomcat adminport
HTTP/1.1
AJP/1.3

You can change the port numbers (e.g. HTTP/1.1 port number 8080 to 8082).

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Groovy method with optional parameters

Can't be done as it stands... The code

def myMethod(pParm1='1', pParm2='2'){
    println "${pParm1}${pParm2}"
}

Basically makes groovy create the following methods:

Object myMethod( pParm1, pParm2 ) {
    println "$pParm1$pParm2"
}

Object myMethod( pParm1 ) {
    this.myMethod( pParm1, '2' )
}

Object myMethod() {
    this.myMethod( '1', '2' )
}

One alternative would be to have an optional Map as the first param:

def myMethod( Map map = [:], String mandatory1, String mandatory2 ){
    println "${mandatory1} ${mandatory2} ${map.parm1 ?: '1'} ${map.parm2 ?: '2'}"
}

myMethod( 'a', 'b' )                // prints 'a b 1 2'
myMethod( 'a', 'b', parm1:'value' ) // prints 'a b value 2'
myMethod( 'a', 'b', parm2:'2nd')    // prints 'a b 1 2nd'

Obviously, documenting this so other people know what goes in the magical map and what the defaults are is left to the reader ;-)

Have a reloadData for a UITableView animate when changing

Swift 4 version for @dmarnel answer:

tableView.reloadSections(IndexSet(integer: 0), with: .automatic)

Hiding an Excel worksheet with VBA

I would like to answer your question, as there are various methods - here I’ll talk about the code that is widely used.

So, for hiding the sheet:

Sub try()
    Worksheets("Sheet1").Visible = xlSheetHidden
End Sub

There are other methods also if you want to learn all Methods Click here

update package.json version automatically

I want to add some clarity to the answers this question got.

Even thought there are some answers here that are tackling properly the problem and providing a solution, they are not the correct ones. The correct answer to this question is to use npm version

Is there a way to edit the file package.json automatically?

Yes, what you can do to make this happen is to run the npm version command when needed, you can read more about it here npm version, but the base usage would be npm version patch and it would add the 3rd digit order on your package.json version (1.0.X)

Would using a git pre-release hook help?

You could configure to run the npm version command on the pre-release hook, as you need, but that depends if that is what you need or not in your CD/CI pipe, but without the npm version command a git pre-release hook can't do anything "easily" with the package.json

The reason why npm version is the correct answer is the following:

  1. If the user is using a folder structure in which he has a package.json he is using npm if he is using npm he has access to the npm scripts.
  2. If he has access to npm scripts he has access to the npm version command.
  3. Using this command he doesn't need to install anything more in his computer or CD/CI pipe which on the long term will reduce the maintainability effort for the project, and will help with the setup

The other answers in which other tools are proposed are incorrect.

gulp-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

grunt-bump works but requires another extra package which could create issues in the long term (point 3 of my answer)

Div side by side without float

Use display:table-cell; for removing space between .Left and .Right

_x000D_
_x000D_
div.left {_x000D_
    background:blue;_x000D_
    height:200px;_x000D_
    width:300px;_x000D_
}_x000D_
_x000D_
div.right{_x000D_
    background:green;_x000D_
    height:300px;_x000D_
    width:100px;_x000D_
}_x000D_
_x000D_
.container{_x000D_
    background:black;_x000D_
    height:400px;_x000D_
    width:450px;_x000D_
}_x000D_
_x000D_
.container > div {_x000D_
    display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>_x000D_
    <div class="left">_x000D_
      LEFT_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>_x000D_
    <div class="right">_x000D_
      RIGHT_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

check the null terminating character in char*

To make this complete: while others now solved your problem :) I would like to give you a piece of good advice: don't reinvent the wheel.

size_t forward_length = strlen(forward);

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

how to refresh Select2 dropdown menu after ajax loading different content?

select2 has the placeholder parameter. Use that one

$("#state").select2({
   placeholder: "Choose a Country"
 });

Sending emails with Javascript

You don't need any javascript, you just need your href to be coded like this:

<a href="mailto:[email protected]">email me here!</a>

selenium get current url after loading a page

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

Is it possible to insert multiple rows at a time in an SQLite database?

I'm surprised that no one has mentioned prepared statements. Unless you are using SQL on its own and not within any other language, then I would think that prepared statements wrapped in a transaction would be the most efficient way of inserting multiple rows.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Jenkins CI: How to trigger builds on SVN commit

I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:

REPOS="$1"
REV="$2"

Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?

You can check out my script from GitHub.

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

It means display width

Whether you use tinyint(1) or tinyint(2), it does not make any difference.

I always use tinyint(1) and int(11), I used several mysql clients (navicat, sequel pro).

It does not mean anything AT ALL! I ran a test, all above clients or even the command-line client seems to ignore this.

But, display width is most important if you are using ZEROFILL option, for example your table has following 2 columns:

A tinyint(2) zerofill

B tinyint(4) zerofill

both columns has the value of 1, output for column A would be 01 and 0001 for B, as seen in screenshot below :)

zerofill with displaywidth

BeautifulSoup Grab Visible Webpage Text

I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.

I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

One solution posted above is:

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python

I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...

One answer here from @Helge was about using nltk of all things.

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop

Iterating through a list to render multiple widgets in Flutter?

The Dart language has aspects of functional programming, so what you want can be written concisely as:

List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();

Read this as "take each name in list and map it to a Text and form them back into a List".

How To Upload Files on GitHub

To upload files to your repo without using the command-line, simply type this after your repository name in the browser:

https://github.com/yourname/yourrepositoryname/upload/master

and then drag and drop your files.(provided you are on github and the repository has been created beforehand)

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

In my case the error was appearing because I had uploaded the whole folder, containing the website files, into the container.

I solved it by moving all the files outside the folder, right into the container.

Convert HTML to PDF in .NET

Instead of parsing HTML directly to PDF, you can create an Bitmap of your HTML-page and then insert the Bitmap into your PDF, using for example iTextSharp.

Here's a code how to get an Bitmap of an URL. I found it somewhere here on SO, if I find the source I'll link it.

public System.Drawing.Bitmap HTMLToImage(String strHTML)
{
    System.Drawing.Bitmap myBitmap = null;

    System.Threading.Thread myThread = new System.Threading.Thread(delegate()
    {
        // create a hidden web browser, which will navigate to the page
        System.Windows.Forms.WebBrowser myWebBrowser = new System.Windows.Forms.WebBrowser();
        // we don't want scrollbars on our image
        myWebBrowser.ScrollBarsEnabled = false;
        // don't let any errors shine through
        myWebBrowser.ScriptErrorsSuppressed = true;
        // let's load up that page!    
        myWebBrowser.Navigate("about:blank");

        // wait until the page is fully loaded
        while (myWebBrowser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
            System.Windows.Forms.Application.DoEvents();

        myWebBrowser.Document.Body.InnerHtml = strHTML;

        // set the size of our web browser to be the same size as the page
        int intScrollPadding = 20;
        int intDocumentWidth = myWebBrowser.Document.Body.ScrollRectangle.Width + intScrollPadding;
        int intDocumentHeight = myWebBrowser.Document.Body.ScrollRectangle.Height + intScrollPadding;
        myWebBrowser.Width = intDocumentWidth;
        myWebBrowser.Height = intDocumentHeight;
        // a bitmap that we will draw to
        myBitmap = new System.Drawing.Bitmap(intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding);
        // draw the web browser to the bitmap
        myWebBrowser.DrawToBitmap(myBitmap, new System.Drawing.Rectangle(0, 0, intDocumentWidth - intScrollPadding, intDocumentHeight - intScrollPadding));
    });
    myThread.SetApartmentState(System.Threading.ApartmentState.STA);
    myThread.Start();
    myThread.Join();

    return myBitmap;
}

How to represent a fix number of repeats in regular expression?

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

how to check if a form is valid programmatically using jQuery Validation Plugin

For a group of inputs you can use an improved version based in @mikemaccana's answer

$.fn.isValid = function(){
    var validate = true;
    this.each(function(){
        if(this.checkValidity()==false){
            validate = false;
        }
    });
};

now you can use this to verify if the form is valid:

if(!$(".form-control").isValid){
    return;
}

You could use the same technique to get all the error messages:

$.fn.getVelidationMessage = function(){
    var message = "";
    var name = "";
    this.each(function(){
        if(this.checkValidity()==false){
            name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
            message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
        }
    })
    return message;
}

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 2.0 & iOS 9 & Xcode 7.1

// 1. request an UITraitCollection instance
let deviceIdiom = UIScreen.mainScreen().traitCollection.userInterfaceIdiom

// 2. check the idiom
switch (deviceIdiom) {

case .Pad:
    print("iPad style UI")
case .Phone:
    print("iPhone and iPod touch style UI")
case .TV: 
    print("tvOS style UI")
default:
    print("Unspecified UI idiom")

}

Swift 3.0 and Swift 4.0

// 1. request an UITraitCollection instance
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom

// 2. check the idiom
switch (deviceIdiom) {

case .pad:
    print("iPad style UI")
case .phone:
    print("iPhone and iPod touch style UI")
case .tv: 
    print("tvOS style UI")
default:
    print("Unspecified UI idiom")
}

Use UITraitCollection. The iOS trait environment is exposed though the traitCollection property of the UITraitEnvironment protocol. This protocol is adopted by the following classes:

  • UIScreen
  • UIWindow
  • UIViewController
  • UIPresentationController
  • UIView

dropping a global temporary table

  1. Down the apache server by running below in putty cd $ADMIN_SCRIPTS_HOME ./adstpall.sh
  2. Drop the Global temporary tables drop table t;

This will workout..

How to run vbs as administrator from vbs?

Add this to the beginning of your file:

Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.Length = 0 Then
  Set ObjShell = CreateObject("Shell.Application")
  ObjShell.ShellExecute "wscript.exe" _
    , """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
  WScript.Quit
End if

Is there a way to use PhantomJS in Python?

In case you are using Buildout, you can easily automate the installation processes that Pykler describes using the gp.recipe.node recipe.

[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs

That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point bin/phantomjs, which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)

driver = webdriver.PhantomJS('bin/phantomjs')