Programs & Examples On #Nonblocking

Non-blocking mode I/O either transfers at least one byte or returns immediately with an error or end of stream. Non-blocking algorithms refer to use of concurrency without the usual mutual exclusion primitives, guaranteeing that thread operations will not block indefinitely. This is usually handled with atomic value modification (increment/decrement) and/or reading (compare-and-exchange) operations.. It isn't clear which this tag is intended for.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

Just to complete the existing answers, I'd suggest using select instead of nonblocking sockets. The point is that nonblocking sockets complicate stuff (except perhaps sending), so I'd say there is no reason to use them at all. If you regularly have the problem that your app is blocked waiting for IO, I would also consider doing the IO in a separate thread in the background.

C non-blocking keyboard input

If you are happy just catching Control-C, it's a done deal. If you really want non-blocking I/O but you don't want the curses library, another alternative is to move lock, stock, and barrel to the AT&T sfio library. It's nice library patterned on C stdio but more flexible, thread-safe, and performs better. (sfio stands for safe, fast I/O.)

A non-blocking read on a subprocess.PIPE in Python

This is a example to run interactive command in subprocess, and the stdout is interactive by using pseudo terminal. You can refer to: https://stackoverflow.com/a/43012138/3555925

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import select
import termios
import tty
import pty
from subprocess import Popen

command = 'bash'
# command = 'docker run -it --rm centos /bin/bash'.split()

# save original tty setting then set it to raw mode
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())

# open pseudo-terminal to interact with subprocess
master_fd, slave_fd = pty.openpty()

# use os.setsid() make it run in a new process group, or bash job control will not be enabled
p = Popen(command,
          preexec_fn=os.setsid,
          stdin=slave_fd,
          stdout=slave_fd,
          stderr=slave_fd,
          universal_newlines=True)

while p.poll() is None:
    r, w, e = select.select([sys.stdin, master_fd], [], [])
    if sys.stdin in r:
        d = os.read(sys.stdin.fileno(), 10240)
        os.write(master_fd, d)
    elif master_fd in r:
        o = os.read(master_fd, 10240)
        if o:
            os.write(sys.stdout.fileno(), o)

# restore tty settings back
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)

Polling the keyboard (detect a keypress) in python

None of these answers worked well for me. This package, pynput, does exactly what I need.

https://pypi.python.org/pypi/pynput

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Using npm behind corporate proxy .pac

Look for the url of the pac file in internet explorer lan settings and download the pac file from the URL configured. The pac file is just a javascript file with a function named FindProxyForURL which returns different proxy hosts in different scenarios.

Try to find a host in that pac file which you think is for general web traffic and plug it into .npmrc in C:\Users\<username>\.npmrc

proxy=http://<username>:<pass>@proxyhost:<port>
https-proxy=http://<uname>:<pass>@proxyhost:<port>

Even though you may login with your domain and username on your corporate machine, It is highly possible that the user active directory domain name is not required for the proxy, only the username and password (which may be different than your Active Directory login)

Don't forget to fiddle with escaping special password characters.

Print all but the first three columns

awk '{for(i=1;i<4;i++) $i="";print}' file

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

Plotting of 1-dimensional Gaussian distribution function

you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np 

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))

How to sort a HashSet?

1. Add all set element in list -> al.addAll(s);
2. Sort all the elements in list using -> Collections.sort(al);


 public class SortSetProblem {
 public static void main(String[] args) {
    ArrayList<String> al = new ArrayList();
    Set<String> s = new HashSet<>();
    s.add("ved");
    s.add("prakash");
    s.add("sharma");
    s.add("apple");
    s.add("ved");
    s.add("banana");
    System.out.println("Before Sorting");
    for (String s1 : s) {
        System.out.print("  " + s1);
    }

    System.out.println("After Sorting");
    al.addAll(s);
    Collections.sort(al);
    for (String set : al) {
        System.out.print(" " + set);
    }
  }
 }

input - ved prakash sharma apple ved banana

Output - apple banana prakash sharma ved

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

This is all perfectly normal. Microsoft added sequences in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.

If you want to have the old behaviour, you can:

  1. use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.
  2. use a sequence generator with the NO CACHE setting (http://msdn.microsoft.com/en-us/library/ff878091.aspx)

Is there a way to select sibling nodes?

have you checked the "Sibling" method in jQuery?

    sibling: function( n, elem ) {
        var r = [];

        for ( ; n; n = n.nextSibling ) {
            if ( n.nodeType === 1 && n !== elem ) {
                r.push( n );
            }
        }

        return r;
    }

the n.nodeType == 1 check if the element is a html node and n!== exclude the current element.

I think you can use the same function, all that code seems to be vanilla javascript.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

Here is a link to VeriSign's SSL Certificate Installation Checker: https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR1130

Enter your URL, click "Test this Web Server" and it will tell you if there are issues with your intermediate certificate authority.

IOS - How to segue programmatically using swift

Another option is to use modal segue

STEP 1: Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right. Lets call the storyboard ID ModalViewController

STEP 2: Open up the 'sender' view controller (let's call it ViewController) and add this code to it

public class ViewController {
  override func viewDidLoad() {
    showModalView()
  }

  func showModalView() {
    if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
      self.present(mvc, animated: true, completion: nil)
    }
  }
}

Note that the View Controller we want to open is also called ModalViewController

STEP 3: To close ModalViewController, add this to it

public class ModalViewController {
   @IBAction func closeThisViewController(_ sender: Any?) {
      self.presentingViewController?.dismiss(animated: true, completion: nil)
   }
}

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Try this:

str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)

Or, use single-quotes to quote your search and replace strings:

str.replace('"', '\\"');   // (Still need to escape the backslash)

As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:

str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');

But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:

var str = "Dude, he totally said that \"You Rock!\"";

But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.

Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.

Under what conditions is a JSESSIONID created?

Beware if your page is including other .jsp or .jspf (fragment)! If you don't set

<%@ page session="false" %>

on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.

For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jspf</url-pattern>
    </jsp-property-group>
</jsp-config>

in order to enable scriptlets inside them.

How to use LocalBroadcastManager?

By declaring one in your AndroidManifest.xml file with the tag (also called static)

<receiver android:name=".YourBrodcastReceiverClass"  android:exported="true">
<intent-filter>
    <!-- The actions you wish to listen to, below is an example -->
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>

You will notice that the broadcast receiver declared above has a property of exported=”true”. This attribute tells the receiver that it can receive broadcasts from outside the scope of the application.
2. Or dynamically by registering an instance with registerReceiver (what is known as context registered)

public abstract Intent registerReceiver (BroadcastReceiver receiver, 
            IntentFilter filter);

public void onReceive(Context context, Intent intent) {
//Implement your logic here
}

There are three ways to send broadcasts:
The sendOrderedBroadcast method, makes sure to send broadcasts to only one receiver at a time. Each broadcast can in turn, pass along data to the one following it, or to stop the propagation of the broadcast to the receivers that follow.
The sendBroadcast is similar to the method mentioned above, with one difference. All broadcast receivers receive the message and do not depend on one another.
The LocalBroadcastManager.sendBroadcast method only sends broadcasts to receivers defined inside your application and does not exceed the scope of your application.

How to merge specific files from Git branches

The simplest solution is:

git checkout the name of the source branch and the paths to the specific files that we want to add to our current branch

git checkout sourceBranchName pathToFile

What is the best collation to use for MySQL with PHP?

Be very, very aware of this problem that can occur when using utf8_general_ci.

MySQL will not distinguish between some characters in select statements, if the utf8_general_ci collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.

This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.

I'm no DBA, but to avoid this problem, I always go with utf8-bin instead of a case-insensitive one.

The script below describes the problem by example.

-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;

-- next, make sure that your client connection is of the same 
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci

-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
    CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');

-- (verify)
SELECT * FROM `test`;

-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are 
-- case insensitive (ending with _ci) do not distinguish between 
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to 
-- do the same with the 'latin1' charset:
--

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci

-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected). This shows 
-- that the problem with utf8/utf8_generic_ci isn't present 
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:

-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;

-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same 
-- way (for any sceptics out there):

-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci

-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';

--
-- Two keys.
--

DROP DATABASE sandbox;

How to grant remote access to MySQL for a whole subnet?

Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.

You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.

For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.

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

simply

#include <cstdio>

    int main(){
        // code...
        std::getchar();
        std::getchar();
        return 0;
    }

for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately. so what we aim to is a simple way of preventing a program from finishing after it outputs everything. Of course there are more complex and clean ways to solve this, but this is the simplest.

C# Help reading foreign characters using StreamReader

I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

What is the difference between persist() and merge() in JPA and Hibernate?

This is coming from JPA. In a very simple way:

  • persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

  • merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

How to create a multi line body in C# System.Net.Mail.MailMessage

Adding . before \r\n makes it work if the original string before \r\n has no .

Other characters may work. I didn't try.

With or without the three lines including IsBodyHtml, not a matter.

Compiling php with curl, where is curl installed?

Try just --with-curl, without specifying a location, and see if it'll find it by itself.

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

Speed up rsync with Simultaneous/Concurrent File Transfers?

There are a number of alternative tools and approaches for doing this listed arround the web. For example:

  • The NCSA Blog has a description of using xargs and find to parallelize rsync without having to install any new software for most *nix systems.

  • And parsync provides a feature rich Perl wrapper for parallel rsync.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

How to create JSON string in C#

The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.

Split string into individual words Java

To include any separators between words (like everything except all lower case and upper case letters), we can do:

String mystring = "hi, there,hi Leo";
String[] arr = mystring.split("[^a-zA-Z]+");
for(int i = 0; i < arr.length; i += 1)
{
     System.out.println(arr[i]);
}

Here the regex means that the separators will be anything that is not a upper or lower case letter [^a-zA-Z], in groups of at least one [+].

Multiple conditions in ngClass - Angular 4

I had this similar issue. I wanted to set a class after looking at multiple expressions. ngClass can evaluate a method inside the component code and tell you what to do.

So inside an *ngFor:

<div [ngClass]="{'shrink': shouldShrink(a.category1, a.category2), 'showAll': section == 'allwork' }">{{a.listing}}</div>

And inside the component:

section = 'allwork';

shouldShrink(cat1, cat2) {
    return this.section === cat1 || this.section === cat2 ? false : true;
}

Here I need to calculate if i should shrink a div based on if a 2 different categories have matched what the selected category is. And it works. So from there you can computer a true/false for the [ngClass] based on what your method returns given the inputs.

CSS Change List Item Background Color with Class

Live Demo


If you want this to be highlighted depending upon the page your user is on then do this:

To auto-highlight your current navigation, first label your body tags with an ID or class that matches the section of the site (usually a directory) that the page is in.

<body class="ab">

We label all files in the "/about/" directory with the "ab" class. Note that we use a class here to label the body tags. We found that using an ID in the body did not work consistently in some older browsers. Next we label our menu items so we can target them individually thus:

<div id="n"> <a class="b" id="hm"
href="/">Home</a> ... <a class="b"
id="ab" href="/about/">About</a> ...
</div>

Note that we use the "b"utton class to label menu items as buttons and an ID ("ab") to label each unique menu item (in this case about). Now all we need is a CSS selector that matches up the body label with the appropriate menu label like this:

