Programs & Examples On #Slk

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

ReactJS call parent method

Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

 const handleParentFun = (value) =>{
   console.log("Call to Parent Component!",value);
 return (<>
           This is Parent Component
               console.log("your value -->",value);

Child Component

import React from "react";

export default function ChildComponent(props){
         <> This is Child Component 
          <button onClick={props.handleParentFun("YoureValue")}>
            Call to Parent Component Function

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

Occurrences of substring in a string

A shorter version. ;)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
    $this->testvar = $new_value;

React-router: How to manually invoke Link?

React Router v5 - React 16.8+ with Hooks (updated 09/23/2020)

If you're leveraging React Hooks, you can take advantage of the useHistory API that comes from React Router v5.

import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';

export default function StackOverflowExample() {
  const history = useHistory();
  const handleOnClick = useCallback(() => history.push('/sample'), [history]);

  return (
    <button type="button" onClick={handleOnClick}>
      Go home

Another way to write the click handler if you don't want to use useCallback

const handleOnClick = () => history.push('/sample');

React Router v4 - Redirect Component

The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).

import { Redirect } from 'react-router';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />;

  return <button onClick={this.handleOnClick} type="button">Button</button>;


React Router v4 - Reference Router Context

You can also take advantage of Router's context that's exposed to the React component.

static contextTypes = {
  router: PropTypes.shape({
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
      replace: PropTypes.func.isRequired
    staticContext: PropTypes.object

handleOnClick = () => {

This is how <Redirect /> works under the hood.


React Router v4 - Externally Mutate History Object

If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter then expose the history as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.

// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';

export const history = createHistory();

export default class BrowserRouter extends Component {
  render() {
    return <Router history={history} children={this.props.children} />

// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';


// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';


Latest BrowserRouter to extend:

React Router v2

Push a new state to the browserHistory instance:

import {browserHistory} from 'react-router';
// ...


phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Linux / Ubuntu: If installed phpmyadmin via apt: sudo apt-get install phpmyadmin php-mbstring

Can check /etc/phpmyadmin/config-db.php for changing the user credentials.


Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you're importing a third-party module 'foo' that doesn't provide any typings, either in the library itself, or in the @types/foo package (generated from the DefinitelyTyped repository), then you can make this error go away by declaring the module in a file with a .d.ts extension. TypeScript looks for .d.ts files in the same places that it will look for normal .ts files: as specified under "files", "include", and "exclude" in the tsconfig.json.

// foo.d.ts
declare module 'foo';

Then when you import foo it'll just be typed as any.

Alternatively, if you want to roll your own typings you can do that too:

// foo.d.ts
declare module 'foo' {
    export function getRandomNumber(): number

Then this will compile correctly:

import { getRandomNumber } from 'foo';
const x = getRandomNumber(); // x is inferred as number

You don't have to provide full typings for the module, just enough for the bits that you're actually using (and want proper typings for), so it's particularly easy to do if you're using a fairly small amount of API.

On the other hand, if you don't care about the typings of external libraries and want all libraries without typings to be imported as any, you can add this to a file with a .d.ts extension:

declare module '*';

The benefit (and downside) of this is that you can import absolutely anything and TS will compile.

SQL Client for Mac OS X that works with MS SQL Server

Let's work together on a canonical answer.

Native Apps



(TODO: Add others mentioned below)

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

Nginx not picking up site in sites-enabled?

I had the same problem. It was because I had accidentally used a relative path with the symbolic link.

Are you sure you used full paths, e.g.:

ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

MySQL Trigger - Storing a SELECT in a variable

I'm posting this solution because I had a hard time finding what I needed. This post got me close enough (+1 for that thank you), and here is the final solution for rearranging column data before insert if the data matches a test.

Note: this is from a legacy project I inherited where:

  1. The Unique Key is a composite of rridprefix + rrid
  2. Before I took over there was no constraint preventing duplicate unique keys
  3. We needed to combine two tables (one full of duplicates) into the main table which now has the constraint on the composite key (so merging fails because the gaining table won't allow the duplicates from the unclean table)
  4. on duplicate key is less than ideal because the columns are too numerous and may change

Anyway, here is the trigger that puts any duplicate keys into a legacy column while allowing us to store the legacy, bad data (and not trigger the gaining tables composite, unique key).

  -- prevent duplicate composite keys when merging in archive to main
  SET @EXIST_COMPOSITE_KEY = (SELECT count(*) FROM patientrecords where rridprefix = NEW.rridprefix and rrid = NEW.rrid);

  -- if the composite key to be introduced during merge exists, rearrange the data for insert

    -- set the incoming column data this way (if composite key exists)

    -- the legacy duplicate rrid field will help us keep the bad data
    SET NEW.legacyduperrid = NEW.rrid;

    -- allow the following block to set the new rrid appropriately
    SET NEW.rrid = null;


  -- legacy code tried set the rrid (race condition), now the db does it
  SET NEW.rrid = (
    SELECT if(NEW.rrid is null and NEW.legacyduperrid is null, IFNULL(MAX(rrid), 0) + 1, NEW.rrid)
    FROM patientrecords
    WHERE rridprefix  = NEW.rridprefix

How can I tell if a Java integer is null?

There is no exists for a SCALAR in Perl, anyway. The Perl way is

defined( $x ) 

and the equivalent Java is

anInteger != null

Those are the equivalents.

exists $hash{key}

Is like the Java

map.containsKey( "key" )

From your example, I think you're looking for

if ( startIn != null ) { ...

Android WebView not loading an HTTPS URL

Use this line webview.getSettings().setDomStorageEnabled(true) in your java code

WebView webView = (WebView) findViewById(;    
WebSettings webSettings = webView.getSettings();

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:


You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:


Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(;     imageView.setImageBitmap(bitmap);  } 

'gulp' is not recognized as an internal or external command

If you have mysql install in your windows 10 try uninstall every myqsl app from your computer. Its work for me. exactly when i installed the mysql in my computer gulp command and some other commands stop working and then i have tried everything but not nothing worked for me.

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

Ascending and Descending Number Order in java

Three possible solutions come to my mind:

1. Reverse the order:

//convert the arr to list first
System.out.print("Numbers in Descending Order: " + listWithNumbers);

2. Iterate backwards and print it:

System.out.print("Numbers in Descending Order: " );
for(int i = arr.length - 1; i >= 0; i--){
  System.out.print( " " +arr[i]);

3. Sort it with "oposite" comparator:

Arrays.sort(arr, new Comparator<Integer>(){
   int compare(Integer i1, Integer i2) {
      return i2 - i1;
// or Collections.reverseOrder(), could be used instead
System.out.print("Numbers in Descending Order: " );
for(int i = 0; i < arr.length; i++){
  System.out.print( " " +arr[i]);

T-SQL: Opposite to string concatenation - how to split string into multiple records

I use this function (SQL Server 2005 and above).

create function [dbo].[Split]
    @string nvarchar(4000),
    @delimiter nvarchar(10)
returns @table table
    [Value] nvarchar(4000)
    declare @nextString nvarchar(4000)
    declare @pos int, @nextPos int

    set @nextString = ''
    set @string = @string + @delimiter

    set @pos = charindex(@delimiter, @string)
    set @nextPos = 1
    while (@pos <> 0)
        set @nextString = substring(@string, 1, @pos - 1)

        insert into @table

        set @string = substring(@string, @pos + len(@delimiter), len(@string))
        set @nextPos = @pos
        set @pos = charindex(@delimiter, @string)

In C# check that filename is *possibly* valid (not that it exists)

Probably the bast way is to build a custom method mixing a combination of regex and small look up on your file system (to see the drives, for example)

How do I run a VBScript in 32-bit mode on a 64-bit machine?

   ' ***************
   ' *** 64bit check
   ' ***************
   ' check to see if we are on 64bit OS -> re-run this script with 32bit cscript
   Function RestartWithCScript32(extraargs)
   Dim strCMD, iCount
   strCMD = r32wShell.ExpandEnvironmentStrings("%SYSTEMROOT%") & "\SysWOW64\cscript.exe"
   If NOT r32fso.FileExists(strCMD) Then strCMD = "cscript.exe" ' This may not work if we can't find the SysWOW64 Version
   strCMD = strCMD & Chr(32) & Wscript.ScriptFullName & Chr(32)
   If Wscript.Arguments.Count > 0 Then
    For iCount = 0 To WScript.Arguments.Count - 1
     if Instr(Wscript.Arguments(iCount), " ") = 0 Then ' add unspaced args
      strCMD = strCMD & " " & Wscript.Arguments(iCount) & " "
      If Instr("/-\", Left(Wscript.Arguments(iCount), 1)) > 0 Then ' quote spaced args
       If InStr(WScript.Arguments(iCount),"=") > 0 Then
        strCMD = strCMD & " " & Left(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), "=") ) & """" & Mid(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), "=") + 1) & """ "
       ElseIf Instr(WScript.Arguments(iCount),":") > 0 Then
        strCMD = strCMD & " " & Left(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), ":") ) & """" & Mid(Wscript.Arguments(iCount), Instr(Wscript.Arguments(iCount), ":") + 1) & """ "
        strCMD = strCMD & " """ & Wscript.Arguments(iCount) & """ "
       End If
       strCMD = strCMD & " """ & Wscript.Arguments(iCount) & """ "
      End If
     End If
   End If
   r32wShell.Run strCMD & " " & extraargs, 0, False
   End Function

   Dim r32wShell, r32env1, r32env2, r32iCount
   Dim r32fso
   SET r32fso = CreateObject("Scripting.FileSystemObject")
   Set r32wShell = WScript.CreateObject("WScript.Shell")
   r32env1 = r32wShell.ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%")
   If r32env1 <> "x86" Then ' not running in x86 mode
    For r32iCount = 0 To WScript.Arguments.Count - 1
     r32env2 = r32env2 & WScript.Arguments(r32iCount) & VbCrLf
    If InStr(r32env2,"restart32") = 0 Then RestartWithCScript32 "restart32" Else MsgBox "Cannot find 32bit version of cscript.exe or unknown OS type " & r32env1
    Set r32wShell = Nothing
   End If
   Set r32wShell = Nothing
   Set r32fso = Nothing
   ' *******************
   ' *** END 64bit check
   ' *******************

Place the above code at the beginning of your script and the subsequent code will run in 32bit mode with access to the 32bit ODBC drivers. Source.

Determining Referer in PHP

We have only single option left after reading all the fake referrer problems: i.e. The page we desire to track as referrer should be kept in session, and as ajax called then checking in session if it has referrer page value and doing the action other wise no action.

While on the other hand as he request any different page then make the referrer session value to null.

Remember that session variable is set on desire page request only.

nvarchar(max) still being truncated

Use this PRINT BIG function to output everything:

IF OBJECT_ID('tempdb..#printBig') IS NOT NULL


   @text NVARCHAR(MAX)

--DECLARE @text NVARCHAR(MAX) = 'YourTextHere'
DECLARE @lineSep NVARCHAR(2) = CHAR(13) + CHAR(10)  -- Windows \r\n

DECLARE @off INT = 1
DECLARE @maxLen INT = 4000

WHILE @off < LEN(@text)

  SELECT @len =
      WHEN LEN(@text) - @off - 1 <= @maxLen THEN LEN(@text)
      ELSE @maxLen
             - CHARINDEX(REVERSE(@lineSep),  REVERSE(SUBSTRING(@text, @off, @maxLen)))
             - LEN(@lineSep)
             + 1
  PRINT SUBSTRING(@text, @off, @len)
  --PRINT '@off=' + CAST(@off AS VARCHAR) + ' @len=' + CAST(@len AS VARCHAR)
  SET @off += @len + LEN(@lineSep)



Why is nginx responding to any domain name?

To answer your question - nginx picks the first server if there's no match. See documentation:

If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one...

Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate <path to cert>
    ssl_certificate_key <path to key>
    return 404;

Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.

Missing Authentication Token while accessing API Gateway?

Looks like (as of April 2019) AWS API Gateway throws this exception for a variety of reasons - mostly when you are hitting an endpoint that API Gateway is not able to reach, either because it is not deployed, or also in cases where that particular HTTP method is not supported.

I wish the gateway sends more appropriate error codes like HTTP 405 Method not supported or HTTP 404 not found, instead of a generic HTTP 403 Forbidden.

How can I access Oracle from Python?

If you are using virtualenv, it is not as trivial to get the driver using the installer. What you can do then: install it as described by Devon. Then copy over cx_Oracle.pyd and the cx_Oracle-XXX.egg-info folder from Python\Lib\site-packages into the Lib\site-packages from your virtual env. Of course, also here, architecture and version are important.

Make scrollbars only visible when a Div is hovered over?

If you are only concern about showing/hiding, this code would work just fine:


However, it might modify some elements in your design, in case you are using width=100%, considering that when you hide the scrollbar, it creates a little bit of more room for your width.

scp (secure copy) to ec2 instance without password

scp -i ~/.ssh/key.pem ec2-user@ip:/home/ec2-user/file-to-copy.txt .

The file name shouldnt be between the pem file and the ec2-user string - that doesnt work. This also allows you to reserve the name of the copied file.

display:inline vs display:block

a block or inline-block can have a width (e.g. width: 400px) while inline element is not affected by width. inline element can span to the next line of text (example resize your browser window to see that) while block element can't.

 .inline {
      background: lemonchiffon;
      div {
        display: inline;
        border: 1px dashed darkgreen;

Private class declaration

Private outer class would be useless as nothing can access it.

See more details:

Java: Why can we define a top level class as private?

How to check if a "lateinit" variable has been initialized?

To check if a lateinit var were initialised or not use a .isInitialized on the reference to that property:

if (foo::bar.isInitialized) {

This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

R adding days to a date

Just use

 as.Date("2001-01-01") + 45

from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.

Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).

R> library(RcppBDT)
Loading required package: Rcpp
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
 and 42 methods, of which 31 are possibly relevant:
   addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear, 
   getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
   getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian, 
   getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
   getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize, 
   setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
   setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"

Bower: ENOGIT Git is not installed or not in the PATH

When you ran the git install, you probably didn't choose:

"Use Git from the Windows Command Prompts"

during the installation.

Re-run git install, and choose that option.

How to output to the console and file?

Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.

import traceback
import sys

# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
    def __init__(self, filename):
        self.file = open(filename, 'w')
        self.stdout = sys.stdout

    def __enter__(self):
        sys.stdout = self

    def __exit__(self, exc_type, exc_value, tb):
        sys.stdout = self.stdout
        if exc_type is not None:

    def write(self, data):

    def flush(self):

To use the context manager:

with Tee('test.txt'):
    raise Exception("Test")

How to make connection to Postgres via Node.js

Connection String

The connection string is a string of the form:


(where the parts in [...] can optionally be included or excluded)

Some examples of valid connection strings include:


If you've just started a database on your local machine, the connection string postgres://localhost will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost or postgres://postgres@localhost

If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test databases are only intended for testing though, so you will loose all your data if your computer restarts.

Connecting in node.js

You can connect to the database and issue queries using @databases/pg:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${}, ${beatle.height}, ${beatle.birthday});

    await db.query(sql`SELECT * FROM beatles;`)

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();

You can find a more complete guide to querying Postgres using node.js at

JavaScript pattern for multiple constructors

I believe there are two answers. One using 'pure' Javascript with IIFE function to hide its auxiliary construction functions. And the other using a NodeJS module to also hide its auxiliary construction functions.

I will show only the example with a NodeJS module.

Class Vector2d.js:


    Implement a class of type Vetor2d with three types of constructors.


// If a constructor function is successfully executed,
// must have its value changed to 'true'.let global_wasExecuted = false;  
global_wasExecuted = false;   

//Tests whether number_value is a numeric type
function isNumber(number_value) {
    let hasError = !(typeof number_value === 'number') || !isFinite(number_value);

    if (hasError === false){
        hasError = isNaN(number_value);

    return !hasError;

// Object with 'x' and 'y' properties associated with its values.
function vector(x,y){
    return {'x': x, 'y': y};

//constructor in case x and y are 'undefined'
function new_vector_zero(x, y){

    if (x === undefined && y === undefined){
        global_wasExecuted = true;
        return new vector(0,0);

//constructor in case x and y are numbers
function new_vector_numbers(x, y){

    let x_isNumber = isNumber(x);
    let y_isNumber = isNumber(y);

    if (x_isNumber && y_isNumber){
        global_wasExecuted = true;
        return new vector(x,y);

//constructor in case x is an object and y is any
//thing (he is ignored!)
function new_vector_object(x, y){

    let x_ehObject = typeof x === 'object';
    //ignore y type

    if (x_ehObject){

        //assigns the object only for clarity of code
        let x_object = x;

        //tests whether x_object has the properties 'x' and 'y'
        if ('x' in x_object && 'y' in x_object){

            global_wasExecuted = true;

            we only know that x_object has the properties 'x' and 'y',
            now we will test if the property values ??are valid,
            calling the class constructor again.            
            return new Vector2d(x_object.x, x_object.y);


//Function that returns an array of constructor functions
function constructors(){
    let c = [];

        Your imagination is the limit!
        Create as many construction functions as you want.    

    return c;

class Vector2d {

    constructor(x, y){

        //returns an array of constructor functions
        let my_constructors = constructors(); 

        global_wasExecuted = false;

        //variable for the return of the 'vector' function
        let new_vector;     

        //traverses the array executing its corresponding constructor function
        for (let index = 0; index < my_constructors.length; index++) {

            //execute a function added by the 'constructors' function
            new_vector = my_constructors[index](x,y);
            if (global_wasExecuted) {
                this.x = new_vector.x;
                this.y = new_vector.y;


        return `(x: ${this.x}, y: ${this.y})`;


//Only the 'Vector2d' class will be visible externally
module.exports = Vector2d;  

The useVector2d.js file uses the Vector2d.js module:

const Vector = require('./Vector2d');

let v1 = new Vector({x: 2, y: 3});
console.log(`v1 = ${v1.toString()}`);

let v2 = new Vector(1, 5.2);
console.log(`v2 = ${v2.toString()}`);

let v3 = new Vector();
console.log(`v3 = ${v3.toString()}`);

Terminal output:

v1 = (x: 2, y: 3)
v2 = (x: 1, y: 5.2)
v3 = (x: 0, y: 0)

With this we avoid dirty code (many if's and switch's spread throughout the code), difficult to maintain and test. Each building function knows which conditions to test. Increasing and / or decreasing your building functions is now simple.

casting int to char using C++ style casting

reinterpret_cast cannot be used for this conversion, the code will not compile. According to C++03 standard section 5.2.10-1:

Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.

This conversion is not listed in that section. Even this is invalid:

long l = reinterpret_cast<long>(i)

static_cast is the one which has to be used here. See this and this SO questions.

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/'
dstroot = '/home/myhome/new_folder'

assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Share data between AngularJS controllers

I've created a factory that controls shared scope between route path's pattern, so you can maintain the shared data just when users are navigating in the same route parent path.

.controller('CadastroController', ['$scope', 'RouteSharedScope',
    function($scope, routeSharedScope) {
      var customerScope = routeSharedScope.scopeFor('/Customer');
      //var indexScope = routeSharedScope.scopeFor('/');

So, if the user goes to another route path, for example '/Support', the shared data for path '/Customer' will be automatically destroyed. But, if instead of this the user goes to 'child' paths, like '/Customer/1' or '/Customer/list' the the scope won't be destroyed.

You can see an sample here:

Python how to plot graph sine wave

  • Setting the x-axis with np.arange(0, 1, 0.001) gives an array from 0 to 1 in 0.001 increments.
    • x = np.arange(0, 1, 0.001) returns an array of 1000 points from 0 to 1, and y = np.sin(2*np.pi*x) you will get the sin wave from 0 to 1 sampled 1000 times

I hope this will help:

import matplotlib.pyplot as plt
import numpy as np

Fs = 8000
f = 5
sample = 8000
x = np.arange(sample)
y = np.sin(2 * np.pi * f * x / Fs)
plt.plot(x, y)

enter image description here

P.S.: For comfortable work you can use The Jupyter Notebook.

socket.error: [Errno 48] Address already in use

By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

PHP fwrite new line

You append a newline to both the username and the password, i.e. the output would be something like


use fwrite($fh,$user." ".$password."\n"); instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv() to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';

...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

As I mentioned in this answer, if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

Note that HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

As others have noted, the two also differ when using IPv6:

$_SERVER['HTTP_HOST'] == '[::1]'
$_SERVER['SERVER_NAME'] == '::1'

How to round an average to 2 decimal places in PostgreSQL?

SELECT ROUND(SUM(amount)::numeric, 2) AS total_amount
FROM transactions

Gives: 200234.08

PHP JSON String, escape Double Quotes for JS output

I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));

I hope it helps someone/someone improves it.

GCD to perform task in main thread

As the other answers mentioned, dispatch_async from the main thread is fine.

However, depending on your use case, there is a side effect that you may consider a disadvantage: since the block is scheduled on a queue, it won't execute until control goes back to the run loop, which will have the effect of delaying your block's execution.

For example,

NSLog(@"before dispatch async");
dispatch_async(dispatch_get_main_queue(), ^{
    NSLog(@"inside dispatch async block main thread from main thread");
NSLog(@"after dispatch async");

Will print out:

before dispatch async
after dispatch async
inside dispatch async block main thread from main thread

For this reason, if you were expecting the block to execute in-between the outer NSLog's, dispatch_async would not help you.

How do I compare two strings in python?

Equality in direct comparing:

string1 = "sample"
string2 = "sample"

if string1 == string2 :
    print("Strings are equal with text : ", string1," & " ,string2)
else :
    print ("Strings are not equal")

Equality in character sets:

string1 = 'abc def ghi'
string2 = 'def ghi abc'

set1 = set(string1.split(' '))
set2 = set(string2.split(' '))

print set1 == set2

if string1 == string2 :
    print("Strings are equal with text : ", string1," & " ,string2)
else :
    print ("Strings are not equal")

How do I toggle an element's class in pure JavaScript?

don't need regex just use classlist

var id=document.getElementById('myButton');

function toggle(el,classname){




<button id="myButton">Switch</button>

Simple Usage above Example

var id=document.getElementById('myButton');

function toggle(el,classname){




<button id="myButton">Switch</button>

RequiredIf Conditional Validation Attribute

I had the same problem yesterday, but I did it in a very clean way which works for both client side and server side validation.

Condition: Based on the value of other property in the model, you want to make another property required. Here is the code:

public class RequiredIfAttribute : RequiredAttribute
  private String PropertyName { get; set; }
  private Object DesiredValue { get; set; }

  public RequiredIfAttribute(String propertyName, Object desiredvalue)
    PropertyName = propertyName;
    DesiredValue = desiredvalue;

  protected override ValidationResult IsValid(object value, ValidationContext context)
    Object instance = context.ObjectInstance;
    Type type = instance.GetType();
    Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
    if (proprtyvalue.ToString() == DesiredValue.ToString())
      ValidationResult result = base.IsValid(value, context);
      return result;
    return ValidationResult.Success;

PropertyName is the property on which you want to make your condition
DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required

Say you have the following:

public enum UserType

public class User
  public UserType UserType {get;set;}

              ErrorMessageResourceType = typeof(ResourceString))]
  public string Password { get; set; }

At last but not the least, register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)



Some people was complaining that the client side fires no matter what or it does not work. So I modified the above code to do conditional client side validation with Javascript as well. For this case you don't need to register adapter

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();

        protected override ValidationResult IsValid(object value, ValidationContext context)
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue.ToString() == DesiredValue.ToString())
                if (!_innerAttribute.IsValid(value))
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
            return ValidationResult.Success;

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            var rule = new ModelClientValidationRule
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;

And finally the javascript ( bundle it and renderit...put it in its own script file)

$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;

$.validator.addMethod('requiredif', function (value, element, parameters) {
    var desiredvalue = parameters.desiredvalue;
    desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
    var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
    var actualvalue = {}
    if (controlType == "checkbox" || controlType == "radio") {
        var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
        actualvalue = control.val();
    } else {
        actualvalue = $("#" + parameters.dependentproperty).val();
    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
        var isValid = $, value, element, parameters);
        return isValid;
    return true;

You need obviously the unobstrusive validate jQuery to be included as requirement

The performance impact of using instanceof in Java

instanceof is very efficient, so your performance is unlikely to suffer. However, using lots of instanceof suggests a design issue.

If you can use xClass == String.class, this is faster. Note: you don't need instanceof for final classes.

Function vs. Stored Procedure in SQL Server

  • Functions can be used in a select statement where as procedures cannot.

  • Stored procedure takes both input and output parameters but Functions takes only input parameters.

  • Functions cannot return values of type text, ntext, image & timestamps where as procedures can.

  • Functions can be used as user defined datatypes in create table but procedures cannot.

***Eg:-create table <tablename>(name varchar(10),salary getsal(name))

Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get’s executed and the return Type is returned as the result set.

Check if the number is integer

Here is one, apparently reliable way:

check.integer <- function(N){
    !grepl("[^[:digit:]]", format(N,  digits = 20, scientific = FALSE))


This solution also allows for integers in scientific notation:

> check.integer(222e3)
[1] TRUE

How to get default gateway in Mac OSX

Using System Preferences:

Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.

Step 2: Click Network.

Step 3: Select your network connection and then click Advanced.

Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.

Your content must have a ListView whose id attribute is ''

Inherit Activity Class instead of ListActivity you can resolve this problem.

public class ExampleActivity extends Activity  {

    public void onCreate(Bundle savedInstanceState) {



How to download a file from my server using SSH (using PuTTY on Windows)

You can use the WinSPC program. Its access to any server is pretty easy. The program gives its guide too. I hope it's helpfull.

jQuery if div contains this text, replace that part of the text

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));

Remove quotes from String in Python

There are several ways this can be accomplished.

  • You can make use of the builtin string function .replace() to replace all occurrences of quotes in a given string:

    >>> s = '"abcd" efgh'
    >>> s.replace('"', '')
    'abcd efgh'
  • You can use the string function .join() and a generator expression to remove all quotes from a given string:

    >>> s = '"abcd" efgh'
    >>> ''.join(c for c in s if c not in '"')
    'abcd efgh'
  • You can use a regular expression to remove all quotes from given string. This has the added advantage of letting you have control over when and where a quote should be deleted:

    >>> s = '"abcd" efgh'
    >>> import re
    >>> re.sub('"', '', s)
    'abcd efgh'

React.js: onChange event for contentEditable

Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.

Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.

I'd personally have this as my render function.

var handleChange = function(event){

return (<ContentEditable html={this.state.html} onChange={handleChange} />);


Which uses this simple wrapper around contentEditable.

var ContentEditable = React.createClass({
    render: function(){
        return <div 
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {

                target: {
                    value: html
        this.lastHtml = html;


This just happened to me in a string assignment using double quotes. I was missing a closing curly on a POST variable...

"for {$_POST['txtName'] on $date";

should have been

"for {$_POST['txtName']} on $date";

I can't explain why. I mean, I see the error that would break the code but I don't see why it references a class error.

How to get the sizes of the tables of a MySQL database?

select x.dbname as db_name, x.table_name as table_name, x.bytesize as the_size from
     table_schema as dbname,
     sum(index_length+data_length) as bytesize,
   group by table_schema
  ) x
  x.bytesize > 999999
order by x.bytesize desc;

What is the best way to dump entire objects to a log in C#?

I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:

  private string ObjectToXml(object output)
     string objectAsXmlString;

     System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
     using (System.IO.StringWriter sw = new System.IO.StringWriter())
           xs.Serialize(sw, output);
           objectAsXmlString = sw.ToString();
        catch (Exception ex)
           objectAsXmlString = ex.ToString();

     return objectAsXmlString;

You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.

How to execute a program or call a system command from Python

Update: is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)

Here's some examples from the documentation.

Run a process:

>>>["ls", "-l"])  # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

Raise on failed run:

>>>"exit 1", shell=True, check=True)
Traceback (most recent call last):
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

Capture output:

>>>["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

Original answer:

I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.

Example usage from the README:

>>> r ='git config', data='data to pipe in', timeout=2)

>>> r.status_code
>>> r.std_out
'usage: git config [options]'
>>> r.std_err

Pipe stuff around too:

>>> r ='uptime | pbcopy')

>>> r.command
>>> r.status_code

>>> r.history
[<Response 'uptime'>]

Eclipse IDE for Java - Full Dark Theme

If the purpose of a dark theme is to make your eyes comfortable, you can enable High Contrast settings of your Operating System. For example in Windows 8.1 you can turn on - off High Contrast by pressing ALT + left SHIFT + PRINT SCREEN

This will make entire OS in dark mode, not only eclipse. Below is a sample screenshot of Eclipse with High Contrast enabled

enter image description here

What is the best way to tell if a character is a letter or number in Java without using regexes?

Compare its value. It should be between the value of 'a' and 'z', 'A' and 'Z', '0' and '9'

possibly undefined macro: AC_MSG_ERROR

I had this problem with my own, but in this case (and for the benefit of anyone here from Google) it was because I had accidentally quoted the AC_MSG_ERROR so it was being treated as a string:

AX_BOOST_BASE([1.42], [], [AC_MSG_ERROR([Could not find Boost])])

Once I removed the square brackets around the AC_MSG_ERROR macro, it worked:

AX_BOOST_BASE([1.42], [], AC_MSG_ERROR([Could not find Boost]))

Those comments saying you should install pkg-config or some package are missing the point. The AC_MSG_ERROR is supposed to work and give you a helpful message like "You need to install package XYZ", but because of some problem, the AC_MSG_ERROR doesn't work. Installing package XYZ will certainly make the error go away, but only because once the package is there, there is no longer any need to print an error message!

So installing pkg-config or a particular package just bypasses the problem, it doesn't actually fix it.

Decode UTF-8 with Javascript

To answer the original question: here is how you decode utf-8 in javascript:


function encode_utf8(s) {
  return unescape(encodeURIComponent(s));

function decode_utf8(s) {
  return decodeURIComponent(escape(s));

We have been using this in our production code for 6 years, and it has worked flawlessly.

Note, however, that escape() and unescape() are deprecated. See this.

Expected corresponding JSX closing tag for input Reactjs

It happens when we do not close a html tag.

Make sure all the html tags are closed.

In my case it was the <br> tag. It should be <br />.

Try temporarily removing piece of code until you find which html tag closing is missing.

How to convert POJO to JSON and vice versa?

If you are aware of Jackson 2, there is a great tutorial at on how to convert Java Objects to JSON and vice versa. The following code snippets have been taken from that tutorial.

Convert Java object to JSON, writeValue(...):

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

//Object to JSON in file
mapper.writeValue(new File("c:\\file.json"), obj);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

Convert JSON to Java object, readValue(...):

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

//JSON from URL to Object
Staff obj = mapper.readValue(new URL(""), Staff.class);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Jackson 2 Dependency:


For the full tutorial, please go to the link given above.

How to check what version of jQuery is loaded?

if (typeof jQuery != 'undefined') {  
    // jQuery is loaded => print the version

Spring Boot War deployed to Tomcat

I think you're confused by different paradigms here. First, war files and server deployment -- those things belong to Java Enterprise Edition (Java EE). These concepts have no real place in a spring-boot application, which follows a different model.

Spring-boot is responsible for creating an embedded container and running your services within it directly from standard jar files (although it can do a lot more). I think the intent of this model is to support micro-service development -- where each service has its own container and is completely self contained. You can use your code to generate Java EE apps too, but that would be silly considering that spring-boot is a lot easier (for certain types of application/service).

So, given this information you now have to decide what paradigm you're going to follow, and you need to follow that and only that.

Spring-boot is executable -- you just have to run the main method in the App class which you can do from the command line or using your favourite IDE or maven or gradle (tip: maven is the right answer). This will bring up a tomcat server (by default) and your service will be available within it. Given the configuration you posted above your service should be available at: http://localhost:7777/context/help -- the context is meant to be replaced with your context name, which you haven't shared.

You aren't meant to be creating a war, running tomcat, or deploying anything. None of that is necessary in spring-boot. The packaging in your pom should be jar, not war and the scope of the spring-boot-starter-tomcat should be removed -- it certainly isn't provided.

When you run your main method, the console output should tell you the context that you've registered; use that to get the URL right.

Having said all that, spring-boot has to exist in a JEE world for now (until it is widely adopted). For that reason, the spring people have documented an approach to building a war rather than an executable jar, for deployment to a servlet or JEE container. This allows a lot of the spring-boot tech to be used in environments where there are restrictions against using anything but wars (or ears). However, this is a just a response to the fact that such environments are quite common, and is not seen as a necessary, or even desirable, part of the solution.

How to do INSERT into a table records extracted from another table

Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.

  1. Open both recordsets
  2. Extract the data from the first table (SELECT blablabla)
  3. Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
  4. Close both recordsets

This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)

Dynamically generating a QR code with PHP

qrcode-generator on Github. Simplest script and works like charm.


  • No third party dependency
  • No limitations for the number of QR code generations

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

Sleep function in ORACLE

Short of granting access to DBMS_LOCK.sleep, this will work but it's a horrible hack:

IN_TIME INT; --num seconds
v_now DATE;

-- 1) Get the date & time 
  INTO v_now

-- 2) Loop until the original timestamp plus the amount of seconds <= current date
  EXIT WHEN v_now + (IN_TIME * (1/86400)) <= SYSDATE;

How to bind Close command to a button

In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.

According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the CommandBinding. What this essentially does is say "When you hear this Message do this".

So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.

MainWindow.xaml.cs (Or other Code-Behind)

void CloseApp( object target, ExecutedRoutedEventArgs e ) {
    /*** Code to check for State before Closing ***/

void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
    /*** Logic to Determine if it is safe to Close the Window ***/
    e.CanExecute = true;

Now we need to setup the "Connection" between the SystemCommands.CloseWindowCommand and the CloseApp and CloseAppCanExecute

MainWindow.xaml (Or anything that implements CommandBindings)

    <CommandBinding Command="SystemCommands.CloseWindowCommand"

You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:

    <CommandBinding Command="SystemCommands.CloseWindowCommand"

Finally you need to tell the UIElement to send out the CloseWindowCommand.

<Button Command="SystemCommands.CloseWindowCommand">

Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".

This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:

protected override void OnClick(EventArgs e){
    /*** Function to Execute ***/

In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.

I hope this clears things up...

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/ so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/','text/plain','text/csv','text/tsv');
  // do something
} else {
  die("Sorry, mime type not allowed");

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

Merging arrays with the same keys

$arr1 = array(
   "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
   "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
   "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
   "3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
   "4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")

if you want to convert this array as following:

$arr2 = array(
   "0" => array(
          "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
          "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
          "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
          "3" => array("fid" => 1, "tid" => 7, "name" => "Xi")

    "1" => array(
          "0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")

so, my answer will be like this:

$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
    $inner_array = array();

    $fid_value = $value['fid'];
    if(!in_array($value['fid'], $unique_array))
            array_push($unique_array, $fid_value);
            array_push($inner_array, $value);
            $outer_array[$fid_value] = $inner_array;

            array_push($outer_array[$fid_value], $value);


hope this answer will help somebody sometime.

What is event bubbling and capturing?


  Event propagate to the upto root element is **BUBBLING**.


  Event propagate from body(root) element to eventTriggered Element is **CAPTURING**.

How to compile LEX/YACC files on Windows?

As for today (2011-04-05, updated 2017-11-29) you will need the lastest versions of:

  1. flex-2.5.4a-1.exe

  2. bison-2.4.1-setup.exe

  3. After that, do a full install in a directory of your preference without spaces in the name. I suggest C:\GnuWin32. Do not install it in the default (C:\Program Files (x86)\GnuWin32) because bison has problems with spaces in directory names, not to say parenthesis.

  4. Also, consider installing Dev-CPP in the default directory (C:\Dev-Cpp)

  5. After that, set the PATH variable to include the bin directories of gcc (in C:\Dev-Cpp\bin) and flex\bison (in C:\GnuWin32\bin). To do that, copy this: ;C:\Dev-Cpp\bin;C:\GnuWin32\bin and append it to the end of the PATH variable, defined in the place show by this figure:
    step-by-step to set PATH variable under Win-7.
    If the figure is not in good resolution, you can see a step-by-step here.

  6. Open a prompt, cd to the directory where your ".l" and ".y" are, and compile them with:

    1. flex hello.l
    2. bison -dy hello.y
    3. gcc lex.yy.c -o hello.exe

Commands to create lexical analyzer, parser and executable.

You will be able to run the program. I made the sources for a simple test (the infamous Hello World):



#include ""
int yyerror(char *errormsg);



("hi"|"oi")"\n"       { return HI;  }
("tchau"|"bye")"\n"   { return BYE; }
.                     { yyerror("Unknown char");  }


int main(void)
   return 0;

int yywrap(void)
   return 0;

int yyerror(char *errormsg)
    fprintf(stderr, "%s\n", errormsg);



#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);


%token HI BYE


         hi bye

        HI     { printf("Hello World\n");   }
        BYE    { printf("Bye World\n"); exit(0); }

Edited: avoiding "warning: implicit definition of yyerror and yylex".

Disclaimer: remember, this answer is very old (since 2011!) and if you run into problems due to versions and features changing, you might need more research, because I can't update this answer to reflect new itens. Thanks and I hope this will be a good entry point for you as it was for many.

Updates: if something (really small changes) needs to be done, please check out the official repository at github:

Happy hacking.

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
public static void readgson(String file) {
    try {
        System.out.println( "Reading JSON file from Java program" );

        FileReader fileReader = new FileReader( file ); object = (JsonObject) parser.parse( fileReader );

        Set <java.util.Map.Entry<String,>> keys = object.entrySet();
        if ( keys.isEmpty() ) {
            System.out.println( "Empty JSON Object" );
        }else {
            Map<String, Object> map = json_UnKnown_Format( keys );
            System.out.println("Json 2 Map : "+map);

    } catch (IOException ex) {
        System.out.println("Input File Does not Exists.");
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String,>> keys ){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    for (Entry<String, JsonElement> entry : keys) {
        String keyEntry = entry.getKey();
        System.out.println(keyEntry + " : ");
        JsonElement valuesEntry =  entry.getValue();
        if (valuesEntry.isJsonNull()) {
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonPrimitive()) {
            System.out.println("P - "+valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonArray()) {
            JsonArray array = valuesEntry.getAsJsonArray();
            List<Object> array2List = new ArrayList<Object>();
            for (JsonElement jsonElements : array) {
                System.out.println("A - "+jsonElements);
            jsonMap.put(keyEntry, array2List);
        }else if (valuesEntry.isJsonObject()) {             
    obj = (JsonObject) parser.parse(valuesEntry.toString());                    
             Set <java.util.Map.Entry<String,>> obj_key = obj.entrySet();
             jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
    return jsonMap;
public static void writeJson( String file ) {

    JSONObject json = new JSONObject();

    json.put("Key1", "Value");
    json.put("Key2", 777); // Converts to "777"
    json.put("Key3", null);
    json.put("Key4", false);

        JSONArray jsonArray = new JSONArray();

    json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Obj-Key1", 20);
        jsonObj.put("Obj-Key2", "Value2");
        jsonObj.put(4, "Value2"); // Converts to "4"

    json.put("InnerObject", jsonObj);

        JSONObject jsonObjArray = new JSONObject();
            JSONArray objArray = new JSONArray();
            objArray.put(0, "Obj-Array3");
        jsonObjArray.put("ObjectArray", objArray);

    json.put("InnerObjectArray", jsonObjArray);

        Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
        sortedTree.put("Sorted1", 10);
        sortedTree.put("Sorted2", 103);
        sortedTree.put("Sorted3", 14);

    json.put("TreeMap", sortedTree);        

    try {
        System.out.println("Writting JSON into file ...");
        FileWriter jsonFileWriter = new FileWriter(file);

    } catch (IOException e) { 


Bootstrap 3: Scroll bars

You need to use overflow option like below:

    max-height: 300px;
    overflow-y: scroll; 

Change the height according to amount of items you need to show

docker cannot start on windows

For me the issue was virtualization was not enabled.

On windows 10: Go to task manager -> Performance -> CPU and you should see as section as "Virtualization : Enabled"

If you do not see this option, it means that virtualization has not been enabled.

Another interesting thing to note is you must have Hyper V enabled. However as I was using parallels desktop, I had to enabled to "Nested Virtualization" for Hyper V to be "truly enabled". So if your windows is a VM, check out the settings for Parallels (or whatever you're using) that nested virtualization is enabled.

Python 3 ImportError: No module named 'ConfigParser'

I was getting the same error on Mac OS 10, Python 3.7.6 & Django 2.2.7. I want to use this opportunity to share what worked for me after trying out numerous solutions.


  1. Installed Connector/Python 8.0.20 for Mac OS from link

  2. Copy current dependencies into requirements.txt file, deactivated the current virtual env, and deleted it using;

    create the file if not already created with; touch requirements.txt

    copy dependency to file; python -m pip3 freeze > requirements.txt

    deactivate and delete current virtual env; deactivate && rm -rf <virtual-env-name>

  3. Created another virtual env and activated it using; python -m venv <virtual-env-name> && source <virtual-env-name>/bin/activate

  4. Install previous dependencies using; python -m pip3 install -r requirements.txt

Difference between ApiController and Controller in ASP.NET MVC

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.

How do I center text horizontally and vertically in a TextView?

Use this for relative layout


and for other layout


How to determine whether a given Linux is 32 bit or 64 bit?

If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a

To get your specific machine hardware name run

uname -m

You can also call

getconf LONG_BIT

which returns either 32 or 64

Calling a rest api with username and password - how to

Here is the solution for Rest API

class Program
    static void Main(string[] args)
        BaseClient clientbase = new BaseClient("", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;

    public async Task<BaseResponse> GetCallAsync(string endpoint)
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            return baseresponse;
        catch (Exception ex)
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        return baseresponse;

public class BaseResponse
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }

public class BaseClient
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
        HttpClientHandler handler = new HttpClientHandler()
            Proxy = new WebProxy(""),
            UseProxy = false,

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();


Implement a simple factory pattern with Spring 3 annotations

You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

public class MyServiceFactory {

    private MyServiceOne myServiceOne;

    private MyServiceTwo myServiceTwo;

    private MyServiceThree myServiceThree;

    private MyServiceDefault myServiceDefault;

    public static MyService getMyService(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne;
        } else if (service.equals("two")) {
            return myServiceTwo;
        } else if (service.equals("three")) {
            return myServiceThree;
        } else {
            return myServiceDefault;

But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

public class MyServiceAdapter implements MyService {

    private MyServiceOne myServiceOne;

    private MyServiceTwo myServiceTwo;

    private MyServiceThree myServiceThree;

    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();

This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

python 2 instead of python 3 as the (temporary) default python?

Use python command to launch scripts, not shell directly. E.g.

  python2 /usr/bin/command

AFAIK this is the recommended method to workaround scripts with bad env interpreter line.

LocalDate to java.util.Date and vice versa simplest conversion?

Date -> LocalDate:

LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate -> Date:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Nested routes with react router v4 / v5

I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.

    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />


Most efficient way to get table row count

Next to the information_schema suggestion, this:


should also be very fast, provided there's an index on the id field (which I believe must be the case with auto_increment)

sqldeveloper error message: Network adapter could not establish the connection error

I have had the same problem. I am using windows 7 and this should also work for windows 8. The services responsible for the TNS listener and database were stopped when I looked in the Task Manager.

1: Hit Ctrl-Alt-Del and select "Start Task Manager".

From there go to the "Services" tab.

There are 5 services that need to be running for the database to be accessed correctly.

In the list below "databasename" is the database name you assigned during creation without the quotes.

I am also using database 11g, if you are using another type those fields would be different below. the * after home is the home install, if you have more than 1 database there would be home1, and home2

These are the 5 services

  1. OracleVssWriter"databasename"
  2. OracleService"databasename"
  3. OracleOraDb11g_home*TNSListener
  4. OracleOraDb11g_home*ClrAgent
  5. OracleDBConsole"databasename"

If any of these services are stopped right click on them and start them. After they have all started go back into SQL developer and re-try the connection and it should work.

How to remove last n characters from every element in the R vector

Here is an example of what I would do. I hope it's what you're looking for.

char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)

a should now contain:

  data data2
1 foo_ 1
2 bar_ 2
3   ap 3
4    b 4

Event handlers for Twitter Bootstrap dropdowns?

Twitter bootstrap is meant to give a baseline functionality, and provides only basic javascript plugins that do something on screen. Any additional content or functionality, you'll have to do yourself.

<div class="btn-group">
  <button class="btn dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href="#" id="action-1">Action</a></li>
    <li><a href="#" id="action-2">Another action</a></li>
    <li><a href="#" id="action-3">Something else here</a></li>
</div><!-- /btn-group -->

and then with jQuery

//do something

How to pass parameters to a Script tag?

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

Unable to get spring boot to automatically create database schema

If your entity class isn't in the same package as your main class, you can use @EntityScan annotation in the main class, specifying the Entity you want to save or package too. Like your model package.


spring.jpa.hibernate.ddl-auto = create

You can use the option update. It won't erase any data, and will create tables in the same way.

In jQuery, how do I get the value of a radio button when they all have the same name?

in your selector, you should also specify that you want the checked radiobutton:


Windows batch script to move files

This is exactly how it worked for me. For some reason the above code failed.

This one runs a check every 3 minutes for any files in there and auto moves it to the destination folder. If you need to be prompted for conflicts then change the /y to /-y

move /y "D:\Dropbox\Dropbox\Camera Uploads\*.*" "D:\Archive\Camera Uploads\"
timeout 360
goto backup

Google Chrome: This setting is enforced by your administrator

Try to use this solution:


Run regedit, Delete the key, then restart Chrome.

How to import an existing project from GitHub into Android Studio

In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.

Good Luck with your project

How to remove elements/nodes from angular.js array

You can use plain javascript - Array.prototype.filter()

$scope.items = $scope.items.filter(function(item) {
    return !== 'ted';

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2015, this is how you do it.

If you want to automatically include all descendant files below a specific folder:

<Content Include="Path\To\Folder\**" />

This can be restricted to include only files within the path specified:

<Content Include="Path\To\Folder\*.*" />

Or even only files with a specified extension:

<Content Include="Path\To\Folder\*.jpg" >

The import javax.servlet can't be resolved

I had the same problem because my "Dynamic Web Project" had no reference to the installed server i wanted to use and therefore had no reference to the Servlet API the server provides.

Following steps solved it without adding an extra Servlet-API to the Java Build Path (Eclipse version: Luna):

  • Right click on your "Dynamic Web Project"
  • Select Properties
  • Select Project Facets in the list on the left side of the "Properties" wizard
  • On the right side of the wizard you should see a tab named Runtimes. Select the Runtime tab and check the server you want to run the servlet.

Edit: if there is no server listed you can create a new one on the Runtimes tab

package R does not exist

I forgot to add the "name" of my "package" at the top of my java class. Check if yours is actually added.

Protractor : How to wait for page complete after click a button?

Depending on what you want to do, you can try:


or {
  // do some stuff 

to solve the promise. It would be better if you can do that in the beforeEach.

NB: I noticed that the expect() waits for the promise inside (i.e. getCurrentUrl) to be solved before comparing.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Simple Steps

  1. 1 Open SQL Server Configuration Manager
  2. Under SQL Server Services Select Your Server
  3. Right Click and Select Properties
  4. Log on Tab Change Built-in-account tick
  5. in the drop down list select Network Service
  6. Apply and start The service

Where is Java Installed on Mac OS X?

If you type

java -verbose 

This also gives the location from which the jars are loaded and hence also the java path.

How to set JAVA_HOME environment variable on Mac OS X 10.9?

I got it working by adding to ~/.profile. Somehow after updating to El Capitan beta, it didnt work even though JAVA_HOME was defined in .bash_profile.

If there are any El Capitan beta users, try adding to .profile

How to trap on UIViewAlertForUnsatisfiableConstraints?

This usually appears when you want to use UIActivityViewController in iPad.

Add below, before you present the controller to mark the arrow.

activityViewController.popoverPresentationController?.sourceRect = senderView.frame // senderView can be your button/view you tapped to call this VC

I assume you already have below, if not, add together:

activityViewController.popoverPresentationController?.sourceView = self.view

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Nicer code for this:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

How to link to a named anchor in Multimarkdown?

The best way to create internal links (related with sections) is create list but instead of link, put #section or #section-title if the header includes spaces.


Go to section
* [Hello](#hello)  
* [Hello World](#hello-world)
* [Another section](#new-section) <-- it's called 'Another section' in this list but refers to 'New section'

## Hello
### Hello World
## New section

List preview

Go to section
Hello           <-- [Hello](#hello)                 -- go to `Hello` section
Hello World     <-- [Hello World](#hello world)     -- go to `Hello World` section
Another section <-- [Another section](#new-section) -- go to `New section`


<p>Go to section</p>
    <li><a href="#hello">Hello</a></li>
    <li><a href="#hello-world">Hello World</a></li>
    <li><a href="#new-section">Another section</a> &lt;– it’s called ‘Another section’ in this list but refers to ‘New section’</li>
<h2 id="hello">Hello</h2>
<h3 id="hello-world">Hello World</h3>
<h2 id="new-section">New section</h2>

It doesn't matter whether it's h1, h2, h3, etc. header, you always refer to it using just one #.
All references in section list should be converted to lowercase text as it is shown in the example above.

The link to the section should be lowercase. It won't work otherwise. This technique works very well for all Markdown variants, also MultiMarkdown.

Currently I'm using the Pandoc to convert documents format. It's much better than MultiMarkdown.
Test Pandoc here

An efficient way to transpose a file in Bash

Here's a Haskell solution. When compiled with -O2, it runs slightly faster than ghostdog's awk and slightly slower than Stephan's thinly wrapped c python on my machine for repeated "Hello world" input lines. Unfortunately GHC's support for passing command line code is non-existent as far as I can tell, so you will have to write it to a file yourself. It will truncate the rows to the length of the shortest row.

transpose :: [[a]] -> [[a]]
transpose = foldr (zipWith (:)) (repeat [])

main :: IO ()
main = interact $ unlines . map unwords . transpose . map words . lines

Swift - encode URL

Swift 3:

let originalString = ""

1. encodingQuery:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)



2. encodingURL:

let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)



String Concatenation in EL

With EL 2 you can do the following:

#{'this'.concat(' is').concat(' a').concat(' test!')}

How to upgrade all Python packages with pip

If you are on macOS,

  1. make sure you have Homebrew installed
  2. install jq in order to read the JSON you’re about to generate
brew install jq
  1. update each item on the list of outdated packages generated by pip3 list --outdated
pip3 install --upgrade  `pip3 list --outdated --format json | jq '.[] | .name' | awk -F'"' '{print $2}'`

Phonegap Cordova installation Windows

I faced the same problem and struggled for an hour to get pass through by reading the documents and the other issues reported in Stack Overflow but I didn't find any answer to it. So, here is the guide to successfully run the phonegap/cordova in Windows Machine.

Follow these steps

  1. Download and Install node.js from
  2. Run the command npm install -g phonegap (in case of phonegap installation) or run the command npm install -g cordova (in case of Cordova installation).
  3. As the installation gets completed you can notice this:

    C:\Users\binaryuser\AppData\Roaming\npm\cordova -> C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova\bin\cordova
    [email protected] C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected] ([email protected])
    +-- [email protected] ([email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected]
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
  4. Notice the above line you can see the path were the file is mentioned. Copy that path. In my case it is C:\Users\binaryuser\AppData\Roaming\npm\cordova so use cd C:\Users\binaryuser\AppData\Roaming\npm\ and type cordova. There it is, it finally works.

  5. Since the -g key value isn't working you have set the Environment Variables path:
    1. Press Win + Pause|Break or right click on Computer and choose Properties.
    2. Click Advanced system settings on the left.
    3. Click Environment Variables under the Advanced tab.
    4. Select the PATH variable and click Edit.
    5. Copy the path mentioned above to the value field and press OK.

Make one div visible and another invisible

Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.

ExecuteNonQuery: Connection property has not been initialized.

double click on your form to create form_load event.Then inside that event write command.connection = "your connection name";

Is there an addHeaderView equivalent for RecyclerView?

There isn't an easy way like listview.addHeaderView() but you can achieve this by adding a type to your adapter for header.

Here is an example

public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    String[] data;

    public HeaderAdapter(String[] data) { = data;

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new VHItem(null);
        } else if (viewType == TYPE_HEADER) {
            //inflate your layout and pass it to view holder
            return new VHHeader(null);

        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");

    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            String dataItem = getItem(position);
            //cast holder to VHItem and set data
        } else if (holder instanceof VHHeader) {
            //cast holder to VHHeader and set data for header.

    public int getItemCount() {
        return data.length + 1;

    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;

    private boolean isPositionHeader(int position) {
        return position == 0;

    private String getItem(int position) {
        return data[position - 1];

    class VHItem extends RecyclerView.ViewHolder {
        TextView title;

        public VHItem(View itemView) {

    class VHHeader extends RecyclerView.ViewHolder {
        Button button;

        public VHHeader(View itemView) {

link to gist -> here

How can I get the current network interface throughput statistics on Linux/UNIX?

I couldn't get the parse ifconfig script to work for me on an AMI so got this to work measuring received traffic averaged over 10 seconds

date && rxstart=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && sleep 10 && rxend=`ifconfig eth0 | grep bytes | awk '{print $2}' | cut -d : -f 2` && difference=`expr $rxend - $rxstart` && echo "Received `expr $difference / 10` bytes per sec"

Sorry, it's ever so cheap and nasty but it worked!

Bootstrap Columns Not Working

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-4">  
                    <a href="">About</a>
                <div class="col-md-4">
                    <img src="image.png">
                <div class="col-md-4"> 
                    <a href="#myModal1" data-toggle="modal">SHARE</a>

You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.

A simpler way would be

<div class="container">
   <div class="row">
       <div class="col-md-4">  
          <a href="">About</a>
       <div class="col-md-4">
          <img src="image.png">
       <div class="col-md-4"> 
           <a href="#myModal1" data-toggle="modal">SHARE</a>

node.js, with SSL

Depending on your needs, you could allow both secure and unsecure connections and still only use one instance.

You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the instance.

Server side :

// needed to read certificates from disk
const fs          = require( "fs"    );

// Servers with and without SSL
const http        = require( "http"  )
const https       = require( "https" );
const httpPort    = 3333;
const httpsPort   = 3334;
const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )
httpServer.listen( httpPort, function() {
    console.log(  `Listening HTTP on ${httpPort}` );
httpsServer.listen( httpsPort, function() {
    console.log(  `Listening HTTPS on ${httpsPort}` );

const ioServer = require( "" );
const io       = new ioServer();
io.attach( httpServer  );
io.attach( httpsServer );

io.on( "connection", function( socket ) {

    console.log( "user connected" );
    // ... your code


Client side :

var url    = "//" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
    // set to false only if you use self-signed certificate !
    "rejectUnauthorized": true
socket.on( "connect", function( e ) {
    console.log( "connect", e );

If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:

const httpServer  = http.createServer();
const httpsServer = https.createServer({
    "key" : fs.readFileSync( "yourcert.key" ),
    "cert": fs.readFileSync( "yourcert.crt" ),
    "ca"  : fs.readFileSync( "yourca.crt"   )


const CORS_fn = (req, res) => {
    res.setHeader( "Access-Control-Allow-Origin"     , "*"    );
    res.setHeader( "Access-Control-Allow-Credentials", "true" );
    res.setHeader( "Access-Control-Allow-Methods"    , "*"    );
    res.setHeader( "Access-Control-Allow-Headers"    , "*"    );
    if ( req.method === "OPTIONS" ) {
const httpServer  = http.createServer( CORS_fn );
const httpsServer = https.createServer({
        "key" : fs.readFileSync( "yourcert.key" ),
        "cert": fs.readFileSync( "yourcert.crt" ),
        "ca"  : fs.readFileSync( "yourca.crt"   )
}, CORS_fn );

And of course add/remove headers and set the values of the headers according to your needs.

jQuery: print_r() display equivalent?

You can also do

console.log("a = %o, b = %o", a, b);

where a and b are objects.

What is the difference between partitioning and bucketing a table in Hive ?

Partitioning data is often used for distributing load horizontally, this has performance benefit, and helps in organizing data in a logical fashion. Example: if we are dealing with a large employee table and often run queries with WHERE clauses that restrict the results to a particular country or department . For a faster query response Hive table can be PARTITIONED BY (country STRING, DEPT STRING). Partitioning tables changes how Hive structures the data storage and Hive will now create subdirectories reflecting the partitioning structure like


If query limits for employee from country=ABC, it will only scan the contents of one directory country=ABC. This can dramatically improve query performance, but only if the partitioning scheme reflects common filtering. Partitioning feature is very useful in Hive, however, a design that creates too many partitions may optimize some queries, but be detrimental for other important queries. Other drawback is having too many partitions is the large number of Hadoop files and directories that are created unnecessarily and overhead to NameNode since it must keep all metadata for the file system in memory.

Bucketing is another technique for decomposing data sets into more manageable parts. For example, suppose a table using date as the top-level partition and employee_id as the second-level partition leads to too many small partitions. Instead, if we bucket the employee table and use employee_id as the bucketing column, the value of this column will be hashed by a user-defined number into buckets. Records with the same employee_id will always be stored in the same bucket. Assuming the number of employee_id is much greater than the number of buckets, each bucket will have many employee_id. While creating table you can specify like CLUSTERED BY (employee_id) INTO XX BUCKETS; where XX is the number of buckets . Bucketing has several advantages. The number of buckets is fixed so it does not fluctuate with data. If two tables are bucketed by employee_id, Hive can create a logically correct sampling. Bucketing also aids in doing efficient map-side joins etc.

How to get a list of current open windows/process with Java?

This is my code for a function that gets the tasks and gets their names, also adding them into a list to be accessed from a list. It creates temp files with the data, reads the files and gets the task name with the .exe suffix, and arranges the files to be deleted when the program has exited with System.exit(0), it also hides the processes being used to get the tasks and also java.exe so that the user can't accidentally kill the process that runs the program all together.

private static final DefaultListModel tasks = new DefaultListModel();

public static void getTasks()
    new Thread()
        public void run()
                File batchFile = File.createTempFile("batchFile", ".bat");
                File logFile = File.createTempFile("log", ".txt");
                String logFilePath = logFile.getAbsolutePath();
                try (PrintWriter fileCreator = new PrintWriter(batchFile)) 
                    String[] linesToPrint = {"@echo off", "tasklist.exe >>" + logFilePath, "exit"};
                    for(String string:linesToPrint)
                int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();
                if(task == 0)
                    FileReader fileOpener = new FileReader(logFile);
                    try (BufferedReader reader = new BufferedReader(fileOpener))
                        String line;
                            line = reader.readLine();
                            if(line != null)
                                        int index = line.lastIndexOf(".exe", line.length());
                                        String taskName = line.substring(0, index + 4);
                                        if(! taskName.equals("tasklist.exe") && ! taskName.equals("cmd.exe") && ! taskName.equals("java.exe"))
            catch (FileNotFoundException ex) 
                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
            catch (IOException | InterruptedException ex) 
                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
            catch (NullPointerException ex)
                // This stops errors from being thrown on an empty line

public static void killTask(String taskName)
    new Thread()
        public void run()
                Runtime.getRuntime().exec("taskkill.exe /IM " + taskName);
            catch (IOException ex) 
                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

Get Base64 encode file-data from Input Form

Inspired by @Josef's answer:

const fileToBase64 = async (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = (e) => reject(e)

const file = event.srcElement.files[0];
const imageStr = await fileToBase64(file)

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

How do I use a regex in a shell script?

To complement the existing helpful answers:

Using Bash's own regex-matching operator, =~, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:

set -- '12-34-5678' # set $1 to sample value

kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match

Note, however, that the caveat re using flavor-specific regex constructs such as \d equally applies: While =~ supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.

To remain portable (in the context of Bash), stick to the POSIX ERE specification.

Note that =~ even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]} array variable.

Further notes:

  • $kREGEX_DATE is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).

  • While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \.

    • E.g., on Linux, where \< is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes does.
  • I've changed variable name REGEX_DATE to kREGEX_DATE (k signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Open up Windows' System Properties from the control panel and hunt down the environment variables section:

  • Add a JAVA_HOME entry pointing to the directory where the JDK is installed (e.g. C:\Program Files\Java\jre6)
  • Find the Path entry and add the following onto the end ;%JAVA_HOME%\bin
  • OK the changes
  • Restart eclipse so that it is aware of the new environment

Most Java tools will now be able to find your Java installation either by using the JAVA_HOME environment variable or by looking for java.exe / javaw.exe in the Path environment variable.

How do I pass along variables with XMLHTTPRequest

How about?

function callHttpService(url, params){
  // Assume params contains key/value request params
  let queryStrings = '';

  for(let key in params){
      queryStrings += `${key}=${params[key]}&`
 const fullUrl = `${url}?queryStrings`

  //make http request with fullUrl

Javascript Array of Functions

I would complement this thread by posting an easier way to execute various functions within an Array using the shift() Javascript method originally described here

  var a = function(){ console.log("this is function: a") }
  var b = function(){ console.log("this is function: b") }
  var c = function(){ console.log("this is function: c") }

  var foo = [a,b,c];

  while (foo.length){

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

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle:

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>

    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>

How do I connect to this localhost from another computer on the same network?

This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.

# Using a vhost
$ browser-sync start --proxy

# Using a vhost with PORT
$ browser-sync start --proxy

# Using a localhost address
$ browser-sync start --proxy localhost:8001

# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1

How to limit the number of selected checkboxes?

  if ($('.checkbox:checked').length >= 3) {

i used this.

Cluster analysis in R: determine the optimal number of clusters

If your question is how can I determine how many clusters are appropriate for a kmeans analysis of my data?, then here are some options. The wikipedia article on determining numbers of clusters has a good review of some of these methods.

First, some reproducible data (the data in the Q are... unclear to me):

n = 100
g = 6 
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), 
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))

enter image description here

One. Look for a bend or elbow in the sum of squared error (SSE) scree plot. See & for more. The location of the elbow in the resulting plot suggests a suitable number of clusters for the kmeans:

mydata <- d
wss <- (nrow(mydata)-1)*sum(apply(mydata,2,var))
  for (i in 2:15) wss[i] <- sum(kmeans(mydata,
plot(1:15, wss, type="b", xlab="Number of Clusters",
     ylab="Within groups sum of squares")

We might conclude that 4 clusters would be indicated by this method: enter image description here

Two. You can do partitioning around medoids to estimate the number of clusters using the pamk function in the fpc package.

library(fpc) <- pamk(d)
cat("number of clusters estimated by optimum average silhouette width:",$nc, "\n")

enter image description here enter image description here

# we could also do:
asw <- numeric(20)
for (k in 2:20)
  asw[[k]] <- pam(d, k) $ silinfo $ avg.width <- which.max(asw)
cat("silhouette-optimal number of clusters:",, "\n")
# still 4

Three. Calinsky criterion: Another approach to diagnosing how many clusters suit the data. In this case we try 1 to 10 groups.

fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE) <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:",, "\n")
# 5 clusters!

enter image description here

Four. Determine the optimal model and number of clusters according to the Bayesian Information Criterion for expectation-maximization, initialized by hierarchical clustering for parameterized Gaussian mixture models

# See
# Run the function to see how many clusters
# it finds to be optimal, set it to search for
# at least 1 model and up 20.
d_clust <- Mclust(as.matrix(d), G=1:20) <- dim(d_clust$z)[2]
cat("model-based optimal number of clusters:",, "\n")
# 4 clusters

enter image description here enter image description here enter image description here

Five. Affinity propagation (AP) clustering, see

d.apclus <- apcluster(negDistMat(r=2), d)
cat("affinity propogation optimal number of clusters:", length(d.apclus@clusters), "\n")
# 4
plot(d.apclus, d)

enter image description here enter image description here

Six. Gap Statistic for Estimating the Number of Clusters. See also some code for a nice graphical output. Trying 2-10 clusters here:

clusGap(d, kmeans, 10, B = 100, verbose = interactive())

Clustering k = 1,2,..., K.max (= 10): .. done
Bootstrapping, b = 1,2,..., B (= 100)  [one "." per sample]:
.................................................. 50 
.................................................. 100 
Clustering Gap statistic ["clusGap"].
B=100 simulated reference sets, k = 1..10
 --> Number of clusters (method 'firstSEmax', SE.factor=1): 4
          logW   E.logW        gap     SE.sim
 [1,] 5.991701 5.970454 -0.0212471 0.04388506
 [2,] 5.152666 5.367256  0.2145907 0.04057451
 [3,] 4.557779 5.069601  0.5118225 0.03215540
 [4,] 3.928959 4.880453  0.9514943 0.04630399
 [5,] 3.789319 4.766903  0.9775842 0.04826191
 [6,] 3.747539 4.670100  0.9225607 0.03898850
 [7,] 3.582373 4.590136  1.0077628 0.04892236
 [8,] 3.528791 4.509247  0.9804556 0.04701930
 [9,] 3.442481 4.433200  0.9907197 0.04935647
[10,] 3.445291 4.369232  0.9239414 0.05055486

Here's the output from Edwin Chen's implementation of the gap statistic: enter image description here

Seven. You may also find it useful to explore your data with clustergrams to visualize cluster assignment, see for more details.

Eight. The NbClust package provides 30 indices to determine the number of clusters in a dataset.

nb <- NbClust(d, diss=NULL, distance = "euclidean",
        method = "kmeans",,, 
        index = "alllong", alphaBeale = 0.1)
hist(nb$[1,], breaks = max(na.omit(nb$[1,])))
# Looks like 3 is the most frequently determined number of clusters
# and curiously, four clusters is not in the output at all!

enter image description here

If your question is how can I produce a dendrogram to visualize the results of my cluster analysis, then you should start with these: And see here for more exotic methods:

Here are a few examples:

d_dist <- dist(as.matrix(d))   # find distance matrix 
plot(hclust(d_dist))           # apply hirarchical clustering and plot

enter image description here

# a Bayesian clustering method, good for high-dimension data, more details:
x <- as.matrix(d)
d.bclus <- bclust(x, transformed.par = c(0, -50, log(16), 0, 0, 0))
viplot(imp(d.bclus)$var); plot(d.bclus); ditplot(d.bclus)
dptplot(d.bclus, scale = 20, horizbar.plot = TRUE,varimp = imp(d.bclus)$var, horizbar.distance = 0, dendrogram.lwd = 2)
# I just include the dendrogram here

enter image description here

Also for high-dimension data is the pvclust library which calculates p-values for hierarchical clustering via multiscale bootstrap resampling. Here's the example from the documentation (wont work on such low dimensional data as in my example):

boston.pv <- pvclust(Boston)

enter image description here

Does any of that help?

Cross-browser custom styling for file upload button

Please find below a way that works on all browsers. Basically I put the input on top the image. I make it huge using font-size so the user is always clicking the upload button.

.myFile {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  float: left;_x000D_
  clear: left;_x000D_
.myFile input[type="file"] {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  opacity: 0;_x000D_
  font-size: 100px;_x000D_
  filter: alpha(opacity=0);_x000D_
  cursor: pointer;_x000D_
<label class="myFile">_x000D_
  <img src="" alt="" />_x000D_
  <input type="file" />_x000D_

Error In PHP5 ..Unable to load dynamic library

Seems like you upgraded PHP to newer version and old .ini files are still pointing to old location.

The solution: find out where are modules located now

ls -l /usr/lib/php5

There should be a directory similar to old 20090626. In my case it is now 20131226

The .ini files giving you an error are located at /etc/php5/cli/conf.d/

Just edit those .ini files which module gives you an error. For example, in case the error is for mcrypt module:

sudo vi /etc/php5/cli/conf.d/20-mcrypt.ini

Change the line:


to reflect the new path for .so file. In my case the correct path should be:


That's it! The error is gone. Ofc you'd have to do it with each module giving you an error.

How do I parse a URL into hostname and path in javascript?

js-uri (available on Google Code) takes a string URL and resolves a URI object from it:

var some_uri = new URI("");

alert(some_uri.authority); //
alert(some_uri);           //

var blah      = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full);         //

How do I solve this "Cannot read property 'appendChild' of null" error?

For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.

                var div, container = document.getElementById("container")
                for(var i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);

        <div id="container"></div>

Looking at the error in the console for the above code.

Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.

            height: 200px;
            width: 700px;
            background-color: red;
            margin: 10px;

            height: 100px;
            width: 100px;
            background-color: purple;
            margin: 20px;
            display: inline-block;
        <div id="container"></div>
                var div, container = document.getElementById("container")
                for(let i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);

I hope this helps. :)

Get Hours and Minutes (HH:MM) from date

The following works on 2008R2+ to produce 'HH:MM':

when len(replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')) = 4
then '0'+ replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','')
else replace(replace(replace(right(cast(getdate() as varchar),7),'AM',''),'PM',''),' ','') end as [Time]

Insert an item into sorted list in Python

This is the best way to append the list and insert values to sorted list:

 a = [] num = int(input('How many numbers: ')) for n in range(num):
     numbers = int(input('Enter values:'))

 b = sorted(a) print(b) c = int(input("enter value:")) for i in
     if b[i] > c:
         index = i
         break d = b[:i] + [c] + b[i:] print(d)`

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
set /p "a=Enter Choice: "
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    set "param1=%globalparam2%"
    goto :param1Check
    set /p "param1=Enter Choice: "
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s '' | python -c "import sys, json; print json.load(sys.stdin)['region']")


Inputting a default image in case the src attribute of an html <img> is not valid?

A modulable version with JQuery, add this at the end of your file:

    $(function() {
        $('img[data-src-error]').error(function() {
            var o = $(this);
            var errorSrc = o.attr('data-src-error');

            if (o.attr('src') != errorSrc) {
                o.attr('src', errorSrc);

and on your img tag:

<img src="..." data-src-error="..." />

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

How to specify test directory for mocha?

Run all files in test_directory including sub directories that match test.js

find ./parent_test_directory -name '*test.js' | xargs mocha -R spec

or use the --recursive switch

mocha --recursive test_directory/

How to get the current time in milliseconds from C in Linux?

You have to do something like this:

struct timeval  tv;
gettimeofday(&tv, NULL);

double time_in_mill = 
         (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond

What is the Linux equivalent to DOS pause?

read does this:

user@host:~$ read -n1 -r -p "Press any key to continue..." key

The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

If you are using Bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
    echo 'A key was pressed.'
    echo 'No key was pressed.'

How to JOIN three tables in Codeigniter

public function getdata(){
        $this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, as id');
        $this->db->from('tblmaster t'); 
        $this->db->join('country c', '');
        $this->db->join('state s', 't.state=s.state_id');
        $this->db->join('city ct', '');
        $query = $this->db->get();      
        return $query->result();

How to get access to HTTP header information in Spring MVC REST controller?

You can use HttpEntity to read both Body and Headers.

   @RequestMapping(value = "/restURL")
   public String serveRest(HttpEntity<String> httpEntity){
                MultiValueMap<String, String> headers = 
                Iterator<Map.Entry<String, List<String>>> s = 
                while(s.hasNext()) {
                    Map.Entry<String, List<String>> obj =;
                    String key = obj.getKey();
                    List<String> value = obj.getValue();
                String body = httpEntity.getBody();


MySQL: is a SELECT statement case sensitive?

String fields with the binary flag set will always be case sensitive. Should you need a case sensitive search for a non binary text field use this: SELECT 'test' REGEXP BINARY 'TEST' AS RESULT;

'uint32_t' identifier not found error

You can #include <cstdint>. It's part of C++-standard since 2011.

How to call a function in shell Scripting?

The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:

main() {
  case "$choice" in
    true)  process_install;;
    false) process_exit;;




Firebase FCM notifications click_action payload

If your app is in background, Firebase will not trigger onMessageReceived(). onMessageReceived() is called when app is in foreground . When app is in background,onMessageReceived() method will be called only if the body of contain only data payload.Here ,i just created a method to build custom notification with intent having ur your required activity . and called this method in onMessageRecevied() .

In PostMan:


header:Authorization:key=ur key

body --->>

{  "data" : {
      "Nick" : "Mario",
      "Room" : "PoSDenmark",


  "to" : "xxxxxxxxx"


in your application.

class MyFirebaseMessagingService  extends FirebaseMessagingService {

 public void onMessageReceived(RemoteMessage remoteMessage) {
       if (remoteMessage.getData().size() > 0) {
           sendNotification("ur message body") ;
private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, Main2Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setContentTitle("FCM Message")

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */,;


when the data payload comes to the mobile,then onMessageReceived() method will be called.. inside that method ,i just made a custom notification. this will work even if ur app is background or foreground.

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

How to detect Ctrl+V, Ctrl+C using JavaScript?

Short solution for preventing user from using context menu, copy and cut in jQuery:

jQuery(document).bind("cut copy contextmenu",function(e){

Also disabling text selection in CSS might come handy:

.noselect {  
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
     user-select: none;

Using parameters in batch files at Windows command line

Batch Files automatically pass the text after the program so long as their are variables to assign them to. They are passed in order they are sent; e.g. %1 will be the first string sent after the program is called, etc.

If you have Hello.bat and the contents are:

@echo off
echo.Hello, %1 thanks for running this batch file (%2)

and you invoke the batch in command via

hello.bat APerson241 %date%

you should receive this message back:

Hello, APerson241 thanks for running this batch file (01/11/2013)

Getting the names of all files in a directory with PHP

You could just try the scandir(Path) function. it is fast and easy to implement


$files = scandir("somePath");

This Function returns a list of file into an Array.

to view the result, you can try



foreach($files as $file)
echo $file."< br>";

From an array of objects, extract value of a property as array

It is better to use some sort of libraries like lodash or underscore for cross browser assurance.

In Lodash you can get values of a property in array by following method,"foo")

and in Underscore


Both will return

[1, 2, 3]

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Highlighting Text Color using Html.fromHtml() in Android?

Alternative solution: Using a WebView instead. Html is easy to work with.

WebView webview = new WebView(this);

String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";

webview.loadData(summary, "text/html", "utf-8");

Transport endpoint is not connected

There is a segmentation fault problem which was introduced in 0.1.39. You may check my repository that fixed this one in meanwhile:

How do I assert an Iterable contains elements with a certain property?

AssertJ 3.9.1 supports direct predicate usage in anyMatch method.

assertThat(collection).anyMatch(element -> element.someProperty.satisfiesSomeCondition())

This is generally suitable use case for arbitrarily complex condition.

For simple conditions I prefer using extracting method (see above) because resulting iterable-under-test might support value verification with better readability. Example: it can provide specialized API such as contains method in Frank Neblung's answer. Or you can call anyMatch on it later anyway and use method reference such as "searchedvalue"::equals. Also multiple extractors can be put into extracting method, result subsequently verified using tuple().

CSS display:table-row does not expand when width is set to 100%

Tested answer:

In the .view-row css, change:




and get rid of "float". Everything will work as expected.

As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.

Working example:

<div class="view">

with css:

.view {

.view > div {
  display: table-cell;

Object spread vs. Object.assign

This is now part of ES6, thus is standardized, and is also documented on MDN:

It's very convenient to use and makes a lot of sense alongside object destructuring.

The one remaining advantage listed above is the dynamic capabilities of Object.assign(), however this is as easy as spreading the array inside of a literal object. In the compiled babel output it uses exactly what is demonstrated with Object.assign()

So the correct answer would be to use object spread since it is now standardized, widely used (see react, redux, etc), is easy to use, and has all the features of Object.assign()

How to select records without duplicate on just one field in SQL?

Duplicate rows can be removed for Complex Queries by,

First storing the result to a #TempTable or @TempTableVariable

Delete from #TempTable or @TempTableVariable where your condition

Then select the rest of the data.

If need to create a row number create an identity column.

How can I remove the extension of a filename in a shell script?

echo $file ${file%.*}


/tmp/ /tmp/

Note that only the last extension is removed.

Can I send a ctrl-C (SIGINT) to an application on Windows?

A solution that I have found from here is pretty simple if you have python 3.x available in your command line. First, save a file ( with the contents:

import ctypes
import sys

kernel = ctypes.windll.kernel32

pid = int(sys.argv[1])
kernel.SetConsoleCtrlHandler(None, 1)
kernel.GenerateConsoleCtrlEvent(0, 0)

Then call:

python 12345

If that doesn't work, I recommend trying out the windows-kill project:

Change arrow colors in Bootstraps carousel

This worked for me:

.carousel-control-prev-icon {
        background-image: url("data:image/svg+xml,%3csvg xmlns='' fill='%23000' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e");
      .carousel-control-next-icon {
        background-image: url("data:image/svg+xml,%3csvg xmlns='' fill='%23000' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5L3.75 4l-2.5 2.5L2.75 8l4-4-4-4z'/%3e%3c/svg%3e");

I changed the color in the url of the icon. Thats the original that is used in the bootstrap page but with this section in black:


How to add new DataRow into DataTable?

If need to copy from another table then need to copy structure first:

DataTable copyDt = existentDt.Clone();

show dbs gives "Not Authorized to execute command" error

for me it worked by adding

1) "You can run the mongodb instance without username and password first.---OK

2) "Then you can add the user to the system database of the mongodb which is default one using the query below".---OK

  user: "myUserAdmin",
  pwd: "abc123",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ],
  mechanisms:[ "SCRAM-SHA-1" ] // I added this line


Assign an initial value to radio button as checked

For anyone looking for an Angular2 (2.4.8) solution, since this is a generically-popular question when searching:

<div *ngFor="let choice of choices">
  <input type="radio" [checked]="choice == defaultChoice">

This will add the checked attribute to the input given the condition, but will add nothing if the condition fails.

Do not do this:

[attr.checked]="choice == defaultChoice"

because this will add the attribute checked="false" to every other input element.

Since the browser only looks for the presence of the checked attribute (the key), ignoring its value, so the last input in the group will be checked.

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.


$sample = <<END;
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";

Find JavaScript function definition in Chrome

2016 Update: in Chrome Version 51.0.2704.103

There is a Go to member shortcut (listed in settings > shortcut > Text Editor). Open the file containing your function (in the sources panel of the DevTools) and press:

ctrl + shift + O

or in OS X:

? + shift + O

This enables to list and reach members of the current file.

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup

Here's a jsfiddle for you to play around.

Import error: No module name urllib2

Python 3:

import urllib.request

wp = urllib.request.urlopen("")
pw =

Python 2:

import urllib
import sys

wp = urllib.urlopen("")
for line in wp:

While I have tested both the Codes in respective versions.

How do I read input character-by-character in Java?

If I were you I'd just use a scanner and use ".nextByte()". You can cast that to a char and you're good.

Image, saved to sdcard, doesn't appear in Android's Gallery app

this work with me

File file = ..... // Save file

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

How to know if other threads have finished?

You could also use the Executors object to create an ExecutorService thread pool. Then use the invokeAll method to run each of your threads and retrieve Futures. This will block until all have finished execution. Your other option would be to execute each one using the pool and then call awaitTermination to block until the pool is finished executing. Just be sure to call shutdown() when you're done adding tasks.

cannot connect to pc-name\SQLEXPRESS

Use (LocalDB)\MSSQLLocalDB as the server name

How can I know which radio button is selected via jQuery?

You can use the :checked selector along with the radio selector.


Copy folder recursively in Node.js

There are some modules that support copying folders with their content. The most popular would be wrench.js:

// Deep-copy an existing directory
wrench.copyDirSyncRecursive('directory_to_copy', 'location_where_copy_should_end_up');

An alternative would be node-fs-extra:

fs.copy('/tmp/mydir', '/tmp/mynewdir', function (err) {
  if (err) {
  } else {
}); // Copies directory, even if it has subdirectories or files

PHP Constants Containing Arrays?

You can store them as static variables of a class:

class Constants {
    public static $array = array('guy', 'development team');
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';

If you don't like the idea that the array can be changed by others, a getter might help:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
$constantArray = Constants::getArray();


Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

$x = Constants::getArray()['index'];

'invalid value encountered in double_scalars' warning, possibly numpy

Zero-size array passed to numpy.mean raises this warning (as indicated in several comments).

For some other candidates:

  • median also raises this warning on zero-sized array.

other candidates do not raise this warning:

  • min,argmin both raise ValueError on empty array
  • randn takes *arg; using randn(*[]) returns a single random number
  • std,var return nan on an empty array

Validate that text field is numeric usiung jQuery

This should work. I would trim the whitespace from the input field first of all:

if($('#Field').val() != "") {
    var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var intRegex = /^\d+$/;
    if(!intRegex.test(value)) {
        errors += "Field must be numeric.<br/>";
        success = false;
} else {
    errors += "Field is blank.</br />";
    success = false;

What are all codecs and formats supported by FFmpeg?

The formats and codecs supported by your build of ffmpeg can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.

Formats (muxers and demuxers):

List all formats:

ffmpeg -formats

Display options specific to, and information about, a particular muxer:

ffmpeg -h muxer=matroska

Display options specific to, and information about, a particular demuxer:

ffmpeg -h demuxer=gif

Codecs (encoders and decoders):

List all codecs:

ffmpeg -codecs

List all encoders:

ffmpeg -encoders

List all decoders:

ffmpeg -decoders

Display options specific to, and information about, a particular encoder:

ffmpeg -h encoder=mpeg4

Display options specific to, and information about, a particular decoder:

ffmpeg -h decoder=aac

Reading the results

There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:

$ ffmpeg -encoders
 V..... = Video
 A..... = Audio
 S..... = Subtitle
 .F.... = Frame-level multithreading
 ..S... = Slice-level multithreading
 ...X.. = Codec is experimental
 ....B. = Supports draw_horiz_band
 .....D = Supports direct rendering method 1
 V.S... mpeg4                MPEG-4 part 2

In this example V.S... indicates that the encoder mpeg4 is a Video encoder and supports Slice-level multithreading.

Also see

What is a codec and how does it differ from a format?

Advantages of using display:inline-block vs float:left in CSS

There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.

Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.

button image as form input submit button?

You could use an image submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

Convert command line argument to string

I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**) doesn't use const char** so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.

#include <cstdio>
#include <iostream>

using namespace std;

namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  return true;
}  // namespace _

int main(int args_count, char** args) {
  cout << "\n\nTesting ArgsToString...\n";

  if (args_count <= 1) return 1;
  cout << "\nArguments:\n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
  cout << "\n\nContiguous Args:\n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "\n\nContiguous Args:\n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
      cout << c;
  cout << "\n\nPrinting argument string...\n";
  _::ArgsToString(args_count, args);
  cout << "\n" << args[1];
  return 0;

$(document).click() not working correctly on iPhone. jquery

On mobile iOS the click event does not bubble to the document body and thus cannot be used with .live() events. If you have to use a non native click-able element like a div or section is to use cursor: pointer; in your css for the non-hover on the element in question. If that is ugly you could look into delegate().

Iteration over std::vector: unsigned vs signed index variable

For iterating backwards see this answer.

Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use std::size_t as the index variable type. However, that is not portable. Always use the size_type typedef of the container (While you could get away with only a conversion in the forward iterating case, it could actually go wrong all the way in the backward iterating case when using std::size_t, in case std::size_t is wider than what is the typedef of size_type):

Using std::vector

Using iterators

for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
    /* std::cout << *it; ... */

Important is, always use the prefix increment form for iterators whose definitions you don't know. That will ensure your code runs as generic as possible.

Using Range C++11

for(auto const& value: a) {
     /* std::cout << value; ... */

Using indices

for(std::vector<int>::size_type i = 0; i != v.size(); i++) {
    /* std::cout << v[i]; ... */

Using arrays

Using iterators

for(element_type* it = a; it != (a + (sizeof a / sizeof *a)); it++) {
    /* std::cout << *it; ... */

Using Range C++11

for(auto const& value: a) {
     /* std::cout << value; ... */

Using indices

for(std::size_t i = 0; i != (sizeof a / sizeof *a); i++) {
    /* std::cout << a[i]; ... */

Read in the backward iterating answer what problem the sizeof approach can yield to, though.

Delete statement in SQL is very slow

It's possible that other tables have FK constraint to your [table]. So the DB needs to check these tables to maintain the referential integrity. Even if you have all needed indexes corresponding these FKs, check their amount.

I had the situation when NHibernate incorrectly created duplicated FKs on the same columns, but with different names (which is allowed by SQL Server). It has drastically slowed down running of the DELETE statement.

SQL ORDER BY date problem

this should work for your date format

order by convert(date, your_column, 104) desc

How to force input to only allow Alpha Letters?

<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);"   required />

function alphaOnly(event) {
  var key = event.keyCode;`enter code here`
  return ((key >= 65 && key <= 90) || key == 8);

JavaScript variable assignments from tuples

You have to do it the ugly way. If you really want something like this, you can check out CoffeeScript, which has that and a whole lot of other features that make it look more like python (sorry for making it sound like an advertisement, but I really like it.)