body.ab #n #ab, body.ab #n #ab
a{color:#333;background:#dcdcdc;text-decoration:none;}

This code effectively highlights the "About" menu item and makes it appear dark gray. When you label the rest of the site and menu items, you'll end up with a grouped selector that looks something like this:

body.hm #n #hm, body.hm #n #hm a,
body.sm #n #sm, body.sm #n #sm a,
body.is #n #is, body.is #n #is a,
body.ab #n #ab, body.ab #n #ab a, 
body.ct #n #ct, body.ct #n #ct
a{color:#333;background:#dcdcdc;text-decoration:none;}

For example when the user navigates to the sitemap section the .sm classed body tag matches the #sm menu option and triggers the CSS highlight of the "Sitemap" in the navigation bar.

Source

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

Angularjs $http post file and form data

I recently wrote a directive that supports native multiple file uploads. The solution I've created relies on a service to fill the gap you've identified with the $http service. I've also included a directive, which provides an easy API for your angular module to use to post the files and data.

Example usage:

<lvl-file-upload
    auto-upload='false'
    choose-file-button-text='Choose files'
    upload-file-button-text='Upload files'
    upload-url='http://localhost:3000/files'
    max-files='10'
    max-file-size-mb='5'
    get-additional-data='getData(files)'
    on-done='done(files, data)'
    on-progress='progress(percentDone)'
    on-error='error(files, type, msg)'/>

You can find the code on github, and the documentation on my blog

It would be up to you to process the files in your web framework, but the solution I've created provides the angular interface to getting the data to your server. The angular code you need to write is to respond to the upload events

angular
    .module('app', ['lvl.directives.fileupload'])
    .controller('ctl', ['$scope', function($scope) {
        $scope.done = function(files,data} { /*do something when the upload completes*/ };
        $scope.progress = function(percentDone) { /*do something when progress is reported*/ };
        $scope.error = function(file, type, msg) { /*do something if an error occurs*/ };
        $scope.getAdditionalData = function() { /* return additional data to be posted to the server*/ };

    });

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Java 8: merge lists with stream API

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

Firefox and SSL: sec_error_unknown_issuer

Had same issue this end of week, only Firefox will not accept certificate... The solution for me has been to add, in the apache configuration of the website, the intermediate certificate with the following line :

SSLCACertificateFile /your/path/to/ssl_ca_certs.pem

Find more infomration on https://httpd.apache.org/docs/2.4/fr/mod/mod_ssl.html

Where does Oracle SQL Developer store connections?

On linux systems:

~/.sqldeveloper/system<sqldeveloper_version>/o.jdeveloper.db.connection/connections.xml

Parsing domain from a URL

I have edited for you:

function getHost($Address) { 
    $parseUrl = parse_url(trim($Address));
    $host = trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 

    $parts = explode( '.', $host );
    $num_parts = count($parts);

    if ($parts[0] == "www") {
        for ($i=1; $i < $num_parts; $i++) { 
            $h .= $parts[$i] . '.';
        }
    }else {
        for ($i=0; $i < $num_parts; $i++) { 
            $h .= $parts[$i] . '.';
        }
    }
    return substr($h,0,-1);
}

All type url (www.domain.ltd, sub1.subn.domain.ltd will result to : domain.ltd.

Check if Cookie Exists

Sometimes you still need to know if Cookie exists in Response. Then you can check if cookie key exists:

HttpContext.Current.Response.Cookies.AllKeys.Contains("myCookie")

More info can be found here.

In my case I had to modify Response Cookie in Application_EndRequest method in Global.asax. If Cookie doesn't exist I don't touch it:

string name = "myCookie";
HttpContext context = ((HttpApplication)sender).Context;
HttpCookie cookie = null;

if (context.Response.Cookies.AllKeys.Contains(name))
{
    cookie = context.Response.Cookies[name];
}

if (cookie != null)
{
    // update response cookie
}

MySQL - SELECT * INTO OUTFILE LOCAL ?

Re: SELECT * INTO OUTFILE

Check if MySQL has permissions to write a file to the OUTFILE directory on the server.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

I use this method and it works well:

1- Copy And paste the .jar files under the libs folder.

2- Add compile fileTree(dir: 'libs', include: '*.jar') to dependencies in build.gradle then all the jars in the libs folder will be included..

3- Right click on libs folder and select 'Add as library' option from the list.

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Android XML Percent Symbol

Per google official documentation, use %1$s and %2$s http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Hello, %1$s! You have %2$d new messages.

Java synchronized method lock on object, or method?

This example (although not pretty one) can provide more insight into locking mechanism. If incrementA is synchronized, and incrementB is not synchronized, then incrementB will be executed ASAP, but if incrementB is also synchronized then it has to 'wait' for incrementA to finish, before incrementB can do its job.

Both methods are called onto single instance - object, in this example it is: job, and 'competing' threads are aThread and main.

Try with 'synchronized' in incrementB and without it and you will see different results.If incrementB is 'synchronized' as well then it has to wait for incrementA() to finish. Run several times each variant.

class LockTest implements Runnable {
    int a = 0;
    int b = 0;

    public synchronized void incrementA() {
        for (int i = 0; i < 100; i++) {
            this.a++;
            System.out.println("Thread: " + Thread.currentThread().getName() + "; a: " + this.a);
        }
    }

    // Try with 'synchronized' and without it and you will see different results
    // if incrementB is 'synchronized' as well then it has to wait for incrementA() to finish

    // public void incrementB() {
    public synchronized void incrementB() {
        this.b++;
        System.out.println("*************** incrementB ********************");
        System.out.println("Thread: " + Thread.currentThread().getName() + "; b: " + this.b);
        System.out.println("*************** incrementB ********************");
    }

    @Override
    public void run() {
        incrementA();
        System.out.println("************ incrementA completed *************");
    }
}

class LockTestMain {
    public static void main(String[] args) throws InterruptedException {
        LockTest job = new LockTest();
        Thread aThread = new Thread(job);
        aThread.setName("aThread");
        aThread.start();
        Thread.sleep(1);
        System.out.println("*************** 'main' calling metod: incrementB **********************");
        job.incrementB();
    }
}

Line Break in HTML Select Option?

You can use a library called select2

You also can look at this Stackoverflow Question & Answer

<select id="selectBox" style="width: 500px">
  <option value="1" data-desc="this is my <br> multiple line 1">option 1</option>
  <option value="2" data-desc="this is my <br> multiple line 2">option 2</option>
</select>

In javascript

$(function(){
  $("#selectBox").select2({
    templateResult: formatDesc
  });

  function formatDesc (opt) {
   var optdesc = $(opt.element).attr('data-desc'); 
    var $opt = $(
      '<div><strong>' + opt.text + '</strong></div><div>' + optdesc + '</div>'
    );
    return $opt;
  };
});

How to install plugins to Sublime Text 2 editor?

Without Package Manager

I highly recommend using the Package Manager as described in other answers as it's far more convenient for both installing and updating. However, sometimes plugins are not in the directory, so here is the manual approach.

First off, find your Packages directory in your Application Support/Sublime Text 2 directory, for example:

~/Library/Application Support/Sublime Text 2/Packages

Now, take your Plugin folder (which you can download as a zip from GitHub, for example) and simply copy the folder into your Packages directory:

cp ~/Downloads/SomePlugin-master/ 
   ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/SomePlugin`

Restart Sublime Text 2 and boom! you're done.

With Package Manager

Refer to one of the other answers here or go to the Package Manager home page.

Bonus Points

If there's a plugin that isn't in the Package Manager, why not submit it on behalf of the author by following the steps found here.

How can I obtain the element-wise logical NOT of a pandas Series?

To invert a boolean Series, use ~s:

In [7]: s = pd.Series([True, True, False, True])

In [8]: ~s
Out[8]: 
0    False
1    False
2     True
3    False
dtype: bool

Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:

In [119]: s = pd.Series([True, True, False, True]*10000)

In [10]:  %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop

In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop

In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop

As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray; they are now subclasses of pd.NDFrame. This might have something to do with why np.invert(s) is no longer as fast as ~s or -s.

Caveat: timeit results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.

How to perform a real time search and filter on a HTML table

Datatable JS plugin is also one good alternate to accomedate search feature for html table

var table = $('#example').DataTable();

// #myInput is a <input type="text"> element
$('#myInput').on( 'keyup', function () {
    table.search( this.value ).draw();
} );

https://datatables.net/examples/basic_init/zero_configuration.html

Access to the path is denied

I Solved with this setting:

IIS > Application Pools > [your site] > Advanced Settings... > Identity > Built-in accound > LocalSystem

Automapper missing type map configuration or unsupported mapping - Error

I know this is a rather old question as of now, but I had found the proper solution was that I was not declaring the assembly attribute.

My code is:

using AutoMapper;
...

namespace [...].Controllers
{
    public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
    {
        Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
    }
    ...
}

This was fixed by adding the following line before my namespace declaration:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]

The full code is:

using AutoMapper;
...

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]

namespace [...].Controllers
{
    public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
    {
        Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
    }
    ...
}

Constantly print Subprocess output while process is running

There is actually a really simple way to do this when you just want to print the output:

import subprocess
import sys

def execute(command):
    subprocess.check_call(command, stdout=sys.stdout, stderr=subprocess.STDOUT)

Here we're simply pointing the subprocess to our own stdout, and using existing succeed or exception api.

How to make IPython notebook matplotlib plot inline

I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Creating a simple XML file using python

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
        DOC(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),
            )   
        )   

print lxml.etree.tostring(the_doc, pretty_print=True)

Output:

<root>
  <doc>
    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>
  </doc>
</root>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))

Powershell Get-ChildItem most recent file in directory

If you want the latest file in the directory and you are using only the LastWriteTime to determine the latest file, you can do something like below:

gci path | sort LastWriteTime | select -last 1

On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar

gci path | select -last 1

Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}

Github "Updates were rejected because the remote contains work that you do not have locally."

You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

How to load data to hive from HDFS without removing the source file?

I found that, when you use EXTERNAL TABLE and LOCATION together, Hive creates table and initially no data will present (assuming your data location is different from the Hive 'LOCATION').

When you use 'LOAD DATA INPATH' command, the data get MOVED (instead of copy) from data location to location that you specified while creating Hive table.

If location is not given when you create Hive table, it uses internal Hive warehouse location and data will get moved from your source data location to internal Hive data warehouse location (i.e. /user/hive/warehouse/).

recursively use scp but excluding some folders

Although scp supports recursive directory copying with the -r option, it does not support filtering of the files. There are several ways to accomplish your task, but I would probably rely on find, xargs, tar, and ssh instead of scp.

find . -type d -wholename '*bench*/image' \
| xargs tar cf - \
| ssh user@remote tar xf - -C /my/dir

The rsync solution can be made to work, but you are missing some arguments. rsync also needs the r switch to recurse into subdirectories. Also, if you want the same security of scp, you need to do the transfer under ssh. Something like:

rsync -avr -e "ssh -l user" --exclude 'fl_*' ./bench* remote:/my/dir

How to execute Ant build in command line

Try running all targets individually to check that all are running correct

run ant target name to run a target individually

e.g. ant build-project

Also the default target you specified is

project basedir="." default="build" name="iControlSilk4J"

This will only execute build-subprojects,build-project and init

No resource found that matches the given name '@style/Theme.AppCompat.Light'

If you are looking for the solution in Android Studio :

  1. Right click on your app
  2. Open Module Settings
  3. Select Dependencies tab
  4. Click on green + symbol which is on the right side
  5. Select Library Dependency
  6. Choose appcompat-v7 from list

Move view with keyboard using Swift

func registerForKeyboardNotifications()
    {
        //Keyboard
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWasShown), name: UIKeyboardDidShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIKeyboardDidHideNotification, object: nil)


    }
    func deregisterFromKeyboardNotifications(){

        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)

    }
    func keyboardWasShown(notification: NSNotification){

        let userInfo: NSDictionary = notification.userInfo!
        let keyboardInfoFrame = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue()

        let windowFrame:CGRect = (UIApplication.sharedApplication().keyWindow!.convertRect(self.view.frame, fromView:self.view))

        let keyboardFrame = CGRectIntersection(windowFrame, keyboardInfoFrame!)

        let coveredFrame = UIApplication.sharedApplication().keyWindow!.convertRect(keyboardFrame, toView:self.view)

        let contentInsets = UIEdgeInsetsMake(0, 0, (coveredFrame.size.height), 0.0)
        self.scrollViewInAddCase .contentInset = contentInsets;
        self.scrollViewInAddCase.scrollIndicatorInsets = contentInsets;
        self.scrollViewInAddCase.contentSize = CGSizeMake((self.scrollViewInAddCase.contentSize.width), (self.scrollViewInAddCase.contentSize.height))

    }
    /**
     this method will fire when keyboard was hidden

     - parameter notification: contains keyboard details
     */
    func keyboardWillBeHidden (notification: NSNotification) {

        self.scrollViewInAddCase.contentInset = UIEdgeInsetsZero
        self.scrollViewInAddCase.scrollIndicatorInsets = UIEdgeInsetsZero

    }

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

Entity framework linq query Include() multiple children entities

Use extension methods. Replace NameOfContext with the name of your object context.

public static class Extensions{
   public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country") ;
     }

     public static Company CompanyById(this NameOfContext context, int companyID){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country")
             .FirstOrDefault(c => c.Id == companyID) ;
      }

}

Then your code becomes

     Company company = 
          context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);

     //or if you want even more
     Company company = 
          context.CompanyById(companyID);

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;
}

How do I pass parameters to a jar file at the time of execution?

The JAVA Documentation says:

java [ options ] -jar file.jar [ argument ... ]

and

... Non-option arguments after the class name or JAR file name are passed to the main function...

Maybe you have to put the arguments in single quotes.

'Missing contentDescription attribute on image' in XML

This warning tries to improve accessibility of your application.

To disable missing content description warning in the whole project, you can add this to your application module build.gradle

android {

    ...

    lintOptions {
        disable 'ContentDescription'
    }
}

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

Why won't eclipse switch the compiler to Java 8?

This is a old topic but I just wanted to point out that I have searched enough to find that Indigo version can't be updated to S.E 1.8 here the link which is given on eclipse website to update the Execution Environment but if you try it will throw error for Indigo.

Image//wiki.eclipse.org/File:ExecutionEnvironmentDescriptionInstallation.png this is the link where the Information about execution environment is given.

https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler This shows the step by step to update Execution environment.

I have tried to update Execution environment and I got the same error.

How to dynamically create a class?

It will take some work, but is certainly not impossible.

What I have done is:

  • Create a C# source in a string (no need to write out to a file),
  • Run it through the Microsoft.CSharp.CSharpCodeProvider (CompileAssemblyFromSource)
  • Find the generated Type
  • And create an instance of that Type (Activator.CreateInstance)

This way you can deal with the C# code you already know, instead of having to emit MSIL.

But this works best if your class implements some interface (or is derived from some baseclass), else how is the calling code (read: compiler) to know about that class that will be generated at runtime?

How to trap on UIViewAlertForUnsatisfiableConstraints?

This post helped me A LOT!

I added UIViewAlertForUnsatisfiableConstraints symbolic breakpoint with suggested action:

Obj-C project

po [[UIWindow keyWindow] _autolayoutTrace]

Symbolic breakpoint with custom action in Objective-C project

Swift project

expr -l objc++ -O -- [[UIWindow keyWindow] _autolayoutTrace]

Symbolic breakpoint with custom action

With this hint, the log became more detailed, and It was easier for me identify which view had the constraint broken.

UIWindow:0x7f88a8e4a4a0
|   UILayoutContainerView:0x7f88a8f23b70
|   |   UINavigationTransitionView:0x7f88a8ca1970
|   |   |   UIViewControllerWrapperView:0x7f88a8f2aab0
|   |   |   |   •UIView:0x7f88a8ca2880
|   |   |   |   |   *UIView:0x7f88a8ca2a10
|   |   |   |   |   |   *UIButton:0x7f88a8c98820'Archived'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8cb0e30'Archived'
|   |   |   |   |   |   *UIButton:0x7f88a8ca22d0'Download'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8cb04e0'Download'
|   |   |   |   |   |   *UIButton:0x7f88a8ca1580'Deleted'
|   |   |   |   |   |   |   UIButtonLabel:0x7f88a8caf100'Deleted'
|   |   |   |   |   *UIView:0x7f88a8ca33e0
|   |   |   |   |   *_UILayoutGuide:0x7f88a8ca35b0
|   |   |   |   |   *_UILayoutGuide:0x7f88a8ca4090
|   |   |   |   |   _UIPageViewControllerContentView:0x7f88a8f1a390
|   |   |   |   |   |   _UIQueuingScrollView:0x7f88aa031c00
|   |   |   |   |   |   |   UIView:0x7f88a8f38070
|   |   |   |   |   |   |   UIView:0x7f88a8f381e0
|   |   |   |   |   |   |   |   •UIView:0x7f88a8f39fa0, MISSING HOST CONSTRAINTS
|   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8cb9bf0'Retrieve data'- AMBIGUOUS LAYOUT for UIButton:0x7f88a8cb9bf0'Retrieve data'.minX{id: 170}, UIButton:0x7f88a8cb9bf0'Retrieve data'.minY{id: 171}
|   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8f3ad80- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8f3ad80.minX{id: 172}, UIImageView:0x7f88a8f3ad80.minY{id: 173}
|   |   |   |   |   |   |   |   |   *App.RecordInfoView:0x7f88a8cbe530- AMBIGUOUS LAYOUT for App.RecordInfoView:0x7f88a8cbe530.minX{id: 174}, App.RecordInfoView:0x7f88a8cbe530.minY{id: 175}, App.RecordInfoView:0x7f88a8cbe530.Width{id: 176}, App.RecordInfoView:0x7f88a8cbe530.Height{id: 177}
|   |   |   |   |   |   |   |   |   |   +UIView:0x7f88a8cc1d30- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1d30.minX{id: 178}, UIView:0x7f88a8cc1d30.minY{id: 179}, UIView:0x7f88a8cc1d30.Width{id: 180}, UIView:0x7f88a8cc1d30.Height{id: 181}
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8cc1ec0- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1ec0.minX{id: 153}, UIView:0x7f88a8cc1ec0.minY{id: 151}, UIView:0x7f88a8cc1ec0.Width{id: 154}, UIView:0x7f88a8cc1ec0.Height{id: 165}
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e68e10- AMBIGUOUS LAYOUT for UIView:0x7f88a8e68e10.minX{id: 155}, UIView:0x7f88a8e68e10.minY{id: 150}, UIView:0x7f88a8e68e10.Width{id: 156}
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e65de0- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e65de0.minX{id: 159}, UIImageView:0x7f88a8e65de0.minY{id: 182}
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e69080'8-6-2015'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8e69080'8-6-2015'.minX{id: 183}, UILabel:0x7f88a8e69080'8-6-2015'.minY{id: 184}, UILabel:0x7f88a8e69080'8-6-2015'.Width{id: 185}
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0690'16:34'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8cc0690'16:34'.minX{id: 186}, UILabel:0x7f88a8cc0690'16:34'.minY{id: 187}, UILabel:0x7f88a8cc0690'16:34'.Width{id: 188}, UILabel:0x7f88a8cc0690'16:34'.Height{id: 189}
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8cc2050- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc2050.minX{id: 161}, UIView:0x7f88a8cc2050.minY{id: 166}, UIView:0x7f88a8cc2050.Width{id: 163}
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e69d90- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e69d90.minX{id: 190}, UIImageView:0x7f88a8e69d90.minY{id: 191}, UIImageView:0x7f88a8e69d90.Width{id: 192}, UIImageView:0x7f88a8e69d90.Height{id: 193}
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cc00
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e618d0
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e5ba10
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cd70
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e58e10
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e5e7a0
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3cee0
|   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3dc70
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e64dd0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e65290'Average flow rate'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8e712d0'177.0 ml/s'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8c97150'1299.4'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3dde0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3df50'Maximum flow rate'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cbfdb0'371.6 ml/s'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0230'873.5'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3e2a0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3e410'Total volume'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0f20'371.6 ml'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3e870
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3ea00'Time do max. flow'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc0ac0'3.6 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3ee10
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3efa0'Flow time'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cbf980'2.1 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3f3e0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3f570'Voiding time'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc17e0'3.5 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3f9a0
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8f3fb30'Voiding delay'
|   |   |   |   |   |   |   |   |   |   |   |   *UILabel:0x7f88a8cc1380'1.0 s'
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8e65000
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e52f20'Show'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e6e1d0
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e52c90'Send'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e61bb0
|   |   |   |   |   |   |   |   |   |   |   |   *UIButton:0x7f88a8e528e0'Delete'
|   |   |   |   |   |   |   |   |   |   |   |   *UIImageView:0x7f88a8e6b3f0
|   |   |   |   |   |   |   |   |   |   |   |   *UIView:0x7f88a8f3ff60
|   |   |   |   |   |   |   |   |   *UIActivityIndicatorView:0x7f88a8cba080
|   |   |   |   |   |   |   |   |   |   UIImageView:0x7f88a8cba700
|   |   |   |   |   |   |   |   |   *_UILayoutGuide:0x7f88a8cc3150
|   |   |   |   |   |   |   |   |   *_UILayoutGuide:0x7f88a8cc3b10
|   |   |   |   |   |   |   UIView:0x7f88a8f339c0
|   |   UINavigationBar:0x7f88a8c96810
|   |   |   _UINavigationBarBackground:0x7f88a8e45c00
|   |   |   |   UIImageView:0x7f88a8e46410
|   |   |   UINavigationItemView:0x7f88a8c97520'App'
|   |   |   |   UILabel:0x7f88a8c97cc0'App'
|   |   |   UINavigationButton:0x7f88a8e3e850
|   |   |   |   UIImageView:0x7f88a8e445b0
|   |   |   _UINavigationBarBackIndicatorView:0x7f88a8f2b530

Legend:
    * - is laid out with auto layout
    + - is laid out manually, but is represented in the layout engine because translatesAutoresizingMaskIntoConstraints = YES
    • - layout engine host

Then I paused execution Pause and I changed problematic view's background color with the command (replacing 0x7f88a8cc2050 with the memory address of your object of course)...

Obj-C

expr ((UIView *)0x7f88a8cc2050).backgroundColor = [UIColor redColor]

Swift 3.0

expr -l Swift -- import UIKit
expr -l Swift -- unsafeBitCast(0x7f88a8cc2050, to: UIView.self).backgroundColor = UIColor.red

... and the result It was awesome!

Hinted View

Simply amazing! Hope It helps.

Loop through all elements in XML using NodeList

public class XMLParser {
   public static void main(String[] args){
      try {
         DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = dBuilder.parse(new File("xml input"));
         NodeList nl=doc.getDocumentElement().getChildNodes();

         for(int k=0;k<nl.getLength();k++){
             printTags((Node)nl.item(k));
         }
      } catch (Exception e) {/*err handling*/}
   }

   public static void printTags(Node nodes){
       if(nodes.hasChildNodes()  || nodes.getNodeType()!=3){
           System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
           NodeList nl=nodes.getChildNodes();
           for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
       }
   }
}

Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Updating ReportViewer should works. Use below instruction to install updated ReportViewer from Nuget Package Manager console.

Install-Package Microsoft.ReportingServices.ReportViewerControl.WebForms

Just add below assembly reference in your aspx file.

Here, 15.0.0.0 is the version number of the ReportViewerControl.WebForms that was installed in my VS. Please check Reference of the Solution to confirm the version number. No need to add PublicTokens (if multiple installation exists, it may creates trouble again).

How to run Python script on terminal?

This Depends on what version of python is installed on you system. See below.

If You have Python 2.* version you have to run this command

python gameover.py

But if you have Python 3.* version you have to run this command

python3 gameover.py

Because for MAC with Python version 3.* you will get command not found error

if you run "python gameover.py"

Git refusing to merge unrelated histories on rebase

I struggled with this as well, but I managed to find a workaround.

When you run into the error above, just cherry-pick the merge commit and then continue the rebase:

git cherry-pick -m 1 1234deadbeef1234deadbeef
git rebase --continue

What is @ModelAttribute in Spring MVC?

I know this is an old thread, but I thought I throw my hat in the ring and see if I can muddy the water a little bit more :)

I found my initial struggle to understand @ModelAttribute was a result of Spring's decision to combine several annotations into one. It became clearer once I split it into several smaller annotations:

For parameter annotations, think of @ModelAttribute as the equivalent of @Autowired + @Qualifier i.e. it tries to retrieve a bean with the given name from the Spring managed model. If the named bean is not found, instead of throwing an error or returning null, it implicitly takes on the role of @Bean i.e. Create a new instance using the default constructor and add the bean to the model.

For method annotations, think of @ModelAttribute as the equivalent of @Bean + @Before, i.e. it puts the bean constructed by user's code in the model and it's always called before a request handling method.

Figuratively, I see @ModelAttribute as the following (please don't take it literally!!):

@Bean("person")
@Before
public Person createPerson(){
  return new Person();
}

@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
  ...
}

As you can see, Spring made the right decision to make @ModelAttribute an all-encompassing annotation; no one wants to see an annotation smorgasbord.

Local and global temporary tables in SQL Server

Quoting from Books Online:

Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions.

Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped using DROP TABLE:

  • A local temporary table created in a stored procedure is dropped automatically when the stored procedure completes. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process which called the stored procedure that created the table.
  • All other local temporary tables are dropped automatically at the end of the current session.
  • Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.

JQuery Calculate Day Difference in 2 date textboxes

This is how I did it using the Math.floor() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = Math.floor((end-start) / (365.25 * 24 * 60 * 60 * 1000));
console.log(diff);

You could also do it this way using the Math.round() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = new Date(end - start) / (1000 * 60 * 60 * 24 * 365.25);
var age = Math.round(diff);
console.log(age);

How to set cookies in laravel 5 independently inside controller

You may try this:

Cookie::queue($name, $value, $minutes);

This will queue the cookie to use it later and later it will be added with the response when response is ready to be sent. You may check the documentation on Laravel website.

Update (Retrieving A Cookie Value):

$value = Cookie::get('name');

Note: If you set a cookie in the current request then you'll be able to retrieve it on the next subsequent request.

Safest way to convert float to integer in python?

Combining two of the previous results, we have:

int(round(some_float))

This converts a float to an integer fairly dependably.

How to access a dictionary key value present inside a list?

First of all don't use 'list' as variable name.

If you have simple dictionaries with unique keys then you can do the following(note that new dictionary object with all items from sub-dictionaries will be created):

res  = {}
for line in listOfDicts:
   res.update(line)
res['d']
>>> 4

Otherwise:

getValues = lambda key,inputData: [subVal[key] for subVal in inputData if key in subVal]
getValues('d', listOfDicts)
>>> [4]

Or very base:

def get_value(listOfDicts, key):
    for subVal in listOfDicts:
        if key in subVal:
            return subVal[key]

How to convert int to string on Arduino?

The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.

char *i2str(int i, char *buf){
  byte l=0;
  if(i<0) buf[l++]='-';
  boolean leadingZ=true;
  for(int div=10000, mod=0; div>0; div/=10){
    mod=i%div;
    i/=div;
    if(!leadingZ || i!=0){
       leadingZ=false;
       buf[l++]=i+'0';
    }
    i=mod;
  }
  buf[l]=0;
  return buf;
}

Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.

How to format current time using a yyyyMMddHHmmss format?

Time package in Golang has some methods that might be worth looking.

func (Time) Format

func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,

Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.

Source (http://golang.org/pkg/time/#Time.Format)

I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)

func ExampleTime_Format() {
        // layout shows by example how the reference time should be represented.
        const layout = "Jan 2, 2006 at 3:04pm (MST)"
        t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
        fmt.Println(t.Format(layout))
        fmt.Println(t.UTC().Format(layout))
        // Output:
    // Nov 10, 2009 at 3:00pm (PST)
        // Nov 10, 2009 at 11:00pm (UTC)
    }

Check if an object exists

You can use:

try:
   # get your models
except ObjectDoesNotExist:
   # do something

Find out if string ends with another string in C++

Use std::equal algorithm from <algorithms> with reverse iteration:

std::string LogExt = ".log";
if (std::equal(LogExt.rbegin(), LogExt.rend(), filename.rbegin())) {
   …
}

Intercept and override HTTP requests from WebView

As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is

@Override public void onLoadResource(WebView view, String url)

This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...

How do I install the yaml package for Python?

following command will download pyyaml, which also includes yaml

pip install pyYaml

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

UITableView Separator line

You can add a UIImageView that is, for example, 1 point high and as wide as the cell's frame, and then set its origin to the bottom left corner of the cell.

Android Studio: Plugin with id 'android-library' not found

Add the below to the build.gradle project module:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

How to create Custom Ratings bar in Android

I investigated the original source,
and here is my result.

styles.xml (res/values)

<!-- RatingBar -->
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar_full</item>
    <item name="android:indeterminateDrawable">@drawable/ratingbar_full</item>
    <item name="android:minHeight">13.4dp</item>
    <item name="android:maxHeight">13.4dp</item>
</style>

ratingbar_full.xml (res/drawable)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/progress" android:drawable="@drawable/btn_rating_star_on_normal" />
</layer-list>

btn_rating_star_off_normal.png (res/drawable-xxhdpi)

enter image description here

btn_rating_star_on_normal.png (res/drawable-xxhdpi)

enter image description here

activity_ratingbar.xml (res/layout)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/ratingbar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="13.4dp"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="2.6"
        android:secondaryProgressTint="#00000000"
        android:stepSize="0.1" />
</FrameLayout>

This is the result.

enter image description here

  • Note that I added the actual height(13.4dp) of ratingbar in layout_height property, because if it is wrap_content it will draw lines below stars. (in my case only in a preview of Android Studio)

Hide keyboard in react-native

I just tested this using the latest React Native version (0.4.2), and the keyboard is dismissed when you tap elsewhere.

And FYI: you can set a callback function to be executed when you dismiss the keyboard by assigning it to the "onEndEditing" prop.

Convert bytes to bits in python

input_str = "ABC"
[bin(byte) for byte in bytes(input_str, "utf-8")]

Will give:

['0b1000001', '0b1000010', '0b1000011']

java.net.UnknownHostException: Invalid hostname for server: local

This might happen due to various reasons

1) Check if you have VPN connected, you might get this error sometimes if yes

"Your hostname, localhost resolves to a loopback address: 127.0.0.1; using 10.xxx.1.193 instead (on interface cscotun0)"

2) Check your $HOSTNAME

3) try to ping $HOSTNAME on commandline and if it doesnt work, tweak the system settings to make your local host respond to pings

What causes signal 'SIGILL'?

It means the CPU attempted to execute an instruction it didn't understand. This could be caused by corruption I guess, or maybe it's been compiled for the wrong architecture (in which case I would have thought the O/S would refuse to run the executable). Not entirely sure what the root issue is.

Tree view of a directory/folder in Windows?

TreeSize professional has what you want. but it focus on the sizes of folders and files.

What is the difference between association, aggregation and composition?

It's important to understand why we should even bother with using more than once relationship line. The most obvious reason is to describe parent-child relationship between classes (when parent deleted all its child’s are deleted as a result), but more impotently, we want to distinguish between simple association and composition in order to place implicit restrictions on the visibility and propagation of changes to the related classes, a matter which plays an important role in understanding and reducing system complexity.

Association

The most abstract way to describe static relationship between classes is using the Association link, which simply states that there is some kind of a link or a dependency between two classes or more.

Weak Association

ClassA may be linked to ClassB in order to show that one of its methods includes parameter of ClassB instance, or returns instance of ClassB.

Strong Association

ClassA may also be linked to ClassB in order to show that it holds a reference to ClassB instance.

Aggregation (Shared Association)

In cases where there’s a part-of relationship between ClassA (whole) and ClassB (part), we can be more specific and use the aggregation link instead of the association link, highlighting that ClassB can also be aggregated by other classes in the application (therefore aggregation is also known as shared association).

enter image description here

It’s important to note that the aggregation link doesn’t state in any way that ClassA owns ClassB nor that there’s a parent-child relationship (when parent deleted all its child’s are being deleted as a result) between the two. Actually, quite the opposite! The aggregation link usually used to stress the point that ClassA is not the exclusive container of ClassB, as in fact ClassB has another container.

Aggregation v.s. Association The association link can replace the aggregation link in every situation, while aggregation cannot replace association in situations where there’s only a ‘weak link’ between the classes, i.e. ClassA has method/s that contain parameter of ClassB but ClassA doesn’t hold reference to ClassB instance.

Martin Fowler suggest that the aggregation link should not be used at all because it has no added value and it disturb consistency, Quoting Jim Rumbaugh "Think of it as a modeling placebo".

Composition (Not-Shared Association)

We should be more specific and use the composition link in cases where in addition to the part-of relationship between ClassA and ClassB - there’s a strong lifecycle dependency between the two, meaning that when ClassA is deleted then ClassB is also deleted as a result

enter image description here

The composition link shows that a class (container, whole) has exclusive ownership over other class/s (parts), meaning that the container object and its parts constitute a parent-child/s relationship.

Unlike association and aggregation, when using the composition relationship, the composed class cannot appear as a return type or parameter type of the composite class. Thus, changes to the composed class cannot propagate to the rest of the system. Consequently, usage of composition limits complexity growth as the system grows.

Measuring system complexity

System complexity can be measured simply by looking at a UML class diagram and evaluating the association, aggregation, and composition relationship lines. The way to measure complexity is to determine how many classes can be affected by changing a particular class. If class A exposes class B, then any given class that uses class A can theoretically be affected by changes to class B. The sum of the number of potentially affected classes for every class in the system is the total system complexity.

You can read more on my blog: http://aviadezra.blogspot.com/2009/05/uml-association-aggregation-composition.html


How to check the multiple permission at single request in Android M?

I faced the same problem and below is the workaround I came up with:

public boolean checkForPermission(final String[] permissions, final int permRequestCode, int msgResourceId) {
        final List<String> permissionsNeeded = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            final String perm = permissions[i];
            if (ContextCompat.checkSelfPermission(getActivity(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(permissions[i])) {
                    final AlertDialog dialog = AlertDialog.newInstance( getResources().getString(R.string.permission_title), getResources().getString(msgResourceId) );
                    dialog.setPositiveButton("OK", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // add the request.
                            permissionsNeeded.add(perm);
                            dialog.dismiss();
                        }
                    });
                    dialog.show( getActivity().getSupportFragmentManager(), "HCFAlertDialog" );
                } else {
                    // add the request.
                    permissionsNeeded.add(perm);
                }
            }
        }

        if (permissionsNeeded.size() > 0) {
            // go ahead and request permissions
            requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]), permRequestCode);
            return false;
        } else {
            // no permission need to be asked so all good...we have them all.
            return true;
        }
    }

And you call the above method like this:

if ( checkForPermission( new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, 
Manifest.permission.CAMERA}, REQUEST_PERMISSION_EXTERNAL_STORAGE_RESULT, R.string.permission_image) ) {
                        // DO YOUR STUFF

                    }

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

Easiest way to read/write a file's content in Python

contents = open(filename)

This gives you generator so you must save somewhere the values though, or

contents = [line for line in open(filename)]

This does the saving to list explicit close is not then possible (at least with my knowledge of Python).

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

Save bitmap to file function

  1. You need an appropriate permission in manifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
  2. out.flush() check the out is not null..

  3. String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
    File dir = new File(file_path);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dir, "sketchpad" + pad.t_id + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
    
    bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();
    

How to get the current directory in a C program?

Look up the man page for getcwd.

Installing Oracle Instant Client

The directions state:

  1. Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
  2. Unzip the packages into a single directory such as "instantclient".
  3. Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
  4. Start your application and enjoy.

Suggest extracting/unzipping into a new directory. They've suggested instantclient, but you can name the directory anything you like. Name it C:\OracleInstantClient\ if you choose.

Then in Step 3, open a Windows Command Prompt. Type:

PATH C:\OracleInstantClient; %PATH%`

That's all there is to it!

How to install Openpyxl with pip

(optional) Install git for windows (https://git-scm.com/) to get git bash. Git bash is much more similar to Linux terminal than Windows cmd.

Install Anaconda 3

https://www.anaconda.com/download/

It should set itself into Windows PATH. Restart your PC. Then pip should work in your cmd

Then in cmd (or git bash), run command

pip install openpyxl

What is the difference between String and StringBuffer in Java?

A String is an immutable character array.

A StringBuffer is a mutable character array. Often converted back to String when done mutating.

Since both are an array, the maximum size for both is equal to the maximum size of an integer, which is 2^31-1 (see JavaDoc, also check out the JavaDoc for both String and StringBuffer).This is because the .length argument of an array is a primitive int. (See Arrays).

[Vue warn]: Cannot find element

The simple thing is to put the script below the document, just before your closing </body> tag:

<body>
   <div id="main">
      <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
   </div>
   <script src="app.js"></script>
</body>

app.js file:

var main = new Vue({
    el: '#main',
    data: {
        currentActivity: 'home'
    }
});

Relative URLs in WordPress

Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.

I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

Remove folder and its contents from git/GitHub's history

In addition to the popular answer above I would like to add a few notes for Windows-systems. The command

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
  • works perfectly without any modification! Therefore, you must not use Remove-Item, del or anything else instead of rm -rf.

  • If you need to specify a path to a file or directory use slashes like ./path/to/node_modules

How to check if a textbox is empty using javascript

Canonical without using frameworks with added trim prototype for older browsers

<html>
<head>
<script type="text/javascript">
// add trim to older IEs
if (!String.trim) {
  String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g, "");};
}

window.onload=function() { // onobtrusively adding the submit handler
  document.getElementById("form1").onsubmit=function() { // needs an ID
    var val = this.textField1.value; // 'this' is the form 
    if (val==null || val.trim()=="") { 
      alert('Please enter something');
      this.textField1.focus();
      return false; // cancel submission
    }
    return true; // allow submit
  }
}
</script>
</head>
<body>
<form id="form1">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>
</body>
</html>

Here is the inline version, although not recommended I show it here in case you need to add validation without being able to refactor the code

function validate(theForm) { // passing the form object
  var val = theForm.textField1.value;
  if (val==null || val.trim()=="") { 
    alert('Please enter something');
    theForm.textField1.focus();
    return false; // cancel submission
  }
  return true; // allow submit
}

passing the form object in (this)

<form onsubmit="return validate(this)">
  <input type="text" name="textField1" value="" /><br/>
  <input type="submit" />
</form>

Rethrowing exceptions in Java without losing the stack trace

something like this

try 
{
  ...
}
catch (FooException e) 
{
  throw e;
}
catch (Exception e)
{
  ...
}

What's the UIScrollView contentInset property for?

Content insets solve the problem of having content that goes underneath other parts of the User Interface and yet still remains reachable using scroll bars. In other words, the purpose of the Content Inset is to make the interaction area smaller than its actual area.

Consider the case where we have three logical areas of the screen:

TOP BUTTONS

TEXT

BOTTOM TAB BAR

and we want the TEXT to never appear transparently underneath the TOP BUTTONS, but we want the Text to appear underneath the BOTTOM TAB BAR and yet still allow scrolling so we could update the text sitting transparently under the BOTTOM TAB BAR.

Then we would set the top origin to be below the TOP BUTTONS, and the height to include the bottom of BOTTOM TAB BAR. To gain access to the Text sitting underneath the BOTTOM TAB BAR content we would set the bottom inset to be the height of the BOTTOM TAB BAR.

Without the inset, the scroller would not let you scroll up the content enough to type into it. With the inset, it is as if the content had extra "BLANK CONTENT" the size of the content inset. Blank text has been "inset" into the real "content" -- that's how I remember the concept.

Setting the User-Agent header for a WebClient request

const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
    var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
    var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
    if (knownRequestHeadersField != null)
    {
        string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
                    knownRequestHeaders[39] = ua;
    }
}

How to get day of the month?

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(aDate);
    return cal.get(Calendar.DAY_OF_MONTH);
}

How to style readonly attribute with CSS?

capitalize the first letter of Only

_x000D_
_x000D_
input[readOnly] {_x000D_
      background: red !important;_x000D_
    }
_x000D_
<input type="text" name="country" value="China" readonly="readonly" />
_x000D_
_x000D_
_x000D_

How to set the custom border color of UIView programmatically?

Swift 3.0

       groundTrump.layer.borderColor = UIColor.red.cgColor

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

VBA: Conditional - Is Nothing

In my sample code, I was setting my object to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing and also if not My_Object is nothing. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:

if My_Object is Nothing Then
    'do nothing
Else
    'Do something
End if

'profile name is not valid' error when executing the sp_send_dbmail command

You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.

Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx

See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx

Example script for 'TestUser' to use the profile named 'General Admin Mail'.


USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'General Admin Mail',
    @principal_name = 'TestUser',
    @is_default = 1 ;

Address validation using Google Maps API

Google's geocoding api does what want you want. As Xerus points out, as long as you are not using the geocoded points on a non-google Map, you should be good (terms of service). Specifically,

3.1 Use without a Google Map. Customer may use Google Maps Content from the Geocoding API in Customer Applications without a corresponding Google Map.


3.3 No use with a non-Google map.  Customer must not use Google Maps Content from the Geocoding API in conjunction with a non-Google map.

Who is listening on a given TCP port on Mac OS X?

I am a Linux guy. In Linux it is extremely easy with netstat -ltpn or any combination of those letters. But in Mac OS X netstat -an | grep LISTEN is the most humane. Others are very ugly and very difficult to remember when troubleshooting.

How can I remove an element from a list, with lodash?

you can do it with _pull.

_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});

check the reference

Why is the use of alloca() not considered good practice?

Here's why:

char x;
char *y=malloc(1);
char *z=alloca(&x-y);
*z = 1;

Not that anyone would write this code, but the size argument you're passing to alloca almost certainly comes from some sort of input, which could maliciously aim to get your program to alloca something huge like that. After all, if the size isn't based on input or doesn't have the possibility to be large, why didn't you just declare a small, fixed-size local buffer?

Virtually all code using alloca and/or C99 vlas has serious bugs which will lead to crashes (if you're lucky) or privilege compromise (if you're not so lucky).

Importing CSV data using PHP/MySQL

Database Connection:

 try {
        $conn = mysqli_connect($servername, $username, $password, $db);
        //echo "Connected successfully"; 
    } catch (exception $e) {
        echo "Connection failed: " . $e->getMessage();
    }

Code to read CSV file and upload to table in database.

   $file = fopen($filename, "r");
            while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
                $sql = "INSERT into db_table 
                   values ('','" . $getData[1] . "','" . $getData[2] . "','" . $getData[3] . "','" . $getData[4] . "','" . $getData[5] . "','" . $getData[6] . "')";
                $result = mysqli_query($conn, $sql);
                if (!isset($result)) {
                    echo "<script type=\"text/javascript\">
                            alert(\"Invalid File:Please Upload CSV File. 
                            window.location = \"home.do\"
                          </script>";
                } else {
                    echo "<script type=\"text/javascript\">
                        alert(\"CSV File has been successfully Imported.\");
                        window.location = \"home.do\"
                    </script>";
                }
            }
            fclose($file);

Installing PIL with pip

Install

pip install Pillow

Then, Just import in your file like,

from PIL import Image

I am using windows. It is working for me.

NOTE:

Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace.

i.e. change:

import Image

to:

from PIL import Image

https://pypi.org/project/Pillow/2.2.1/

What is Type-safe?

Type-safety should not be confused with static / dynamic typing or strong / weak typing.

A type-safe language is one where the only operations that one can execute on data are the ones that are condoned by the data's type. That is, if your data is of type X and X doesn't support operation y, then the language will not allow you to to execute y(X).

This definition doesn't set rules on when this is checked. It can be at compile time (static typing) or at runtime (dynamic typing), typically through exceptions. It can be a bit of both: some statically typed languages allow you to cast data from one type to another, and the validity of casts must be checked at runtime (imagine that you're trying to cast an Object to a Consumer - the compiler has no way of knowing whether it's acceptable or not).

Type-safety does not necessarily mean strongly typed, either - some languages are notoriously weakly typed, but still arguably type safe. Take Javascript, for example: its type system is as weak as they come, but still strictly defined. It allows automatic casting of data (say, strings to ints), but within well defined rules. There is to my knowledge no case where a Javascript program will behave in an undefined fashion, and if you're clever enough (I'm not), you should be able to predict what will happen when reading Javascript code.

An example of a type-unsafe programming language is C: reading / writing an array value outside of the array's bounds has an undefined behaviour by specification. It's impossible to predict what will happen. C is a language that has a type system, but is not type safe.

Using GregorianCalendar with SimpleDateFormat

SimpleDateFormat.format() method takes a Date as a parameter. You can get a Date from a Calendar by calling its getTime() method:

public static String format(GregorianCalendar calendar) {
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    fmt.setCalendar(calendar);
    String dateFormatted = fmt.format(calendar.getTime());

    return dateFormatted;
}

Also note that the months start at 0, so you probably meant:

int month = Integer.parseInt(splitDate[1]) - 1;

Java: Multiple class declarations in one file

Just FYI, if you are using Java 11+, there is an exception to this rule: if you run your java file directly (without compilation). In this mode, there is no restriction on a single public class per file. However, the class with the main method must be the first one in the file.

What is the difference between properties and attributes in HTML?

After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.

HTML attribute vs. DOM property

-------------------------------

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.

  • Some HTML attributes don't have corresponding properties. colspan is one example.

  • Some DOM properties don't have corresponding attributes. textContent is one example.

  • Many HTML attributes appear to map to properties ... but not in the way you might think!

That last category is confusing until you grasp this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob">, it creates a corresponding DOM node with a value property initialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute: input.getAttribute('value') returns "Bob".

The HTML attribute value specifies the initial value; the DOM value property is the current value.


The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When you add the disabled attribute, its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button>.

Setting the button's disabled property disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

Using grep to search for a string that has a dot in it

There are so many answers here suggesting to escape the dot with \. but I have been running into this issue over and over again: \. gives me the same result as .

However, these two expressions work for me:

$ grep -r 0\\.49 *

And:

$ grep -r 0[.]49 *

I'm using a "normal" bash shell on Ubuntu and Archlinux.

Edit, or, according to comments:

$ grep -r '0\.49' *

Note, the single-quotes doing the difference here.

Cannot call getSupportFragmentManager() from activity

This worked for me. Running android API 19 and above.

FragmentManager fragMan = getFragmentManager();

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Angular.js vs Knockout.js vs Backbone.js

    It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

    Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

    Very data driven app? Angular with its nice data binding.

    Game programming? None - direct to canvas; maybe a game engine.

    python numpy vector math

    You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

    As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

    Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

    Edit: Regarding your comment:

    1. Yes. The whole of numpy is based on arrays.

    2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

    3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

      An example in ipython:

      In [1]: import math
      
      In [2]: import numpy as np
      
      In [3]: a = np.array([4,2,7])
      
      In [4]: np.linalg.norm(a)
      Out[4]: 8.3066238629180749
      
      In [5]: math.sqrt(sum([n**2 for n in a]))
      Out[5]: 8.306623862918075
      
      In [6]: b = a/np.linalg.norm(a)
      
      In [7]: np.linalg.norm(b)
      Out[7]: 1.0
      

      Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

    Inheritance and Overriding __init__ in python

    Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

    How to append output to the end of a text file

    for the whole question:

    cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
    

    this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.

    Run the above with the cron every hour, or

    while :
    do
        cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
        sleep 3600
    done
    

    Differences between Lodash and Underscore.js

    I'm agree with most of things said here, but I just want to point out an argument in favor of Underscore.js: the size of the library.

    Specially in case you are developing an app or website which intend to be use mostly on mobile devices, the size of the resulting bundle and the effect on the boot or download time may have an important role.

    For comparison, these sizes are those I noticed with source-map-explorer after running Ionic serve:

    Lodash: 523 kB
    Underscore.js: 51.6 kB
    

    One can use BundlePhobia to check the current size of Lodash and Underscore.js.

    Trying to add adb to PATH variable OSX

    In your terminal, navigate to home directory

    cd
    create file .bash_profile
    
    touch .bash_profile
    open file with TextEdit
    
    open -e .bash_profile
    insert line into TextEdit
    
    export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/
    save file and reload file
    

    source ~/.bash_profile is very important check if adb was set into path

    adb version
    

    It should be fine now.

    SQL Server: Get data for only the past year

    I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.

    At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.

    SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
    

    Thanks to those above whose solutions helped me arrive at what I needed.

    What underlies this JavaScript idiom: var self = this?

    function Person(firstname, lastname) {
      this.firstname = firstname;
    
      this.lastname = lastname;
      this.getfullname = function () {
        return `${this.firstname}   ${this.lastname}`;
      };
    
      let that = this;
      this.sayHi = function() {
        console.log(`i am this , ${this.firstname}`);
        console.log(`i am that , ${that.firstname}`);
      };
    }
    
    let thisss = new Person('thatbetty', 'thatzhao');
    
    let thatt = {firstname: 'thisbetty', lastname: 'thiszhao'};
    

    thisss.sayHi.call(thatt);

    Open a Web Page in a Windows Batch FIle

    start did not work for me.

    I used:

    firefox http://www.stackoverflow.com
    

    or

    chrome http://www.stackoverflow.com
    

    Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.

    How to $http Synchronous call with AngularJS

    var EmployeeController = ["$scope", "EmployeeService",
            function ($scope, EmployeeService) {
                $scope.Employee = {};
                $scope.Save = function (Employee) {                
                    if ($scope.EmployeeForm.$valid) {
                        EmployeeService
                            .Save(Employee)
                            .then(function (response) {
                                if (response.HasError) {
                                    $scope.HasError = response.HasError;
                                    $scope.ErrorMessage = response.ResponseMessage;
                                } else {
    
                                }
                            })
                            .catch(function (response) {
    
                            });
                    }
                }
            }]
    
    
    var EmployeeService = ["$http", "$q",
                function ($http, $q) {
                    var self = this;
    
                    self.Save = function (employee) {
                        var deferred = $q.defer();                
                        $http
                            .post("/api/EmployeeApi/Create", angular.toJson(employee))
                            .success(function (response, status, headers, config) {
                                deferred.resolve(response, status, headers, config);
                            })
                            .error(function (response, status, headers, config) {
                                deferred.reject(response, status, headers, config);
                            });
    
                        return deferred.promise;
                    };
    

    How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

    Assuming you've used home-brew to install and upgrade Postgres, you can perform the following steps.

    1. Stop current Postgres server:

      launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

    2. Initialize a new 10.1 database:

      initdb /usr/local/var/postgres10.1 -E utf8

    3. run pg_upgrade (note: change bin version if you're upgrading from something other than below):

      pg_upgrade -v \
          -d /usr/local/var/postgres \
          -D /usr/local/var/postgres10.1 \
          -b /usr/local/Cellar/postgresql/9.6.5/bin/ \
          -B /usr/local/Cellar/postgresql/10.1/bin/
      

      -v to enable verbose internal logging

      -d the old database cluster configuration directory

      -D the new database cluster configuration directory

      -b the old PostgreSQL executable directory

      -B the new PostgreSQL executable directory

    4. Move new data into place:

      cd /usr/local/var
      mv postgres postgres9.6
      mv postgres10.1 postgres
      
    5. Restart Postgres:

      launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

    6. Check /usr/local/var/postgres/server.log for details and to make sure the new server started properly.

    7. Finally, re-install the rails pg gem

      gem uninstall pg
      gem install pg
      

    I suggest you take some time to read the PostgreSQL documentation to understand exactly what you're doing in the above steps to minimize frustrations.

    Update Git branches from master

    You have two options:

    The first is a merge, but this creates an extra commit for the merge.

    Checkout each branch:

    git checkout b1
    

    Then merge:

    git merge origin/master
    

    Then push:

    git push origin b1
    

    Alternatively, you can do a rebase:

    git fetch
    git rebase origin/master
    

    What to do with branch after merge

    After the merge, it's safe to delete the branch:

    git branch -d branch1
    

    Additionally, git will warn you (and refuse to delete the branch) if it thinks you didn't fully merge it yet. If you forcefully delete a branch (with git branch -D) which is not completely merged yet, you have to do some tricks to get the unmerged commits back though (see below).

    There are some reasons to keep a branch around though. For example, if it's a feature branch, you may want to be able to do bugfixes on that feature still inside that branch.

    If you also want to delete the branch on a remote host, you can do:

    git push origin :branch1
    

    This will forcefully delete the branch on the remote (this will not affect already checked-out repositiories though and won't prevent anyone with push access to re-push/create it).


    git reflog shows the recently checked out revisions. Any branch you've had checked out in the recent repository history will also show up there. Aside from that, git fsck will be the tool of choice at any case of commit-loss in git.

    Check if inputs are empty using jQuery

    Great collection of answers, would like to add that you can also do this using the :placeholder-shown CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.

    _x000D_
    _x000D_
    if ($('input#cust-descrip').is(':placeholder-shown')) {_x000D_
      console.log('Empty');_x000D_
    }_x000D_
    _x000D_
    $('input#cust-descrip').on('blur', '', function(ev) {_x000D_
      if (!$('input#cust-descrip').is(':placeholder-shown')) {_x000D_
        console.log('Has Text!');_x000D_
      }_x000D_
      else {_x000D_
        console.log('Empty!');_x000D_
      }_x000D_
    });
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    _x000D_
    <input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">
    _x000D_
    _x000D_
    _x000D_

    You can also make use of the :valid and :invalid selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.

    EXCEL VBA Check if entry is empty or not 'space'

    A common trick is to check like this:

    trim(TextBox1.Value & vbnullstring) = vbnullstring
    

    this will work for spaces, empty strings, and genuine null values

    What do I use on linux to make a python program executable

    Another way to do it could be by creating an alias. For example in terminal write:

    alias printhello='python /home/hello_world.py'
    

    Writing printhello will run hello_world.py, but this is only temporary. To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:

    gedit ~/.bashrc
    

    When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

    DFS is more space-efficient than BFS, but may go to unnecessary depths.

    Their names are revealing: if there's a big breadth (i.e. big branching factor), but very limited depth (e.g. limited number of "moves"), then DFS can be more preferrable to BFS.


    On IDDFS

    It should be mentioned that there's a less-known variant that combines the space efficiency of DFS, but (cummulatively) the level-order visitation of BFS, is the iterative deepening depth-first search. This algorithm revisits some nodes, but it only contributes a constant factor of asymptotic difference.

    Display only date and no time

    Include Data Annotations like DisplayFormat and ApplyFormatInEditMode to have the desired output.

    [Display(Name = "Bill Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime BillDate { get; set; }

    Now your Bill date will show like.

    enter image description here

    Recursively looping through an object to build a property list

    A simple path global variable across each recursive call does the trick for me !

    _x000D_
    _x000D_
    var object = {
      aProperty: {
        aSetting1: 1,
        aSetting2: 2,
        aSetting3: 3,
        aSetting4: 4,
        aSetting5: 5
      },
      bProperty: {
        bSetting1: {
          bPropertySubSetting: true
        },
        bSetting2: "bString"
      },
      cProperty: {
        cSetting: "cString"
      }
    }
    
    function iterate(obj, path = []) {
      for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
          if (typeof obj[property] == "object") {
            let curpath = [...path, property];
            iterate(obj[property], curpath);
          } else {
            console.log(path.join('.') + '.' + property + "   " + obj[property]);
            $('#output').append($("<div/>").text(path.join('.') + '.' + property))
          }
        }
      }
    }
    
    iterate(object);
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
    <div id='output'></div>
    _x000D_
    _x000D_
    _x000D_

    How do I reset a jquery-chosen select option with jQuery?

    If you are using chosen, a jquery plugin, then to refresh or clear the content of the dropdown use:

    $('#dropdown_id').empty().append($('< option>'))
    
    dropdown_id.chosen().trigger("chosen:updated")
    

    chosen:updated event will re-build itself based on the updated content.

    md-table - How to update the column width

    You can also use the element selectors:

    mat-header-cell:nth-child(1), mat-cell:nth-child(1) {
        flex: 0 0 64px;
    }
    

    But jymdman's answer is the most recommended way to go in most cases.

    Bash function to find newest file matching pattern

    You can use stat with a file glob and a decorate-sort-undecorate with the file time added on the front:

    $ stat -f "%m%t%N" b2* | sort -rn | head -1 | cut -f2-
    

    popup form using html/javascript/css

    Just replacing "Please enter your name" to your desired content would do the job. Am I missing something?

    Using multiprocessing.Process with a maximum number of simultaneous processes

    more generally, this could also look like this:

    import multiprocessing
    def chunks(l, n):
        for i in range(0, len(l), n):
            yield l[i:i + n]
    
    numberOfThreads = 4
    
    
    if __name__ == '__main__':
        jobs = []
        for i, param in enumerate(params):
            p = multiprocessing.Process(target=f, args=(i,param))
            jobs.append(p)
        for i in chunks(jobs,numberOfThreads):
            for j in i:
                j.start()
            for j in i:
                j.join()
    

    Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.

    Python ValueError: too many values to unpack

    for k, m in self.materials.items():
    

    example:

    miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
    for k, v in miles_dict.items():
        print("%s: %s" % (k, v))
    

    Current timestamp as filename in Java

    Date, SimpleDateFormat and whatever classes are required on the I/O side of things (there are many possibilities).

    javac error: Class names are only accepted if annotation processing is explicitly requested

    first download jdk from https://www.oracle.com/technetwork/java/javase/downloads/index.html. Then in search write Edit the System environment variables In open window i push bottom called Environment Variables Then in System variables enter image description here Push bottom new In field new variables write "Path" In field new value Write directory in folder bin in jdk like "C:\Program Files\Java\jdk1.8.0_191\bin" but in my OS work only this "C:\Program Files\Java\jdk1.8.0_191\bin\javac.exe" enter image description here press ok 3 times

    Start Cmd. I push bottom windows + R. Then write cmd. In cmd write "cd (your directory with code )" looks like C:\Users\user\IdeaProjects\app\src. Then write "javac (name of your main class for your program).java" looks like blabla.java and javac create byte code like (name of your main class).class in your directory. last write in cmd "java (name of your main class)" and my program start work

    ORA-28000: the account is locked error getting frequently

    I have faced this similar issue and resolved it by using following steps :

    1. Open windows command prompt.
    2. Login using the command sqlplus "/ as sysdba"
    3. Then executed the command alter user HR identified by password account unlock

      Please note, the password is the password that I have used.

      By using above steps you can connect to Oracle Database as user HR with the password password.

    How to use Switch in SQL Server

    This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.

    How to replace � in a string

    That's the Unicode Replacement Character, \uFFFD. (info)

    Something like this should work:

    String strImport = "For some reason my ?double quotes? were lost.";
    strImport = strImport.replaceAll("\uFFFD", "\"");
    

    How do I delete specific characters from a particular String in Java?

    You can use replaceAll() method :

    String.replaceAll(",", "");
    String.replaceAll("\\.", "");
    String.replaceAll("\\(", "");
    

    etc..

    how to change background image of button when clicked/focused?

    To change the button background we can follow 2 methods

    1. In the button OnClick, just add this code:

       public void onClick(View v) {
           if(v == buttonName) {
              buttonName.setBackgroundDrawable
               (getResources().getDrawable(R.drawable.imageName_selected));
            }
      
             }
      

      2.Create button_background.xml in the drawable folder.(using xml)

      res -> drawable -> button_background.xml

         <?xml version="1.0" encoding="UTF-8"?>
          <selector xmlns:android="http://schemas.android.com/apk/res/android">
      
               <item android:state_selected="true"
                     android:drawable="@drawable/tabs_selected" /> <!-- selected-->
               <item android:state_pressed="true"
                     android:drawable="@drawable/tabs_selected" /> <!-- pressed-->
               <item  android:drawable="@drawable/tabs_selected"/>
          </selector>
      

      Now set the above file in button's background file.

           <Button
                 android:layout_width="fill_parent" 
                 android:layout_height="wrap_content"
                 android:background="@drawable/button_background"/>
      
                                (or)
      
               Button tiny = (Button)findViewById(R.id.tiny);
                     tiny.setBackgroundResource(R.drawable.abc);
      

      2nd method is better for setting the background fd button

    How can I clear the content of a file?

    Try using something like

    File.Create

    Creates or overwrites a file in the specified path.

    make sounds (beep) with c++

    cout << "\a";
    

    In Xcode, After compiling, you have to run the executable by hand to hear the beep.

    What are OLTP and OLAP. What is the difference between them?

    The difference is quite simple:

    OLTP (Online Transaction Processing)

    OLTP is a class of information systems that facilitate and manage transaction-oriented applications. OLTP has also been used to refer to processing in which the system responds immediately to user requests. Online transaction processing applications are high throughput and insert or update-intensive in database management. Some examples of OLTP systems include order entry, retail sales, and financial transaction systems.

    OLAP (Online Analytical Processing)

    OLAP is part of the broader category of business intelligence, which also encompasses relational database, report writing and data mining. Typical applications of OLAP include business reporting for sales, marketing, management reporting, business process management (BPM), budgeting and forecasting, financial reporting and similar areas.

    See more details OLTP and OLAP

    How do I execute a bash script in Terminal?

    This is an old thread, but I happened across it and I'm surprised nobody has put up a complete answer yet. So here goes...

    The Executing a Command Line Script Tutorial!

    Q: How do I execute this in Terminal?

    Confusions and Conflicts:

    • You do not need an 'extension' (like .sh or .py or anything else), but it helps to keep track of things. It won't hurt. If the script name contains an extension, however, you must use it.
    • You do not need to be in any certain directory at all for any reason.
    • You do not need to type out the name of the program that runs the file (BASH or Python or whatever) unless you want to. It won't hurt.
    • You do not need sudo to do any of this. This command is reserved for running commands as another user or a 'root' (administrator) user. Great post here.

    (A person who is just learning how to execute scripts should not be using this command unless there is a real need, like installing a new program. A good place to put your scripts is in your ~/bin folder. You can get there by typing cd ~/bin or cd $HOME/bin from the terminal prompt. You will have full permissions in that folder.)

    To "execute this script" from the terminal on a Unix/Linux type system, you have to do three things:

    1. Tell the system the location of the script. (pick one)

      • Type the full path with the script name (e.g. /path/to/script.sh). You can verify the full path by typing pwd or echo $PWD in the terminal.
      • Execute from the same directory and use ./ for the path (e.g. ./script.sh). Easy.
      • Place the script in a directory that is on the system PATH and just type the name (e.g. script.sh). You can verify the system PATH by typing echo $PATH or echo -e ${PATH//:/\\n} if you want a neater list.
    2. Tell the system that the script has permission to execute. (pick one)

      • Set the "execute bit" by typing chmod +x /path/to/script.sh in the terminal.
      • You can also use chmod 755 /path/to/script.sh if you prefer numbers. There is a great discussion with a cool chart here.
    3. Tell the system the type of script. (pick one)

      • Type the name of the program before the script. (e.g. BASH /path/to/script.sh or PHP /path/to/script.php) If the script has an extension, such as .php or .py, it is part of the script name and you must include it.
      • Use a shebang, which I see you have (#!/bin/bash) in your example. If you have that as the first line of your script, the system will use that program to execute the script. No need for typing programs or using extensions.
      • Use a "portable" shebang. You can also have the system choose the version of the program that is first in the PATH by using #!/usr/bin/env followed by the program name (e.g. #!/usr/bin/env bash or #!/usr/bin/env python3). There are pros and cons as thoroughly discussed here.

    How to add manifest permission to an application?

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.photoeffect"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="com.example.towntour.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Black.NoTitleBar" >
        <activity
            android:name="com.photoeffect.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    </manifest>
    

    How to do this in Laravel, subquery where in

    The script is tested in Laravel 5.x and 6.x. The static closure can improve performance in some cases.

    Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
                ->whereIn('id', static function ($query) {
                    $query->select(['product_id'])
                        ->from((new ProductCategory)->getTable())
                        ->whereIn('category_id', [15, 223]);
                })
                ->where('active', 1)
                ->get();
    

    generates the SQL

    SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products` 
    WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE 
    `category_id` IN (?, ?)) AND `active` = ?
    

    Password Protect a SQLite DB. Is it possible?

    If you use FluentNHibernate you can use following configuration code:

    private ISessionFactory createSessionFactory()
    {
        return Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
                .ExposeConfiguration(this.buildSchema)
                .BuildSessionFactory();    
    }
    
    private void buildSchema(Configuration config)
    {
            if (filename_not_exists == true)
            {
                new SchemaExport(config).Create(false, true);
            }
    }    
    

    Method UsingFileWithPassword(filename, password) encrypts a database file and sets password.
    It runs only if the new database file is created. The old one not encrypted fails when is opened with this method.

    How to check that an element is in a std::set?

    You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

    For example: Suppose the set already has 20 as an element.

     std::set<int> myset;
     std::set<int>::iterator it;
     std::pair<std::set<int>::iterator,bool> ret;
    
     ret=myset.insert(20);
     if(ret.second==false)
     {
         //do nothing
    
     }
     else
     {
        //do something
     }
    
     it=ret.first //points to element 20 already in set.
    

    If the element is newly inserted than pair::first will point to the position of new element in set.

    Wildcard string comparison in Javascript

    You could use Javascript's substring method. For example:

    var list = ["bird1", "bird2", "pig1"]
    
    for (var i = 0; i < list.length; i++) {
      if (list[i].substring(0,4) == "bird") {
       console.log(list[i]);
      }
    }
    

    Which outputs:

    bird1
    bird2
    

    Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.


    So let's say your getting a pathname from a URL :

    Let's say your at bird1?=letsfly - you could use this code to check the URL:

    var listOfUrls = [
                      "bird1?=letsfly",
                      "bird",
                      "pigs?=dontfly",
                     ]
    
    for (var i = 0; i < list.length; i++) {
      if (listOfUrls[i].substring(0,4) === 'bird') {
        // do something
      }
    }
    

    The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4) with a regex, or even another javascript method like .contains()


    Using the .contains() method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:

    var url = 'www.example.com/bird?=fly'
    
    if (url.contains('bird')) {
      // this is true
      // do something
    }
    

    Get key and value of object in JavaScript?

    for (var i in a) {
       console.log(a[i],i)
    }
    

    Using JQuery to check if no radio button in a group has been checked

    I think this is a simple example, how to check if a radio in a group of radios was checked.

    if($('input[name=html_elements]:checked').length){
        //a radio button was checked
    }else{
        //there was no radio button checked
    } 
    

    jQuery Keypress Arrow Keys

    left = 37,up = 38, right = 39,down = 40
    
    $(document).keydown(function(e) {
    switch(e.which) {
        case 37:
        $( "#prev" ).click();
        break;
    
        case 38:
        $( "#prev" ).click();
        break;
    
        case 39:
        $( "#next" ).click();
        break;
    
        case 40:
        $( "#next" ).click();
        break;
    
        default: return;
    }
    e.preventDefault();
    

    });

    PHP memcached Fatal error: Class 'Memcache' not found

    There are two extensions for memcached in PHP, "memcache" and "memcached".

    It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").

    Organizing a multiple-file Go project

    I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main package, and the latter tend to put everything in a src directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.

    To get the best results I have worked out the following approach.

    myproj/
      main/
        mypack.go
      mypack.go
    

    Where mypack.go is package mypack and main/mypack.go is (obviously) package main.

    If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib subdirectory. E.g.

    myproj/
      main/
        mypack.go
      myextras/
        someextra.go
      mypack.go
      mysupport.go
    

    Or

    myproj.org/
      lib/
        mysupport.go
        myextras/
          someextra.go
      main/
        mypack.go
      mypage.go
    

    Only put the files in a lib directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib --to separate public from private interfaces.

    Doing things this way will give you a nice import path, myproj.org/mypack to reuse the code in other projects. If you use lib then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport.

    When building the project, use main/mypack, e.g. go build main/mypack. If you have more than one executable you can also separate those under main without having to create separate projects. e.g. main/myfoo/myfoo.go and main/mybar/mybar.go.

    How to configure slf4j-simple

    You can programatically change it by setting the system property:

    public class App {
    
        public static void main(String[] args) {
    
            System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
    
            final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
    
            log.trace("trace");
            log.debug("debug");
            log.info("info");
            log.warn("warning");
            log.error("error");
    
        }
    }
    

    The log levels are ERROR > WARN > INFO > DEBUG > TRACE.

    Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.

    Calculate distance between two latitude-longitude points? (Haversine formula)

    In the other answers an implementation in is missing.

    Calculating the distance between two point is quite straightforward with the distm function from the geosphere package:

    distm(p1, p2, fun = distHaversine)
    

    where:

    p1 = longitude/latitude for point(s)
    p2 = longitude/latitude for point(s)
    # type of distance calculation
    fun = distCosine / distHaversine / distVincentySphere / distVincentyEllipsoid 
    

    As the earth is not perfectly spherical, the Vincenty formula for ellipsoids is probably the best way to calculate distances. Thus in the geosphere package you use then:

    distm(p1, p2, fun = distVincentyEllipsoid)
    

    Off course you don't necessarily have to use geosphere package, you can also calculate the distance in base R with a function:

    hav.dist <- function(long1, lat1, long2, lat2) {
      R <- 6371
      diff.long <- (long2 - long1)
      diff.lat <- (lat2 - lat1)
      a <- sin(diff.lat/2)^2 + cos(lat1) * cos(lat2) * sin(diff.long/2)^2
      b <- 2 * asin(pmin(1, sqrt(a))) 
      d = R * b
      return(d)
    }
    

    How to use youtube-dl from a python program?

    Here is a way.

    We set-up options' string, in a list, just as we set-up command line arguments. In this case opts=['-g', 'videoID']. Then, invoke youtube_dl.main(opts). In this way, we write our custom .py module, import youtube_dl and then invoke the main() function.

    Logging best practices

    I'm not qualified to comment on logging for .Net, since my bread and butter is Java, but we've had a migration in our logging over the last 8 years you may find a useful analogy to your question.

    We started with a Singleton logger that was used by every thread within the JVM, and set the logging level for the entire process. This resulted in huge logs if we had to debug even a very specific part of the system, so lesson number one is to segment your logging.

    Our current incarnation of the logger allows multiple instances with one defined as the default. We can instantiate any number of child loggers that have different logging levels, but the most useful facet of this architecture is the ability to create loggers for individual packages and classes by simply changing the logging properties. Lesson number two is to create a flexible system that allows overriding its behavior without changing code.

    We are using the Apache commons-logging library wrapped around Log4J.

    Hope this helps!

    * Edit *

    After reading Jeffrey Hantin's post below, I realized that I should have noted what our internal logging wrapper has actually become. It's now essentially a factory and is strictly used to get a working logger using the correct properties file (which for legacy reasons hasn't been moved to the default position). Since you can specify the logging configuration file on command line now, I suspect it will become even leaner and if you're starting a new application, I'd definitely agree with his statement that you shouldn't even bother wrapping the logger.

    How to check if mod_rewrite is enabled in php?

    Use this function:

    function apache_module_exists($module)
    {
        return in_array($module, apache_get_modules());
    }
    

    Finding last occurrence of substring in string, replacing that

    To replace from the right:

    def replace_right(source, target, replacement, replacements=None):
        return replacement.join(source.rsplit(target, replacements))
    

    In use:

    >>> replace_right("asd.asd.asd.", ".", ". -", 1)
    'asd.asd.asd. -'
    

    How do I get a list of all the duplicate items using pandas in python?

    This may not be a solution to the question, but to illustrate examples:

    import pandas as pd
    
    df = pd.DataFrame({
        'A': [1,1,3,4],
        'B': [2,2,5,6],
        'C': [3,4,7,6],
    })
    
    print(df)
    df.duplicated(keep=False)
    df.duplicated(['A','B'], keep=False)
    

    The outputs:

       A  B  C
    0  1  2  3
    1  1  2  4
    2  3  5  7
    3  4  6  6
    
    0    False
    1    False
    2    False
    3    False
    dtype: bool
    
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    

    ng-options with simple array init

    If you setup your select like the following:

    <select ng-model="myselect" ng-options="b for b in options track by b"></select>
    

    you will get:

    <option value="var1">var1</option>
    <option value="var2">var2</option>
    <option value="var3">var3</option>
    

    working fiddle: http://jsfiddle.net/x8kCZ/15/

    Postgres "psql not recognized as an internal or external command"

    Enter this path in your System environment variable.

    C:\Program Files\PostgreSQL\[YOUR PG VERSION]\bin
    

    In this case i'm using version 10. If you check the postgres folder you are going to see your current versions.

    In my own case i used the following on separate lines:

    C:\Program Files\PostgreSQL\10\bin
    C:\Program Files\PostgreSQL\10\lib
    

    How to get correlation of two vectors in python

    The docs indicate that numpy.correlate is not what you are looking for:

    numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
      Cross-correlation of two 1-dimensional sequences.
      This function computes the correlation as generally defined in signal processing texts:
         z[k] = sum_n a[n] * conj(v[n+k])
      with a and v sequences being zero-padded where necessary and conj being the conjugate.
    

    Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

    from scipy.stats.stats import pearsonr   
    a = [1,4,6]
    b = [1,2,3]   
    print pearsonr(a,b)
    

    This gives

    (0.99339926779878274, 0.073186395040328034)
    

    You can also use numpy.corrcoef:

    import numpy
    print numpy.corrcoef(a,b)
    

    This gives:

    [[ 1.          0.99339927]
     [ 0.99339927  1.        ]]
    

    How to find the minimum value in an ArrayList, along with the index number? (Java)

    Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.

    ArrayList<Integer> a = new ArrayList<>();
    a.add(3);
    a.add(6);
    a.add(2);
    a.add(5);
    
    while (a.size() > 0) {
        int min = 1000;
        for (int b:a) {
            if (b < min)
                min = b;
        }
        System.out.println("minimum: " + min);
        System.out.println("index of min: " + a.indexOf((Integer) min));
        a.remove((Integer) min);
    }
    

    How to print bytes in hexadecimal using System.out.println?

    for (int j=0; j<test.length; j++) {
       System.out.format("%02X ", test[j]);
    }
    System.out.println();
    

    Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe

    Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.

    However, you can convert strings to numbers like this:

    pd.Series(['123', '42']).astype(float)
    

    instead of float(series)

    CSS3 animate border color

    You can use a CSS3 transition for this. Have a look at this example:

    http://jsfiddle.net/ujDkf/1/

    Here is the main code:

    #box {
      position : relative;
      width : 100px;
      height : 100px;
      background-color : gray;
      border : 5px solid black;
      -webkit-transition : border 500ms ease-out;
      -moz-transition : border 500ms ease-out;
      -o-transition : border 500ms ease-out;
      transition : border 500ms ease-out;
    }
    
    #box:hover {
       border : 10px solid red;   
    }
    

    Usage of __slots__?

    A very simple example of __slot__ attribute.

    Problem: Without __slots__

    If I don't have __slot__ attribute in my class, I can add new attributes to my objects.

    class Test:
        pass
    
    obj1=Test()
    obj2=Test()
    
    print(obj1.__dict__)  #--> {}
    obj1.x=12
    print(obj1.__dict__)  # --> {'x': 12}
    obj1.y=20
    print(obj1.__dict__)  # --> {'x': 12, 'y': 20}
    
    obj2.x=99
    print(obj2.__dict__)  # --> {'x': 99}
    

    If you look at example above, you can see that obj1 and obj2 have their own x and y attributes and python has also created a dict attribute for each object (obj1 and obj2).

    Suppose if my class Test has thousands of such objects? Creating an additional attribute dict for each object will cause lot of overhead (memory, computing power etc.) in my code.

    Solution: With __slots__

    Now in the following example my class Test contains __slots__ attribute. Now I can't add new attributes to my objects (except attribute x) and python doesn't create a dict attribute anymore. This eliminates overhead for each object, which can become significant if you have many objects.

    class Test:
        __slots__=("x")
    
    obj1=Test()
    obj2=Test()
    obj1.x=12
    print(obj1.x)  # --> 12
    obj2.x=99
    print(obj2.x)  # --> 99
    
    obj1.y=28
    print(obj1.y)  # --> AttributeError: 'Test' object has no attribute 'y'
    

    What is move semantics?

    My first answer was an extremely simplified introduction to move semantics, and many details were left out on purpose to keep it simple. However, there is a lot more to move semantics, and I thought it was time for a second answer to fill the gaps. The first answer is already quite old, and it did not feel right to simply replace it with a completely different text. I think it still serves well as a first introduction. But if you want to dig deeper, read on :)

    Stephan T. Lavavej took the time to provide valuable feedback. Thank you very much, Stephan!

    Introduction

    Move semantics allows an object, under certain conditions, to take ownership of some other object's external resources. This is important in two ways:

    1. Turning expensive copies into cheap moves. See my first answer for an example. Note that if an object does not manage at least one external resource (either directly, or indirectly through its member objects), move semantics will not offer any advantages over copy semantics. In that case, copying an object and moving an object means the exact same thing:

      class cannot_benefit_from_move_semantics
      {
          int a;        // moving an int means copying an int
          float b;      // moving a float means copying a float
          double c;     // moving a double means copying a double
          char d[64];   // moving a char array means copying a char array
      
          // ...
      };
      
    2. Implementing safe "move-only" types; that is, types for which copying does not make sense, but moving does. Examples include locks, file handles, and smart pointers with unique ownership semantics. Note: This answer discusses std::auto_ptr, a deprecated C++98 standard library template, which was replaced by std::unique_ptr in C++11. Intermediate C++ programmers are probably at least somewhat familiar with std::auto_ptr, and because of the "move semantics" it displays, it seems like a good starting point for discussing move semantics in C++11. YMMV.

    What is a move?

    The C++98 standard library offers a smart pointer with unique ownership semantics called std::auto_ptr<T>. In case you are unfamiliar with auto_ptr, its purpose is to guarantee that a dynamically allocated object is always released, even in the face of exceptions:

    {
        std::auto_ptr<Shape> a(new Triangle);
        // ...
        // arbitrary code, could throw exceptions
        // ...
    }   // <--- when a goes out of scope, the triangle is deleted automatically
    

    The unusual thing about auto_ptr is its "copying" behavior:

    auto_ptr<Shape> a(new Triangle);
    
          +---------------+
          | triangle data |
          +---------------+
            ^
            |
            |
            |
      +-----|---+
      |   +-|-+ |
    a | p | | | |
      |   +---+ |
      +---------+
    
    auto_ptr<Shape> b(a);
    
          +---------------+
          | triangle data |
          +---------------+
            ^
            |
            +----------------------+
                                   |
      +---------+            +-----|---+
      |   +---+ |            |   +-|-+ |
    a | p |   | |          b | p | | | |
      |   +---+ |            |   +---+ |
      +---------+            +---------+
    

    Note how the initialization of b with a does not copy the triangle, but instead transfers the ownership of the triangle from a to b. We also say "a is moved into b" or "the triangle is moved from a to b". This may sound confusing because the triangle itself always stays at the same place in memory.

    To move an object means to transfer ownership of some resource it manages to another object.

    The copy constructor of auto_ptr probably looks something like this (somewhat simplified):

    auto_ptr(auto_ptr& source)   // note the missing const
    {
        p = source.p;
        source.p = 0;   // now the source no longer owns the object
    }
    

    Dangerous and harmless moves

    The dangerous thing about auto_ptr is that what syntactically looks like a copy is actually a move. Trying to call a member function on a moved-from auto_ptr will invoke undefined behavior, so you have to be very careful not to use an auto_ptr after it has been moved from:

    auto_ptr<Shape> a(new Triangle);   // create triangle
    auto_ptr<Shape> b(a);              // move a into b
    double area = a->area();           // undefined behavior
    

    But auto_ptr is not always dangerous. Factory functions are a perfectly fine use case for auto_ptr:

    auto_ptr<Shape> make_triangle()
    {
        return auto_ptr<Shape>(new Triangle);
    }
    
    auto_ptr<Shape> c(make_triangle());      // move temporary into c
    double area = make_triangle()->area();   // perfectly safe
    

    Note how both examples follow the same syntactic pattern:

    auto_ptr<Shape> variable(expression);
    double area = expression->area();
    

    And yet, one of them invokes undefined behavior, whereas the other one does not. So what is the difference between the expressions a and make_triangle()? Aren't they both of the same type? Indeed they are, but they have different value categories.

    Value categories

    Obviously, there must be some profound difference between the expression a which denotes an auto_ptr variable, and the expression make_triangle() which denotes the call of a function that returns an auto_ptr by value, thus creating a fresh temporary auto_ptr object every time it is called. a is an example of an lvalue, whereas make_triangle() is an example of an rvalue.

    Moving from lvalues such as a is dangerous, because we could later try to call a member function via a, invoking undefined behavior. On the other hand, moving from rvalues such as make_triangle() is perfectly safe, because after the copy constructor has done its job, we cannot use the temporary again. There is no expression that denotes said temporary; if we simply write make_triangle() again, we get a different temporary. In fact, the moved-from temporary is already gone on the next line:

    auto_ptr<Shape> c(make_triangle());
                                      ^ the moved-from temporary dies right here
    

    Note that the letters l and r have a historic origin in the left-hand side and right-hand side of an assignment. This is no longer true in C++, because there are lvalues that cannot appear on the left-hand side of an assignment (like arrays or user-defined types without an assignment operator), and there are rvalues which can (all rvalues of class types with an assignment operator).

    An rvalue of class type is an expression whose evaluation creates a temporary object. Under normal circumstances, no other expression inside the same scope denotes the same temporary object.

    Rvalue references

    We now understand that moving from lvalues is potentially dangerous, but moving from rvalues is harmless. If C++ had language support to distinguish lvalue arguments from rvalue arguments, we could either completely forbid moving from lvalues, or at least make moving from lvalues explicit at call site, so that we no longer move by accident.

    C++11's answer to this problem is rvalue references. An rvalue reference is a new kind of reference that only binds to rvalues, and the syntax is X&&. The good old reference X& is now known as an lvalue reference. (Note that X&& is not a reference to a reference; there is no such thing in C++.)

    If we throw const into the mix, we already have four different kinds of references. What kinds of expressions of type X can they bind to?

                lvalue   const lvalue   rvalue   const rvalue
    ---------------------------------------------------------              
    X&          yes
    const X&    yes      yes            yes      yes
    X&&                                 yes
    const X&&                           yes      yes
    

    In practice, you can forget about const X&&. Being restricted to read from rvalues is not very useful.

    An rvalue reference X&& is a new kind of reference that only binds to rvalues.

    Implicit conversions

    Rvalue references went through several versions. Since version 2.1, an rvalue reference X&& also binds to all value categories of a different type Y, provided there is an implicit conversion from Y to X. In that case, a temporary of type X is created, and the rvalue reference is bound to that temporary:

    void some_function(std::string&& r);
    
    some_function("hello world");
    

    In the above example, "hello world" is an lvalue of type const char[12]. Since there is an implicit conversion from const char[12] through const char* to std::string, a temporary of type std::string is created, and r is bound to that temporary. This is one of the cases where the distinction between rvalues (expressions) and temporaries (objects) is a bit blurry.

    Move constructors

    A useful example of a function with an X&& parameter is the move constructor X::X(X&& source). Its purpose is to transfer ownership of the managed resource from the source into the current object.

    In C++11, std::auto_ptr<T> has been replaced by std::unique_ptr<T> which takes advantage of rvalue references. I will develop and discuss a simplified version of unique_ptr. First, we encapsulate a raw pointer and overload the operators -> and *, so our class feels like a pointer:

    template<typename T>
    class unique_ptr
    {
        T* ptr;
    
    public:
    
        T* operator->() const
        {
            return ptr;
        }
    
        T& operator*() const
        {
            return *ptr;
        }
    

    The constructor takes ownership of the object, and the destructor deletes it:

        explicit unique_ptr(T* p = nullptr)
        {
            ptr = p;
        }
    
        ~unique_ptr()
        {
            delete ptr;
        }
    

    Now comes the interesting part, the move constructor:

        unique_ptr(unique_ptr&& source)   // note the rvalue reference
        {
            ptr = source.ptr;
            source.ptr = nullptr;
        }
    

    This move constructor does exactly what the auto_ptr copy constructor did, but it can only be supplied with rvalues:

    unique_ptr<Shape> a(new Triangle);
    unique_ptr<Shape> b(a);                 // error
    unique_ptr<Shape> c(make_triangle());   // okay
    

    The second line fails to compile, because a is an lvalue, but the parameter unique_ptr&& source can only be bound to rvalues. This is exactly what we wanted; dangerous moves should never be implicit. The third line compiles just fine, because make_triangle() is an rvalue. The move constructor will transfer ownership from the temporary to c. Again, this is exactly what we wanted.

    The move constructor transfers ownership of a managed resource into the current object.

    Move assignment operators

    The last missing piece is the move assignment operator. Its job is to release the old resource and acquire the new resource from its argument:

        unique_ptr& operator=(unique_ptr&& source)   // note the rvalue reference
        {
            if (this != &source)    // beware of self-assignment
            {
                delete ptr;         // release the old resource
    
                ptr = source.ptr;   // acquire the new resource
                source.ptr = nullptr;
            }
            return *this;
        }
    };
    

    Note how this implementation of the move assignment operator duplicates logic of both the destructor and the move constructor. Are you familiar with the copy-and-swap idiom? It can also be applied to move semantics as the move-and-swap idiom:

        unique_ptr& operator=(unique_ptr source)   // note the missing reference
        {
            std::swap(ptr, source.ptr);
            return *this;
        }
    };
    

    Now that source is a variable of type unique_ptr, it will be initialized by the move constructor; that is, the argument will be moved into the parameter. The argument is still required to be an rvalue, because the move constructor itself has an rvalue reference parameter. When control flow reaches the closing brace of operator=, source goes out of scope, releasing the old resource automatically.

    The move assignment operator transfers ownership of a managed resource into the current object, releasing the old resource. The move-and-swap idiom simplifies the implementation.

    Moving from lvalues

    Sometimes, we want to move from lvalues. That is, sometimes we want the compiler to treat an lvalue as if it were an rvalue, so it can invoke the move constructor, even though it could be potentially unsafe. For this purpose, C++11 offers a standard library function template called std::move inside the header <utility>. This name is a bit unfortunate, because std::move simply casts an lvalue to an rvalue; it does not move anything by itself. It merely enables moving. Maybe it should have been named std::cast_to_rvalue or std::enable_move, but we are stuck with the name by now.

    Here is how you explicitly move from an lvalue:

    unique_ptr<Shape> a(new Triangle);
    unique_ptr<Shape> b(a);              // still an error
    unique_ptr<Shape> c(std::move(a));   // okay
    

    Note that after the third line, a no longer owns a triangle. That's okay, because by explicitly writing std::move(a), we made our intentions clear: "Dear constructor, do whatever you want with a in order to initialize c; I don't care about a anymore. Feel free to have your way with a."

    std::move(some_lvalue) casts an lvalue to an rvalue, thus enabling a subsequent move.

    Xvalues

    Note that even though std::move(a) is an rvalue, its evaluation does not create a temporary object. This conundrum forced the committee to introduce a third value category. Something that can be bound to an rvalue reference, even though it is not an rvalue in the traditional sense, is called an xvalue (eXpiring value). The traditional rvalues were renamed to prvalues (Pure rvalues).

    Both prvalues and xvalues are rvalues. Xvalues and lvalues are both glvalues (Generalized lvalues). The relationships are easier to grasp with a diagram:

            expressions
              /     \
             /       \
            /         \
        glvalues   rvalues
          /  \       /  \
         /    \     /    \
        /      \   /      \
    lvalues   xvalues   prvalues
    

    Note that only xvalues are really new; the rest is just due to renaming and grouping.

    C++98 rvalues are known as prvalues in C++11. Mentally replace all occurrences of "rvalue" in the preceding paragraphs with "prvalue".

    Moving out of functions

    So far, we have seen movement into local variables, and into function parameters. But moving is also possible in the opposite direction. If a function returns by value, some object at call site (probably a local variable or a temporary, but could be any kind of object) is initialized with the expression after the return statement as an argument to the move constructor:

    unique_ptr<Shape> make_triangle()
    {
        return unique_ptr<Shape>(new Triangle);
    }          \-----------------------------/
                      |
                      | temporary is moved into c
                      |
                      v
    unique_ptr<Shape> c(make_triangle());
    

    Perhaps surprisingly, automatic objects (local variables that are not declared as static) can also be implicitly moved out of functions:

    unique_ptr<Shape> make_square()
    {
        unique_ptr<Shape> result(new Square);
        return result;   // note the missing std::move
    }
    

    How come the move constructor accepts the lvalue result as an argument? The scope of result is about to end, and it will be destroyed during stack unwinding. Nobody could possibly complain afterward that result had changed somehow; when control flow is back at the caller, result does not exist anymore! For that reason, C++11 has a special rule that allows returning automatic objects from functions without having to write std::move. In fact, you should never use std::move to move automatic objects out of functions, as this inhibits the "named return value optimization" (NRVO).

    Never use std::move to move automatic objects out of functions.

    Note that in both factory functions, the return type is a value, not an rvalue reference. Rvalue references are still references, and as always, you should never return a reference to an automatic object; the caller would end up with a dangling reference if you tricked the compiler into accepting your code, like this:

    unique_ptr<Shape>&& flawed_attempt()   // DO NOT DO THIS!
    {
        unique_ptr<Shape> very_bad_idea(new Square);
        return std::move(very_bad_idea);   // WRONG!
    }
    

    Never return automatic objects by rvalue reference. Moving is exclusively performed by the move constructor, not by std::move, and not by merely binding an rvalue to an rvalue reference.

    Moving into members

    Sooner or later, you are going to write code like this:

    class Foo
    {
        unique_ptr<Shape> member;
    
    public:
    
        Foo(unique_ptr<Shape>&& parameter)
        : member(parameter)   // error
        {}
    };
    

    Basically, the compiler will complain that parameter is an lvalue. If you look at its type, you see an rvalue reference, but an rvalue reference simply means "a reference that is bound to an rvalue"; it does not mean that the reference itself is an rvalue! Indeed, parameter is just an ordinary variable with a name. You can use parameter as often as you like inside the body of the constructor, and it always denotes the same object. Implicitly moving from it would be dangerous, hence the language forbids it.

    A named rvalue reference is an lvalue, just like any other variable.

    The solution is to manually enable the move:

    class Foo
    {
        unique_ptr<Shape> member;
    
    public:
    
        Foo(unique_ptr<Shape>&& parameter)
        : member(std::move(parameter))   // note the std::move
        {}
    };
    

    You could argue that parameter is not used anymore after the initialization of member. Why is there no special rule to silently insert std::move just as with return values? Probably because it would be too much burden on the compiler implementors. For example, what if the constructor body was in another translation unit? By contrast, the return value rule simply has to check the symbol tables to determine whether or not the identifier after the return keyword denotes an automatic object.

    You can also pass the parameter by value. For move-only types like unique_ptr, it seems there is no established idiom yet. Personally, I prefer to pass by value, as it causes less clutter in the interface.

    Special member functions

    C++98 implicitly declares three special member functions on demand, that is, when they are needed somewhere: the copy constructor, the copy assignment operator, and the destructor.

    X::X(const X&);              // copy constructor
    X& X::operator=(const X&);   // copy assignment operator
    X::~X();                     // destructor
    

    Rvalue references went through several versions. Since version 3.0, C++11 declares two additional special member functions on demand: the move constructor and the move assignment operator. Note that neither VC10 nor VC11 conforms to version 3.0 yet, so you will have to implement them yourself.

    X::X(X&&);                   // move constructor
    X& X::operator=(X&&);        // move assignment operator
    

    These two new special member functions are only implicitly declared if none of the special member functions are declared manually. Also, if you declare your own move constructor or move assignment operator, neither the copy constructor nor the copy assignment operator will be declared implicitly.

    What do these rules mean in practice?

    If you write a class without unmanaged resources, there is no need to declare any of the five special member functions yourself, and you will get correct copy semantics and move semantics for free. Otherwise, you will have to implement the special member functions yourself. Of course, if your class does not benefit from move semantics, there is no need to implement the special move operations.

    Note that the copy assignment operator and the move assignment operator can be fused into a single, unified assignment operator, taking its argument by value:

    X& X::operator=(X source)    // unified assignment operator
    {
        swap(source);            // see my first answer for an explanation
        return *this;
    }
    

    This way, the number of special member functions to implement drops from five to four. There is a tradeoff between exception-safety and efficiency here, but I am not an expert on this issue.

    Forwarding references (previously known as Universal references)

    Consider the following function template:

    template<typename T>
    void foo(T&&);
    

    You might expect T&& to only bind to rvalues, because at first glance, it looks like an rvalue reference. As it turns out though, T&& also binds to lvalues:

    foo(make_triangle());   // T is unique_ptr<Shape>, T&& is unique_ptr<Shape>&&
    unique_ptr<Shape> a(new Triangle);
    foo(a);                 // T is unique_ptr<Shape>&, T&& is unique_ptr<Shape>&
    

    If the argument is an rvalue of type X, T is deduced to be X, hence T&& means X&&. This is what anyone would expect. But if the argument is an lvalue of type X, due to a special rule, T is deduced to be X&, hence T&& would mean something like X& &&. But since C++ still has no notion of references to references, the type X& && is collapsed into X&. This may sound confusing and useless at first, but reference collapsing is essential for perfect forwarding (which will not be discussed here).

    T&& is not an rvalue reference, but a forwarding reference. It also binds to lvalues, in which case T and T&& are both lvalue references.

    If you want to constrain a function template to rvalues, you can combine SFINAE with type traits:

    #include <type_traits>
    
    template<typename T>
    typename std::enable_if<std::is_rvalue_reference<T&&>::value, void>::type
    foo(T&&);
    

    Implementation of move

    Now that you understand reference collapsing, here is how std::move is implemented:

    template<typename T>
    typename std::remove_reference<T>::type&&
    move(T&& t)
    {
        return static_cast<typename std::remove_reference<T>::type&&>(t);
    }
    

    As you can see, move accepts any kind of parameter thanks to the forwarding reference T&&, and it returns an rvalue reference. The std::remove_reference<T>::type meta-function call is necessary because otherwise, for lvalues of type X, the return type would be X& &&, which would collapse into X&. Since t is always an lvalue (remember that a named rvalue reference is an lvalue), but we want to bind t to an rvalue reference, we have to explicitly cast t to the correct return type. The call of a function that returns an rvalue reference is itself an xvalue. Now you know where xvalues come from ;)

    The call of a function that returns an rvalue reference, such as std::move, is an xvalue.

    Note that returning by rvalue reference is fine in this example, because t does not denote an automatic object, but instead an object that was passed in by the caller.

    How can I get a process handle by its name in C++?

    If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

    How can I find which tables reference a given table in Oracle SQL Developer?

    To add this to SQL Developer as an extension do the following:

    1. Save the below code into an xml file (e.g. fk_ref.xml):
    <items>
        <item type="editor" node="TableNode" vertical="true">
        <title><![CDATA[FK References]]></title>
        <query>
            <sql>
                <![CDATA[select a.owner,
                                a.table_name,
                                a.constraint_name,
                                a.status
                         from   all_constraints a
                         where  a.constraint_type = 'R'
                                and exists(
                                   select 1
                                   from   all_constraints
                                   where  constraint_name=a.r_constraint_name
                                          and constraint_type in ('P', 'U')
                                          and table_name = :OBJECT_NAME
                                          and owner = :OBJECT_OWNER)
                                   order by table_name, constraint_name]]>
            </sql>
        </query>
        </item>
    </items>
    
    1. Add the extension to SQL Developer:

      • Tools > Preferences
      • Database > User Defined Extensions
      • Click "Add Row" button
      • In Type choose "EDITOR", Location is where you saved the xml file above
      • Click "Ok" then restart SQL Developer
    2. Navigate to any table and you should now see an additional tab next to SQL one, labelled FK References, which displays the new FK information.

    3. Reference

    ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

    I had the same problem using PHP and prepared statements on a VARCHAR2 column. My string didn't exceeed the VARCHAR2 size. The problem was that I used -1 as maxlength for binding, but the variable content changed later.

    In example:

    $sMyVariable = '';
    $rParsedQuery = oci_parse($rLink, 'INSERT INTO MyTable (MyVarChar2Column) VALUES (:MYPLACEHOLDER)');
    oci_bind_by_name($rParsedQuery, ':MYPLACEHOLDER', $sMyVariable, -1, SQLT_CHR);
    
    $sMyVariable = 'a';
    oci_execute($rParsedQuery, OCI_DEFAULT);
    $sMyVariable = 'b';
    oci_execute($rParsedQuery, OCI_DEFAULT);
    

    If you replace the -1 with the max column width (i. e. 254) then this code works. With -1 oci_bind_by_param uses the current length of the variable content (in my case 0) as maximum length for this column. This results in ORA-01461 when executing.

    Semaphore vs. Monitors - what's the difference?

    Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.

    The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.

    A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.

    Link: here for further reading. Hope it helps.