Programs & Examples On #Dojo

Dojo Toolkit is an open source modular JavaScript library designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites. It is dual-licensed under the BSD License and the Academic Free License. Dojo uses the Asynchronous Module Definition (AMD) format for its source code, allowing completely modular web application development.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

I had the same error, but in Ubuntu 14.04 inside Windows 10 (Bash on Ubuntu on Windows). All I did to overcome the error was to update the Creators update, which then allowed me to install 16.04 version of Ubuntu bash and then after installing newest version of node (by this steps) I installed also the newest version of npm and then the nodemon started to work properly.

How to identify and switch to the frame in selenium webdriver when frame does not have id

You also can use src to switch to frame, here is what you can use:


How to export JavaScript array info to csv (on client side)?

Download CSV File

  let csvContent = "data:text/csv;charset=utf-8,";
  rows.forEach(function (rowArray) {
    for (var i = 0, len = rowArray.length; i < len; i++) {
      if (typeof (rowArray[i]) == 'string')
        rowArray[i] = rowArray[i].replace(/<(?:.|\n)*?>/gm, '');
      rowArray[i] = rowArray[i].replace(/,/g, '');

    let row = rowArray.join(",");
    csvContent += row + "\r\n"; // add carriage return
  var encodedUri = encodeURI(csvContent);
  var link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", "fileName.csv");

JavaScript code to stop form submission

Simply do it....

<!-- Your Input Elements -->

and here goes your JQuery

$(document).on('submit', 'form', function(e){
    //your code goes here
    //100% works

How to make HTML table cell editable?

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

function edit(el) {_x000D_
function disable(el) {_x000D_
<table border>_x000D_
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>_x000D_
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">_x000D_

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

Can I get the name of the currently running function in JavaScript?

Here is a one liner:

    arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '')

Like this:

    function logChanges() {
      let whoami = arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '');
      console.log(whoami + ': just getting started.');

jQuery override default validation error message display (Css) Popup/Tooltip like

If you could provide some reason as to why you need to replace the label with a div, that would certainly help...

Also, could you paste a sample that'd be helpful ( or

Remove all the children DOM elements in div

while (node.hasChildNodes()) {

How do I implement basic "Long Polling"?

I used this to get to grips with Comet, I have also set up Comet using the Java Glassfish server and found lots of other examples by subscribing to

default select option as blank

Maybe this will be helpful

    <option disabled selected value> -- select an option -- </option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>

-- select an option -- Will be displayed by default. But if you choose an option,you will not be able select it back.

You can also hide it using by adding an empty option

<option style="display:none">

so it won't show up in the list anymore.

Option 2

If you don't want to write CSS and expect the same behaviour of the solution above, just use:

<option hidden disabled selected value> -- select an option -- </option>

Comparing two dictionaries and checking how many (key, value) pairs are equal

The function is fine IMO, clear and intuitive. But just to give you (another) answer, here is my go:

def compare_dict(dict1, dict2):
    for x1 in dict1.keys():
        z = dict1.get(x1) == dict2.get(x1)
        if not z:
            print('key', x1)
            print('value A', dict1.get(x1), '\nvalue B', dict2.get(x1))

Can be useful for you or for anyone else..


I have created a recursive version of the one above.. Have not seen that in the other answers

def compare_dict(a, b):
    # Compared two dictionaries..
    # Posts things that are not equal..
    res_compare = []
    for k in set(list(a.keys()) + list(b.keys())):
        if isinstance(a[k], dict):
            z0 = compare_dict(a[k], b[k])
            z0 = a[k] == b[k]

        z0_bool = np.all(z0)
        if not z0_bool:
            print(k, a[k], b[k])
    return np.all(res_compare)

Is it possible to program Android to act as physical USB keyboard?

Most USB keyboards need drivers to run. Any keyboard functionality (non-standard buttons) beyond the capabilities of the standard HID drivers will need to install some software on the computer.

That being said, It may be possible to use Android's USB capabilities, as well as writing a custom driver if default HID is not sufficient, to achieve your goal. It is likely a very non-trivial undertaking.

Edit: I think KristopherMicinski is right that the level of control you get with the stock Android USB API is inadequate for this purpose. His two solutions of modifying the firmware to communicate using HID standards, as well as a hardware middleman that translates from the Android Accessory protocol to HID both seem valid to me. If installing drivers on the computer is out of the question, these may be the only two options.

However, if you're open to installing a driver for this behavior, It should be possible to write a custom driver that can handle Android USB protocol, and correctly translate to the correct calls/interrupts for keyboard functionality. If memory serves, every peripheral keyboard I've used in the last 10 years has needed to install a driver for full functionality, so this may not be considered non-standard behavior. (The though just occurs that this approach will only allow the device to function as a keyboard inside windows, not during the boot process)

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);

How can I convert an Integer to localized month name in Java?


Month.of( yourMonthNumber )           // Represent a month by its number, 1-12 for January-December. 
  .getDisplayName(                    // Generate text of the name of the month automatically localized. 
      TextStyle.SHORT_STANDALONE ,    // Specify how long or abbreviated the name of month should be.
      new Locale( "es" , "MX" )       // Locale determines (a) the human language used in translation, and (b) the cultural norms used in deciding issues of abbreviation, capitalization, punctuation, and so on.
  )                                   // Returns a String.


Much easier to do now in the java.time classes that supplant these troublesome old legacy date-time classes.

The Month enum defines a dozen objects, one for each month.

The months are numbered 1-12 for January-December.

Month month = Month.of( 2 );  // 2 ? February.

Ask the object to generate a String of the name of the month, automatically localized.

Adjust the TextStyle to specify how long or abbreviated you want the name. Note that in some languages (not English) the month name varies if used alone or as part of a complete date. So each text style has a …_STANDALONE variant.

Specify a Locale to determine:

  • Which human language should be used in translation.
  • What cultural norms should decide issues such as abbreviation, punctuation, and capitalization.


Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l );  // Or Locale.US, Locale.CANADA_FRENCH. 

Name ? Month object

FYI, going the other direction (parsing a name-of-month string to get a Month enum object) is not built-in. You could write your own class to do so. Here is my quick attempt at such a class. Use at your own risk. I gave this code no serious thought nor any serious testing.


Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ;  // Month.JANUARY


package com.basilbourque.example;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.time.Month;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

// For a given name of month in some language, determine the matching `java.time.Month` enum object.
// This class is the opposite of `Month.getDisplayName` which generates a localized string for a given `Month` object.
// Usage… MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ? Month.JANUARY
// Assumes `FormatStyle.FULL`, for names without abbreviation.
// About `java.time.Month` enum:
// USE AT YOUR OWN RISK. Provided without guarantee or warranty. No serious testing or code review was performed.
public class MonthDelocalizer
    private Locale locale;

    private List < String > monthNames, monthNamesStandalone; // Some languages use an alternate spelling for a “standalone” month name used without the context of a date.

    // Constructor. Private, for static factory method.
    private MonthDelocalizer ( @NotNull Locale locale )
        this.locale = locale;

        // Populate the pair of arrays, each having the translated month names.
        int countMonthsInYear = 12; // Twelve months in the year.
        this.monthNames = new ArrayList <>( countMonthsInYear );
        this.monthNamesStandalone = new ArrayList <>( countMonthsInYear );

        for ( int i = 1 ; i <= countMonthsInYear ; i++ )
            this.monthNames.add( Month.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
            this.monthNamesStandalone.add( Month.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
//        System.out.println( this.monthNames );
//        System.out.println( this.monthNamesStandalone );

    // Constructor. Private, for static factory method.
    // Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
    private MonthDelocalizer ( )
        this( Locale.getDefault() );

    // static factory method, instead of  constructors.
    // See article by Dr. Joshua Bloch.
    // The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
    synchronized static public MonthDelocalizer of ( @NotNull Locale localeArg )
        MonthDelocalizer x = new MonthDelocalizer( localeArg ); // This class could be optimized by caching this object.
        return x;

    // Attempt to translate the name of a month to look-up a matching `Month` enum object.
    // Returns NULL if the passed String value is not found to be a valid name of month for the human language and cultural norms of the `Locale` specified when constructing this parent object, `MonthDelocalizer`.
    public Month parse ( @NotNull String input )
        int index = this.monthNames.indexOf( input );
        if ( - 1 == index )
        { // If no hit in the contextual names, try the standalone names.
            index = this.monthNamesStandalone.indexOf( input );
        int ordinal = ( index + 1 );
        Month m = ( ordinal > 0 ) ? Month.of( ordinal ) : null;  // If we have a hit, determine the `Month` enum object. Else return null.
        if ( null == m )
            throw new java.lang.IllegalArgumentException( "The passed month name: ‘" + input + "’ is not valid for locale: " + this.locale.toString() );
        return m;

    // `Object` class overrides.

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

        MonthDelocalizer that = ( MonthDelocalizer ) o;

        return locale.equals( that.locale );

    public int hashCode ( )
        return locale.hashCode();

    public static void main ( String[] args )
        // Usage example:
        MonthDelocalizer monthDelocJapan = MonthDelocalizer.of( Locale.JAPAN );
            Month m = monthDelocJapan.parse( "pink elephant" ); // Invalid input.
        } catch ( IllegalArgumentException e )
            // … handle error
            System.out.println( "ERROR: " + e.getLocalizedMessage() );

        // Ignore exception. (not recommended)
        if ( MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ).equals( Month.JANUARY ) )
            System.out.println( "GOOD - In locale "+Locale.CANADA_FRENCH+", the input ‘janvier’ parses to Month.JANUARY." );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Set size of HTML page and browser window

This should work.

<!DOCTYPE html>
        <title>Hello World</title>
            html, body {
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
                background-color: green;
            #container {
                width: inherit;
                height: inherit;
                margin: 0;
                padding: 0;
                background-color: pink;
            h1 {
                margin: 0;
                padding: 0;
        <div id="container">
            <h1>Hello World</h1>

The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.

The width: inherit; height: inherit; pulls the width and height from the parent element. This should be the default and is not truly necessary.

Try removing the h1 { ... } CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1 element is influencing the layout of its container. You could prevent this by declaring overflow: hidden; on the container or the body.

I'd also suggest you do some reading on the CSS Box Model.

Iterating Through a Dictionary in Swift

If you want to iterate over all the values:

dict.values.forEach { value in
    // print(value)

Install pdo for postgres Ubuntu

PDO driver for PostgreSQL is now included in the debian package php5-dev. The above steps using Pecl no longer works.

Get connection string from App.config

string str = Properties.Settings.Default.myConnectionString; 

How to calculate md5 hash of a file using javascript

I don't believe there is a way in javascript to access the contents of a file upload. So you therefore cannot look at the file contents to generate an MD5 sum.

You can however send the file to the server, which can then send an MD5 sum back or send the file contents back .. but that's a lot of work and probably not worthwhile for your purposes.

How to find all positions of the maximum value in a list?

You can also use the numpy package:

import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))

This will return an numpy array of all the indices that contain the max value

if you want to turn this to a list:

maximum_indices_list = maximum_indices.tolist()

How to replace list item in best way

You can use the next extensions which are based on a predicate condition:

    /// <summary>
    /// Find an index of a first element that satisfies <paramref name="match"/>
    /// </summary>
    /// <typeparam name="T">Type of elements in the source collection</typeparam>
    /// <param name="this">This</param>
    /// <param name="match">Match predicate</param>
    /// <returns>Zero based index of an element. -1 if there is not such matches</returns>
    public static int IndexOf<T>(this IList<T> @this, Predicate<T> match)

        for (int i = 0; i < @this.Count; ++i)
            if (match(@this[i]))
                return i;

        return -1;

    /// <summary>
    /// Replace the first occurance of an oldValue which satisfies the <paramref name="removeByCondition"/> by a newValue
    /// </summary>
    /// <typeparam name="T">Type of elements of a target list</typeparam>
    /// <param name="this">Source collection</param>
    /// <param name="removeByCondition">A condition which decides is a value should be replaced or not</param>
    /// <param name="newValue">A new value instead of replaced</param>
    /// <returns>This</returns>
    public static IList<T> Replace<T>(this IList<T> @this, Predicate<T> replaceByCondition, T newValue)

        int index = @this.IndexOf(replaceByCondition);
        if (index != -1)
            @this[index] = newValue;

        return @this;

    /// <summary>
    /// Replace all occurance of values which satisfy the <paramref name="removeByCondition"/> by a newValue
    /// </summary>
    /// <typeparam name="T">Type of elements of a target list</typeparam>
    /// <param name="this">Source collection</param>
    /// <param name="removeByCondition">A condition which decides is a value should be replaced or not</param>
    /// <param name="newValue">A new value instead of replaced</param>
    /// <returns>This</returns>
    public static IList<T> ReplaceAll<T>(this IList<T> @this, Predicate<T> replaceByCondition, T newValue)

        for (int i = 0; i < @this.Count; ++i)
            if (replaceByCondition(@this[i]))
                @this[i] = newValue;

        return @this;

Notes: - Instead of ThrowIfArgumentIsNull extension, you can use a general approach like:

if (argName == null) throw new ArgumentNullException(nameof(argName));

So your case with these extensions can be solved as:

string targetString = valueFieldValue.ToString();
listofelements.Replace(x => x.Equals(targetString), value.ToString());

Chrome not rendering SVG referenced via <img> tag

I was able to use your sample to create a test page, and it worked just fine. My assumption is that there is something wrong with your svg file. Can you paste that here as well? Here is the sample I used.

 <svg width="100" height="100" xmlns="">
   <!-- Created with SVG-edit - -->
      <title>Layer 1</title>
      <ellipse ry="30" rx="30" id="svg_1" cy="50" cx="50" stroke-width="5" stroke="#000000" fill="#FF0000"/>

How do I setup the InternetExplorerDriver so it works

Here is the exact solution, which worked in my case:

  1. On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, "Enhanced Protected Mode" must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog.

  2. System.setProperty("","C:\\Users\\ssin22\\Downloads\\IEDriverServer_x64_2.48.0\\IEDriverServer.exe");

package Testing;


import org.openqa.selenium.WebDriver;

public class LaunchIE {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


    WebDriver driver=new InternetExplorerDriver();



Python: Best way to add to sys.path relative to the current running script

I see a shebang in your example. If you're running your bin scripts as ./bin/, rather than python ./bin/, there's an option of using the shebang to change $PYTHONPATH variable.

You can't change environment variables directly in shebangs though, so you'll need a small helper script. Put this into your bin folder:

#!/usr/bin/env bash
export PYTHONPATH=$PWD/lib
exec "/usr/bin/python" "$@"

And then change the shebang of your ./bin/ to be #!bin/

Pick a random value from an enum?

This is probably the most concise way of achieving your goal.All you need to do is to call Letter.getRandom() and you will get a random enum letter.

public enum Letter {

    public static Letter getRandom() {
        return values()[(int) (Math.random() * values().length)];

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

Removing some unnecessary SQL and then COUNT(*) will be faster than SQL_CALC_FOUND_ROWS. Example:

SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name

Then count without unnecessary part:

FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'

How to use both onclick and target="_blank"

The method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");



onclick="Javascript: openYourRequiredPage()"

You can use




As you wish

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

How to concatenate a std::string and an int?

The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:

#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
    static_cast<std::ostringstream&>(          \
        std::ostringstream().flush() << tokens \
    ).str()                                    \

Now you can format strings like this:

int main() {
    int i = 123;
    std::string message = MAKE_STRING("i = " << i);
    std::cout << message << std::endl; // prints: "i = 123"

Cannot add a project to a Tomcat server in Eclipse

If you are able to see the project in Eclipse project explorer but unable to see the project while adding the project to the web server, follow project properties -> Project Facets, make sure Dynamic Web Module & Java were ticked.

Onchange open URL via select - jQuery

**redirect on change option with jquery** 

 <select id="selectnav1" class="selectnav">
            <option value="#">Menu </option>
            <option value="">
            <option value="">


<script type="text/javascript">
   $(function () {

        $('#selectnav1').change( function() {
      location.href = $(this).val();

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Getting values from JSON using Python

Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.

data = json.loads('{"lat":444, "lon":555}')
    ret = ''
    for j in data:
        ret = ret+" "+data[j]
return ret

When you use for in this manor you get the key of the object, not the value, so you can get the value, by using the key as an index.

Switching to a TabBar tab view programmatically?

For cases where you may be moving the tabs, here is some code.

for ( UINavigationController *controller in self.tabBarController.viewControllers ) {
            if ( [[controller.childViewControllers objectAtIndex:0] isKindOfClass:[MyViewController class]]) {
                [self.tabBarController setSelectedViewController:controller];

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here:

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text =,
        words = text.text().split(/\s+/).reverse(),
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:


For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    Scanner scan = new Scanner(;

    int number = 0;

    //Run once and loop until the input is within the specified range.
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;

What's the difference between Docker Compose vs. Dockerfile


enter image description here

A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.

Example, Dockerfile

FROM ubuntu:latest
MAINTAINER john doe 

RUN apt-get update
RUN apt-get install -y python python-pip wget
RUN pip install Flask

ADD /home/


Docker Compose

enter image description here

Docker Compose

  • is a tool for defining and running multi-container Docker applications.

  • define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.

  • get an app running in one command by just running docker-compose up

Example, docker-compose.yml

version: "3"
    build: .
    - '5000:5000'
    - .:/code
    - logvolume01:/var/log
    - redis
    image: redis
      logvolume01: {}

How do I kill background processes / jobs when my shell script exits?

Another option is it to have the script set itself as the process group leader, and trap a killpg on your process group on exit.

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

How can I create a temp file with a specific extension with .NET?

This is a simple but effective way to generate incremental filenames. It will look in the current directly (you can easily point that somewhere else) and search for files with the base YourApplicationName*.txt (again you can easily change that). It will start at 0000 so that the first file name will be YourApplicationName0000.txt. if for some reason there are file names with junk between (meaning not numbers) the left and right parts, those files will be ignored by virtue of the tryparse call.

    public static string CreateNewOutPutFile()
        const string RemoveLeft = "YourApplicationName";
        const string RemoveRight = ".txt";
        const string searchString = RemoveLeft + "*" + RemoveRight;
        const string numberSpecifier = "0000";

        int maxTempNdx = -1;

        string fileName;
        string [] Files = Directory.GetFiles(Directory.GetCurrentDirectory(), searchString);
        foreach( string file in Files)
            fileName = Path.GetFileName(file);
            string stripped = fileName.Remove(fileName.Length - RemoveRight.Length, RemoveRight.Length).Remove(0, RemoveLeft.Length);
            if( int.TryParse(stripped,out int current) )
                if (current > maxTempNdx)
                    maxTempNdx = current;
        fileName = RemoveLeft + maxTempNdx.ToString(numberSpecifier) + RemoveRight;
        File.CreateText(fileName); // optional
        return fileName;

Output (echo/print) everything from a PHP Array

Similar to karim's, but with print_r which has a much small output and I find is usually all you need:

function PrintR($var) {
    echo '<pre>';
    echo '</pre>';

Refused to execute script, strict MIME type checking is enabled?

Python flask

On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.

Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript

C:\>reg query HKCR\.js /v "Content Type"

    Content Type    REG_SZ    text/javascript

Converting BitmapImage to Bitmap and vice versa

Here the async version.

public static Task<BitmapSource> ToBitmapSourceAsync(this Bitmap bitmap)
    return Task.Run(() =>
        using (System.IO.MemoryStream memory = new System.IO.MemoryStream())
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            return bitmapImage as BitmapSource;


How to align an input tag to the center without specifying the width?

You can also use the tag, this works in divs and everything else:


This link will help you with the tag:

Why is the <center> tag deprecated in HTML?

How do I set the maximum line length in PyCharm?

You can even set a separate right margin for HTML. Under the specified path:

File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)

This is very useful because generally HTML and JS may be usually long in one line than Python. :)

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Can I convert long to int?

It can convert by

Convert.ToInt32 method

But it will throw an OverflowException if it the value is outside range of the Int32 Type. A basic test will show us how it works:

long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
   try {
         result = Convert.ToInt32(number);
        Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
                    number.GetType().Name, number,
                    result.GetType().Name, result);
     catch (OverflowException) {
      Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
                    number.GetType().Name, number);
// The example displays the following output:
//    The Int64 value -9223372036854775808 is outside the range of the Int32 type.
//    Converted the Int64 value -1 to the Int32 value -1.
//    Converted the Int64 value 0 to the Int32 value 0.
//    Converted the Int64 value 121 to the Int32 value 121.
//    Converted the Int64 value 340 to the Int32 value 340.
//    The Int64 value 9223372036854775807 is outside the range of the Int32 type.

Here there is a longer explanation.

Trigger standard HTML5 validation (form) without using submit button?

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:


Then just call $('#theIdOfMyForm').submit(); in your code.


If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function()
        // break
        return false;

It will give focus on the first invalid input.

How to execute two mysql queries as one in PHP/MYSQL?

You have to use MySQLi, below code works well

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
        /* print divider */
        if ($mysqli->more_results()) {
    } while ($mysqli->next_result());

/* close connection */

Java generics - why is "extends T" allowed but not "implements T"?

There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).

How to match "any character" in regular expression?

I work this Not always dot is means any char. Exception when single line mode. \p{all} should be

String value = "|°¬<>!\"#$%&/()=?'\\¡¿/*-+_@[]^^{}";
String expression = "[a-zA-Z0-9\\p{all}]{0,50}";
} else {

How to programmatically clear application data

This way added by Sebastiano was OK, but it's necessary, when you run tests from i.e. IntelliJ IDE to add:

 try {
    // clearing app data
    Runtime runtime = Runtime.getRuntime();
    runtime.exec("adb shell pm clear YOUR_APP_PACKAGE_GOES HERE");


instead of only "pm package..."

and more important: add it before driver.setCapability(App_package, package_name).

How can I tell if a VARCHAR variable contains a substring?

The standard SQL way is to use like:

where @stringVar like '%thisstring%'

That is in a query statement. You can also do this in TSQL:

if @stringVar like '%thisstring%'

Is it possible to put CSS @media rules inline?

No, @media rules and media queries cannot exist in inline style attributes as they can only contain property: value declarations. As the spec puts it:

The value of the style attribute must match the syntax of the contents of a CSS declaration block

The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.

A dummy span selector would look like this, but if you're targeting a very specific element you will need a more specific selector:

span { background-image: url(particular_ad.png); }

@media (max-width: 300px) {
    span { background-image: url(particular_ad_small.png); }

How do I create a datetime in Python from milliseconds?

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta

as mentioned in the Python standard lib:

fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here


The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

What is the difference between MVC and MVVM?

Injecting Strongly Typed ViewModels into the View using MVC

  1. The controller is responsible for newing up the ViewModel and injecting it into the View. (for get requests)
  2. The ViewModel is the container for DataContext and view state such as the last selected item etc.
  3. The Model contains DB entities and is very close to the DB Schema it does the queries and filtering. (I like EF and LINQ for this)
  4. The Model should also consider repositories and or projection of results into strong types (EF has a great method... EF.Database.Select(querystring, parms) for direct ADO access to inject queries and get back strong types. This addresses the EF is slow argument. EF is NOT SLOW!
  5. The ViewModel gets the data and does the business rules and validation
  6. The controller on post back will cal the ViewModel Post method and wait for results.
  7. The controller will inject the newly updated Viewmodel to the View. The View uses only strong type binding.
  8. The view merely renders the data, and posts events back to the controller. (see examples below)
  9. MVC intercepts the inbound request and routes it to proper controller with strong data type

In this model there is no more HTTP level contact with the request or response objects as MSFT's MVC machine hides it from us.

In clarification of item 6 above (by request)...

Assume a ViewModel like this:

public class myViewModel{
     public string SelectedValue {get;set;}
public void Post(){
    //due to MVC model binding the SelectedValue string above will be set by MVC model binding on post back.
    //this allows you to do something with it.
    SelectedValue = "Thanks for update!";

The controller method of the post will look like this (See below), note that the instance of mvm is automatically instanciated by the MVC binding mechanisms. You never have to drop down to the query string layer as a result! This is MVC instantiating the ViewModel for you based on the query strings!

public ActionResult MyPostBackMethod (myViewModel mvm){
         if (ModelState.IsValid)
               // Immediately call the only method needed in VM...
      return View(mvm);

Note that in order for this actionmethod above to work as you intend, you must have a null CTOR defined that intializes things not returned in the post. The post back must also post back name/value pairs for those things which changed. If there are missing name/value pairs the MVC binding engine does the proper thing which is simply nothing! If this happens you might find yourself saying "I'm losing data on post backs"...

The advantage of this pattern is the ViewModel does all the "clutter" work interfacing to the Model/Buisness logic, the controller is merely a router of sorts. It is SOC in action.

What is the Linux equivalent to DOS pause?

read without any parameters will only continue if you press enter. The DOS pause command will continue if you press any key. Use read –n1 if you want this behaviour.

Find the host name and port using PSQL commands

service postgresql status

returns: 10/main (port 5432): online

I'm running Ubuntu 18.04

get the value of DisplayName attribute

Try these utility methods of mine:

using System.ComponentModel;
using System.Globalization;
using System.Linq;

public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
    where T : Attribute
    var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();

    if (attribute == null && isRequired)
        throw new ArgumentException(
                "The {0} attribute must be defined on member {1}", 

    return (T)attribute;

public static string GetPropertyDisplayName<T>(Expression<Func<T, object>> propertyExpression)
    var memberInfo = GetPropertyInformation(propertyExpression.Body);
    if (memberInfo == null)
        throw new ArgumentException(
            "No property reference expression was found.",

    var attr = memberInfo.GetAttribute<DisplayNameAttribute>(false);
    if (attr == null)
        return memberInfo.Name;

    return attr.DisplayName;

public static MemberInfo GetPropertyInformation(Expression propertyExpression)
    Debug.Assert(propertyExpression != null, "propertyExpression != null");
    MemberExpression memberExpr = propertyExpression as MemberExpression;
    if (memberExpr == null)
        UnaryExpression unaryExpr = propertyExpression as UnaryExpression;
        if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Convert)
            memberExpr = unaryExpr.Operand as MemberExpression;

    if (memberExpr != null && memberExpr.Member.MemberType == MemberTypes.Property)
        return memberExpr.Member;

    return null;

Usage would be:

string displayName = ReflectionExtensions.GetPropertyDisplayName<SomeClass>(i => i.SomeProperty);

Link to reload current page

Completely idempotent url that preserves path, parameters, and anchor.

 <a href="javascript:"> click me </a>

it only uses a little tiny bit of JS.

EDIT: this does not reload the page. It is a link that does nothing.

What is "entropy and information gain"?

As you are reading a book about NLTK it would be interesting you read about MaxEnt Classifier Module

For text mining classification the steps could be: pre-processing (tokenization, steaming, feature selection with Information Gain ...), transformation to numeric (frequency or TF-IDF) (I think that this is the key step to understand when using text as input to a algorithm that only accept numeric) and then classify with MaxEnt, sure this is just an example.

How to convert timestamp to datetime in MySQL?

DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`

This is the ultimate solution if the given date is in encoded format like 1300464000

Renaming columns in Pandas

Just assign it to the .columns attribute:

>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
   $a  $b
0   1  10
1   2  20

>>> df.columns = ['a', 'b']
>>> df
   a   b
0  1  10
1  2  20

Add placeholder text inside UITextView in Swift?

I did this by using two different text views:

  1. One in the background that is used as a placeholder.
  2. One in the foreground (with a transparent background) that the user actually types in.

The idea is that once the user starts typing stuff in the foreground view, the placeholder in the background disappears (and reappears if the user deletes everything). So it behaves exactly like a placeholder for the single line text field.

Here's the code I used for it. Note that descriptionField is the field the user types in and descriptionPlaceholder is the one in the background.

func textViewDidChange(descriptionField: UITextView) {
    if descriptionField.text.isEmpty == false {
        descriptionPlaceholder.text = ""
    } else {
        descriptionPlaceholder.text = descriptionPlaceholderText

How can I close a dropdown on click outside?

You can use (document:click) event:

  host: {
    '(document:click)': 'onClick($event)',
class SomeComponent() {
  constructor(private _eref: ElementRef) { }

  onClick(event) {
   if (!this._eref.nativeElement.contains( // or some similar check

Another approach is to create custom event as a directive. Check out these posts by Ben Nadel:

How to get Database Name from Connection String using SqlConnectionStringBuilder

See MSDN documentation for InitialCatalog Property:

Gets or sets the name of the database associated with the connection...

This property corresponds to the "Initial Catalog" and "database" keys within the connection string...

What is a reasonable length limit on person "Name" fields?

I know I'm late on this one, but I'll add this comment anyway, as others may well come here in the future with similar questions.

Beware of tweaking column sizes dependent on locale. For a start, it sets you up for a maintenance nightmare, leaving aside the fact that people migrate, and take their names with them.

For example, Spanish people with those extra surnames can move to and live in an English-speaking country, and can reasonably expect their full name to be used. Russians have patronymics in addition to their surnames, some African names can be considerably longer than most European names.

Go with making each column as wide as you can reasonably do, taking into account the potential row count. I use 40 characters each for first name, other given names and surname and have never found any problems.

CSS Circular Cropping of Rectangle Image

The object-fit property provides a non-hackish way for doing this (with image centered). It has been supported in major browsers for a few years now (Chrome/Safari since 2013, Firefox since 2015, and Edge since 2015) with the exception of Internet Explorer.

img.rounded {_x000D_
  object-fit: cover;_x000D_
  border-radius: 50%;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
<img src="" class="rounded">

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

How to validate numeric values which may contain dots or commas?

Shortest regexp I know (16 char)


The ^ and $ means begin and end of input string (without this part 23.45 of string like 123.45 will be matched). The \d means digit, the \d? means optional digit, the [,.] means dot or comma. Working example (when you click on left menu> tools> code generator you can gen code for one of 9 popular languages like c#, js, php, java, ...) here.

  // valid
  // nonvalid
].forEach(n=> {
  let result = /^\d\d?[,.]\d\d?$/.test(n);
  console.log(`${n}`.padStart(6,' '), 'is valid:', result);

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

You can specify the latest version of ruby by looking at

  1. Fetch the latest version:

    curl -sSL | bash -s stable --ruby

  2. Install it:

    rvm install 2.2

  3. Use it as default:

    rvm use 2.2 --default

Or run the latest command from ruby:

rvm install ruby --latest
rvm use 2.2 --default

How to debug Apache mod_rewrite

The LogRewrite directive as mentioned by Ben is not available anymore in Apache 2.4. You need to use the LogLevel directive instead. E.g.

LogLevel alert rewrite:trace6


PHP 5 disable strict standards error

The default value of error_reporting flag is E_ALL & ~E_NOTICE if not set in php.ini. But in some installation (particularly installations targeting development environments) has E_ALL | E_STRICT set as value of this flag (this is the recommended value during development). In some cases, specially when you'll want to run some open source projects, that was developed prior to PHP 5.3 era and not yet updated with best practices defined by PHP 5.3, in your development environment, you'll probably run into getting some messages like you are getting. The best way to cope up on this situation, is to set only E_ALL as the value of error_reporting flag, either in php.ini or in code (probably in a front-controller like index.php in web-root as follows:


How to stop/shut down an elasticsearch node?

If you just want to apply new config you don't need to shut it down.

$ sudo service elasticsearch restart

But if you want to shut it down anyway:

$ sudo service elasticsearch stop


$ sudo systemctl stop elasticsearch.service

$ sudo systemctl restart elasticsearch.service


docker restart <elasticsearch-container-name or id>

How to encode a string in JavaScript for displaying in HTML?

The only character that needs escaping is <. (> is meaningless outside of a tag).

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

for anyone who comes across this problem now, with android studio 4.0+ you just have to enable java 8 as mentioned here

android {
    defaultConfig {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

... then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.

Using Mockito's generic "any()" method

This should work

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;


Display HTML form values in same page after submit using Ajax

Here is one way to do it.

<!DOCTYPE html>
  <head lang="en">
  <meta charset="UTF-8">
  <script language="JavaScript">
    function showInput() {
        document.getElementById('display').innerHTML = 


    <label><b>Enter a Message</b></label>
    <input type="text" name="message" id="user_input">

  <input type="submit" onclick="showInput();"><br/>
  <label>Your input: </label>
  <p><span id='display'></span></p>

And this is what it looks like when run.Cheers.

enter image description here

npm - EPERM: operation not permitted on Windows

I use Windows 10. I started the CMD as administrator, and it solved the problem.

Find CMD, right click, and click open as administrator.

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')

Or use textvariable option:

    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)

How to overwrite styling in Twitter Bootstrap

I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css file was written after the media queries. when I moved it above media queries it started working.

Just in case someone else is facing the same problem

What does the 'standalone' directive mean in XML?

  • The standalone directive is an optional attribute on the XML declaration.
  • Valid values are yes and no, where no is the default value.
  • The attribute is only relevant when a DTD is used. (The attribute is irrelevant when using a schema instead of a DTD.)
  • standalone="yes" means that the XML processor must use the DTD for validation only. In that case it will not be used for:
    • default values for attributes
    • entity declarations
    • normalization
  • Note that standalone="yes" may add validity constraints if the document uses an external DTD. When the document contains things that would require modification of the XML, such as default values for attributes, and standalone="yes" is used then the document is invalid.
  • standalone="yes" may help to optimize performance of document processing.

Source: The standalone pseudo-attribute is only relevant if a DTD is used

How to change JFrame icon

Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.

Here's what worked for me:

import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;

frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')

Remove by _id in MongoDB console

Very close. This will work:

db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});

i.e. you don't need a new for the ObjectId.

Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

How can I get the name of an object in Python?

This one-liner works, for all types of objects, as long as they are in globals() dict, which they should be:

def name_of_global_obj(xx):
    return [objname for objname, oid in globals().items()
            if id(oid)==id(xx)][0]

or, equivalently:

def name_of_global_obj(xx):
    for objname, oid in globals().items():
        if oid is xx:
            return objname

What are Aggregates and PODs and how/why are they special?

POD in C++11 was basically split into two different axes here: triviality and layout. Triviality is about the relationship between an object's conceptual value and the bits of data within its storage. Layout is about... well, the layout of an object's subobjects. Only class types have layout, while all types have triviality relationships.

So here is what the triviality axis is about:

  1. Non-trivially copyable: The value of objects of such types may be more than just the binary data that are stored directly within the object.

    For example, unique_ptr<T> stores a T*; that is the totality of the binary data within the object. But that's not the totality of the value of a unique_ptr<T>. A unique_ptr<T> stores either a nullptr or a pointer to an object whose lifetime is managed by the unique_ptr<T> instance. That management is part of the value of a unique_ptr<T>. And that value is not part of the binary data of the object; it is created by the various member functions of that object.

    For example, to assign nullptr to a unique_ptr<T> is to do more than just change the bits stored in the object. Such an assignment must destroy any object managed by the unique_ptr. To manipulate the internal storage of a unique_ptr without going through its member functions would damage this mechanism, to change its internal T* without destroying the object it currently manages, would violate the conceptual value that the object possesses.

  2. Trivially copyable: The value of such objects are exactly and only the contents of their binary storage. This is what makes it reasonable to allow copying that binary storage to be equivalent to copying the object itself.

    The specific rules that define trivial copyability (trivial destructor, trivial/deleted copy/move constructors/assignment) are what is required for a type to be binary-value-only. An object's destructor can participate in defining the "value" of an object, as in the case with unique_ptr. If that destructor is trivial, then it doesn't participate in defining the object's value.

    Specialized copy/move operations also can participate in an object's value. unique_ptr's move constructor modifies the source of the move operation by null-ing it out. This is what ensures that the value of a unique_ptr is unique. Trivial copy/move operations mean that such object value shenanigans are not being played, so the object's value can only be the binary data it stores.

  3. Trivial: This object is considered to have a functional value for any bits that it stores. Trivially copyable defines the meaning of the data store of an object as being just that data. But such types can still control how data gets there (to some extent). Such a type can have default member initializers and/or a default constructor that ensures that a particular member always has a particular value. And thus, the conceptual value of the object can be restricted to a subset of the binary data that it could store.

    Performing default initialization on a type that has a trivial default constructor will leave that object with completely uninitialized values. As such, a type with a trivial default constructor is logically valid with any binary data in its data storage.

The layout axis is really quite simple. Compilers are given a lot of leeway in deciding how the subobjects of a class are stored within the class's storage. However, there are some cases where this leeway is not necessary, and having more rigid ordering guarantees is useful.

Such types are standard layout types. And the C++ standard doesn't even really do much with saying what that layout is specifically. It basically says three things about standard layout types:

  1. The first subobject is at the same address as the object itself.

  2. You can use offsetof to get a byte offset from the outer object to one of its member subobjects.

  3. unions get to play some games with accessing subobjects through an inactive member of a union if the active member is (at least partially) using the same layout as the inactive one being accessed.

Compilers generally permit standard layout objects to map to struct types with the same members in C. But there is no statement of that in the C++ standard; that's just what compilers feel like doing.

POD is basically a useless term at this point. It is just the intersection of trivial copyability (the value is only its binary data) and standard layout (the order of its subobjects is more well-defined). One can infer from such things that the type is C-like and could map to similar C objects. But the standard has no statements to that effect.

can you please elaborate following rules:

I'll try:

a) standard-layout classes must have all non-static data members with the same access control

That's simple: all non-static data members must all be public, private, or protected. You can't have some public and some private.

The reasoning for them goes to the reasoning for having a distinction between "standard layout" and "not standard layout" at all. Namely, to give the compiler the freedom to choose how to put things into memory. It's not just about vtable pointers.

Back when they standardized C++ in 98, they had to basically predict how people would implement it. While they had quite a bit of implementation experience with various flavors of C++, they weren't certain about things. So they decided to be cautious: give the compilers as much freedom as possible.

That's why the definition of POD in C++98 is so strict. It gave C++ compilers great latitude on member layout for most classes. Basically, POD types were intended to be special cases, something you specifically wrote for a reason.

When C++11 was being worked on, they had a lot more experience with compilers. And they realized that... C++ compiler writers are really lazy. They had all this freedom, but they didn't do anything with it.

The rules of standard layout are more or less codifying common practice: most compilers didn't really have to change much if anything at all to implement them (outside of maybe some stuff for the corresponding type traits).

Now, when it came to public/private, things are different. The freedom to reorder which members are public vs. private actually can matter to the compiler, particularly in debugging builds. And since the point of standard layout is that there is compatibility with other languages, you can't have the layout be different in debug vs. release.

Then there's the fact that it doesn't really hurt the user. If you're making an encapsulated class, odds are good that all of your data members will be private anyway. You generally don't expose public data members on fully encapsulated types. So this would only be a problem for those few users who do want to do that, who want that division.

So it's no big loss.

b) only one class in the whole inheritance tree can have non-static data members,

The reason for this one comes back to why they standardized standard layout again: common practice.

There's no common practice when it comes to having two members of an inheritance tree that actually store things. Some put the base class before the derived, others do it the other way. Which way do you order the members if they come from two base classes? And so on. Compilers diverge greatly on these questions.

Also, thanks to the zero/one/infinity rule, once you say you can have two classes with members, you can say as many as you want. This requires adding a lot of layout rules for how to handle this. You have to say how multiple inheritance works, which classes put their data before other classes, etc. That's a lot of rules, for very little material gain.

You can't make everything that doesn't have virtual functions and a default constructor standard layout.

and the first non-static data member cannot be of a base class type (this could break aliasing rules).

I can't really speak to this one. I'm not educated enough in C++'s aliasing rules to really understand it. But it has something to do with the fact that the base member will share the same address as the base class itself. That is:

struct Base {};
struct Derived : Base { Base b; };

Derived d;
static_cast<Base*>(&d) == &d.b;

And that's probably against C++'s aliasing rules. In some way.

However, consider this: how useful could having the ability to do this ever actually be? Since only one class can have non-static data members, then Derived must be that class (since it has a Base as a member). So Base must be empty (of data). And if Base is empty, as well as a base class... why have a data member of it at all?

Since Base is empty, it has no state. So any non-static member functions will do what they do based on their parameters, not their this pointer.

So again: no big loss.

How do I create a folder in a GitHub repository?

Create a new file, and then on the filename use slash. For example


NSOperation vs Grand Central Dispatch

In line with my answer to a related question, I'm going to disagree with BJ and suggest you first look at GCD over NSOperation / NSOperationQueue, unless the latter provides something you need that GCD doesn't.

Before GCD, I used a lot of NSOperations / NSOperationQueues within my applications for managing concurrency. However, since I started using GCD on a regular basis, I've almost entirely replaced NSOperations and NSOperationQueues with blocks and dispatch queues. This has come from how I've used both technologies in practice, and from the profiling I've performed on them.

First, there is a nontrivial amount of overhead when using NSOperations and NSOperationQueues. These are Cocoa objects, and they need to be allocated and deallocated. In an iOS application that I wrote which renders a 3-D scene at 60 FPS, I was using NSOperations to encapsulate each rendered frame. When I profiled this, the creation and teardown of these NSOperations was accounting for a significant portion of the CPU cycles in the running application, and was slowing things down. I replaced these with simple blocks and a GCD serial queue, and that overhead disappeared, leading to noticeably better rendering performance. This wasn't the only place where I noticed overhead from using NSOperations, and I've seen this on both Mac and iOS.

Second, there's an elegance to block-based dispatch code that is hard to match when using NSOperations. It's so incredibly convenient to wrap a few lines of code in a block and dispatch it to be performed on a serial or concurrent queue, where creating a custom NSOperation or NSInvocationOperation to do this requires a lot more supporting code. I know that you can use an NSBlockOperation, but you might as well be dispatching something to GCD then. Wrapping this code in blocks inline with related processing in your application leads in my opinion to better code organization than having separate methods or custom NSOperations which encapsulate these tasks.

NSOperations and NSOperationQueues still have very good uses. GCD has no real concept of dependencies, where NSOperationQueues can set up pretty complex dependency graphs. I use NSOperationQueues for this in a handful of cases.

Overall, while I usually advocate for using the highest level of abstraction that accomplishes the task, this is one case where I argue for the lower-level API of GCD. Among the iOS and Mac developers I've talked with about this, the vast majority choose to use GCD over NSOperations unless they are targeting OS versions without support for it (those before iOS 4.0 and Snow Leopard).

How can I install a CPAN module into a local directory?

Other answers already on Stackoverflow:

From perlfaq8:

How do I keep my own module/library directory?

When you build modules, tell Perl where to install the modules.

For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:

perl Makefile.PL INSTALL_BASE=/mydir/perl

You can set this in your configuration so modules automatically install in your private library directory when you use the shell:

% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit

For Build.PL-based distributions, use the --install_base option:

perl Build.PL --install_base /mydir/perl

You can configure to automatically use this option too:

% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

CSS height 100% percent not working

I would say you have two options:

  1. to get all parent divs styled with 100% height (including body and html)

  2. to use absolute positioning for one of the parent divs (for example #content) and then all child divs set to height 100%

Convert wchar_t to char

A short function I wrote a while back to pack a wchar_t array into a char array. Characters that aren't on the ANSI code page (0-127) are replaced by '?' characters, and it handles surrogate pairs correctly.

size_t to_narrow(const wchar_t * src, char * dest, size_t dest_len){
  size_t i;
  wchar_t code;

  i = 0;

  while (src[i] != '\0' && i < (dest_len - 1)){
    code = src[i];
    if (code < 128)
      dest[i] = char(code);
      dest[i] = '?';
      if (code >= 0xD800 && code <= 0xD8FF)
        // lead surrogate, skip the next code unit, which is the trail

  dest[i] = '\0';

  return i - 1;


Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

I had the same problem

I fixed that by using two options

contentType: false
processData: false

Actually I Added these two command to my $.ajax({}) function

Calculate the execution time of a method

StopWatch will use the high-resolution counter

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

If you're measuring IO then your figures will likely be impacted by external events, and I would worry so much re. exactness (as you've indicated above). Instead I'd take a range of measurements and consider the mean and distribution of those figures.

Change multiple files

I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:

find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

calculating the difference in months between two dates

You won't be able to get that from a TimeSpan, because a "month" is a variable unit of measure. You'll have to calculate it yourself, and you'll have to figure out how exactly you want it to work.

For example, should dates like July 5, 2009 and August 4, 2009 yield one month or zero months difference? If you say it should yield one, then what about July 31, 2009 and August 1, 2009? Is that a month? Is it simply the difference of the Month values for the dates, or is it more related to an actual span of time? The logic for determining all of these rules is non-trivial, so you'll have to determine your own and implement the appropriate algorithm.

If all you want is simply a difference in the months--completely disregarding the date values--then you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
    return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);

Note that this returns a relative difference, meaning that if rValue is greater than lValue, then the return value will be negative. If you want an absolute difference, you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
    return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));

Remove last character from C++ string

int main () {

  string str1="123";
  string str2 = str1.substr (0,str1.length()-1);

  cout<<str2; // output: 12

  return 0;

Undo a merge by pull request?

Starting June 24th, 2014, you can try cancel a PR easily (See "Reverting a pull request") with:

Introducing the Revert Button

you can easily revert a pull request on GitHub by clicking Revert:

You'll be prompted to create a new pull request with the reverted changes:

It remains to be tested though if that revert uses -m or not (for reverting merges as well)

But Adil H Raza adds in the comments (Dec. 2019):

That is the expected behavior, it created a new branch and you can create a PR from this new branch to your master.
This way in the future you can un-revert the revert if need be, it is safest option and not directly changing your master.

Warning: Korayem points out in the comments that:

After a revert, let's say you did some further changes on Git branch and created a new PR from same source/destination branch.
You will find the PR showing only new changes, but nothing of what was there before reverting.

Korayem refers us to "Github: Changes ignored after revert (git cherry-pick, git rebase)" for more.

Globally catch exceptions in a WPF application?

Here is complete example using NLog

using NLog;
using System;
using System.Windows;

namespace MyApp
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public App()
            var currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += CurrentDomain_UnhandledException;

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            var ex = (Exception)e.ExceptionObject;
            logger.Error("UnhandledException caught : " + ex.Message);
            logger.Error("UnhandledException StackTrace : " + ex.StackTrace);
            logger.Fatal("Runtime terminating: {0}", e.IsTerminating);


What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

How often does python flush to a file?

For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.

For example, the open function takes a buffer size argument.

"The optional buffering argument specifies the file’s desired buffer size:"

  • 0 means unbuffered,
  • 1 means line buffered,
  • any other positive value means use a buffer of (approximately) that size.
  • A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files.
  • If omitted, the system default is used.


bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)

Best database field type for a URL

varchar(max) for SQLServer2005

varchar(65535) for MySQL 5.0.3 and later

This will allocate storage as need and shouldn't affect performance.

AttributeError("'str' object has no attribute 'read'")

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Difference between a script and a program?

There are really two dimensions to the scripting vs program reality:

  1. Is the language powerful enough, particularly with string operations, to compete with a macro processor like the posix shell and particularly bash? If it isn't better than bash for running some function there isn't much point in using it.

  2. Is the language convenient and quickly started? Java, Scala, JRuby, Closure and Groovy are all powerful languages, but Java requires a lot of boilerplate and the JVM they all require just takes too long to start up.

OTOH, Perl, Python, and Ruby all start up quickly and have powerful string handling (and pretty much everything-else-handling) operations, so they tend to occupy the sometimes-disparaged-but-not-easily-encroached-upon "scripting" world. It turns out they do well at running entire traditional programs as well.

Left in limbo are languages like Javascript, which aren't used for scripting but potentially could be. Update: since this was written node.js was released on multiple platforms. In other news, the question was closed. "Oh well."

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height

Replace None with NaN in pandas dataframe

If you use df.replace([None], np.nan, inplace=True), this changed all datetime objects with missing data to object dtypes. So now you may have broken queries unless you change them back to datetime which can be taxing depending on the size of your data.

If you want to use this method, you can first identify the object dtype fields in your df and then replace the None:

obj_columns = list(df.select_dtypes(include=['object']).columns.values)
df[obj_columns] = df[obj_columns].replace([None], np.nan)

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:


    echo "<p>Logged in as ".$user."</p>";
    echo "Please log in.";

How the same problem can be solved with an API centric approach by outputting JSON like this:


  user: {
      username: 'Joe', 
      securityToken: 'secret'

and in Angular you could do a get, and handle the response client side.

$"", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How can I trim leading and trailing white space?

The best method is trimws().

The following code will apply this function to the entire dataframe.

mydataframe<- data.frame(lapply(mydataframe, trimws),stringsAsFactors = FALSE)

How can I convert a zero-terminated byte array to string?

  • Use slices instead of arrays for reading. For example, io.Reader accepts a slice, not an array.

  • Use slicing instead of zero padding.


buf := make([]byte, 100)
n, err := myReader.Read(buf)
if n == 0 && err != nil {

consume(buf[:n]) // consume() will see an exact (not padded) slice of read data

Remove ALL styling/formatting from hyperlinks

You can simply define a style for links, which would override a:hover, a:visited etc.:

a {
  color: blue;
  text-decoration: none; /* no underline */

You can also use the inherit value if you want to use attributes from parent styles instead:

body {
  color: blue;
a {
  color: inherit; /* blue colors for links too */
  text-decoration: inherit; /* no underline */

How to reload apache configuration for a site without restarting apache?

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.


java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

IndentationError: unexpected indent error

The error is pretty straightforward - the line starting with check_exists_sql isn't indented properly. From the context of your code, I'd indent it and the following lines to match the line before it:

   #open db connection
   db = MySQLdb.connect("localhost","root","str0ng","TESTDB")

   #prepare a cursor object using cursor() method
   cursor = db.cursor()

   #see if any links in the DB match the crawled link
   check_exists_sql = "SELECT * FROM LINKS WHERE link = '%s' LIMIT 1" % item['link']


And keep indenting it until the for loop ends (all the way through to and including items.append(item).

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    //output the full :not() rule including all ignored items
    &#{$notOutput} {

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/

Option 2: list the ignored items in a variable first


input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = '';

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

Postgres Error: More than one row returned by a subquery used as an expression

This error means that the SELECT store_key FROM store query has returned two or more rows in the SERVER1 database. If you would like to update all customers, use a join instead of a scalar = operator. You need a condition to "connect" customers to store items in order to do that.

If you wish to update all customer_ids to the same store_key, you need to supply a WHERE clause to the remotely executed SELECT so that the query returns a single row.

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <p>Hello and welcome to my website.</p>
        <div class="span6">
            Image Here (TODO)

Visit this link: and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <p>Hello and welcome to my website.</p>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>

Creating virtual directories in IIS express

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
   <application path="/OffSiteStuff" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="d:\temp\SubFolderApp" />
      <binding protocol="http" bindingInformation="*:1132:localhost" />

Practically you need to add a new application tag in your site for each virtual directory. You get a lot of flexibility because you can set different configuration for the virtual directory (for example a different .Net Framework version)

EDIT Thanks to Fevzi Apaydin to point to a more elegant solution.

You can achieve same result by adding one or more virtualDirectory tag to the Application tag:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
      <binding protocol="http" bindingInformation="*:1132:localhost" />


What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:

IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

public ActionResult actionName(int reportID)

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

Returning JSON object as response in Spring Boot

More correct create DTO for API queries, for example entityDTO:

  1. Default response OK with list of entities:
public List<EntityDto> getAll() {
    return entityService.getAllEntities();

But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:

public ResponseEntity<Object> getOneParameterMap() {
    return ResponseEntity.status(HttpStatus.CREATED).body(
            Collections.singletonMap("key", "value"));
  1. And if you need return map of some parameters(since Java 9):
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getSomeParameters() {
    return ResponseEntity.status(HttpStatus.OK).body(Map.of(
            "key-1", "value-1",
            "key-2", "value-2",
            "key-3", "value-3"));

How to submit form on change of dropdown list?

other than using this.form.submit() you also submiting by id or name. example i have form like this : <form action="" name="PostName" id="IdName">

  1. By Name : <select onchange="PostName.submit()">

  2. By Id : <select onchange="IdName.submit()">

Escaping backslash in string - javascript

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.

This question already mentions, and links to other Stack Overflow questions regarding this topic.

Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.

string = string.split("\\");

In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.

So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Several fixes:

  1. Use the right driver class name for your environment: if you are using an out-of-process Derby server, then you want ClientDriver (and need to use derbyclient.jar), the hostname and port, etc. If you want an in-process Derby server, then you want derby.jar, EmbeddedDriver, and a URL that is appropriate for an embedded database.

  2. Put your driver JAR file only in Tomcat's lib/ directory.

  3. Don't put anything in Tomcat's conf/context.xml: there's really no reason for it. Instead, use your webapp's META-INF/context.xml to define your <Resource>.

The error "Cannot create JDBC driver of class '' for connect URL 'null' usually occurs because the JDBC driver is not in the right place (or in too many places, like Tomcat's lib/ directory but also in the webapp's WEB-INF/lib/ directory). Please verify that you have the right driver JAR file in the right place.

PHP preg_match - only allow alphanumeric strings and - _ characters

Why to use regex? PHP has some built in functionality to do that

    $valid_symbols = array('-', '_');
    $string1 = "This is a string*";
    $string2 = "this_is-a-string";

    if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
        echo "String 1 not acceptable acceptable";

preg_match('/\s/',$username) will check for blank space

!ctype_alnum(str_replace($valid_symbols, '', $string1)) will check for valid_symbols

If input field is empty, disable submit button

An easy way to do:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);

<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >

Why does the C++ STL not provide any "tree" containers?

the std::map is based on a red black tree. You can also use other containers to help you implement your own types of trees.

Remove all occurrences of char from string

String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";

for(String t : arr)

This is the example for where I have removed the character - from the String.

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

This is a confusion between constructors and instances.

Remember that when you write a component in React:

class Greeter extends React.Component<any, any> {
    render() {
        return <div>Hello, {this.props.whoToGreet}</div>;

You use it this way:

return <Greeter whoToGreet='world' />;

You don't use it this way:

let Greet = new Greeter();
return <Greet whoToGreet='world' />;

In the first example, we're passing around Greeter, the constructor function for our component. That's the correct usage. In the second example, we're passing around an instance of Greeter. That's incorrect, and will fail at runtime with an error like "Object is not a function".

The problem with this code

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;

is that it's expecting an instance of React.Component. What you want is a function that takes a constructor for React.Component:

function renderGreeting(Elem: new() => React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;

or similarly:

function renderGreeting(Elem: typeof React.Component) {
    return <span>Hello, <Elem />!</span>;

Import one schema into another new schema - Oracle

The issue was with the dmp file itself. I had to re-export the file and the command works fine. Thank you @Justin Cave

How to call execl() in C with the proper arguments?

  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here:

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.

My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as [email protected].

Another thing to try is in the authentication, fill in the third field with the domain, like

Dim smtpAuth = New System.Net.NetworkCredential(
    "TheDude", "hunter2password", "")

If that doesn't work, double check that you can log into the account at:

Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).

One last thing to note, the Send method is Asynchronous. If you call

immediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.

Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.

<?xml version="1.0" encoding="utf-8" ?>
            <source name="System.Net">
                    <add name="System.Net" />
            <source name="System.Net.Sockets">
                    <add name="System.Net" />
            <add name="System.Net" value="Verbose" />
            <add name="System.Net.Sockets" value="Verbose" />
            <add name="System.Net"
        <trace autoflush="true" />

Solr vs. ElasticSearch

Since the long history of Apache Solr, I think one strength of the Solr is its ecosystem. There are many Solr plugins for different types of data and purposes.

solr stack

Search platform in the following layers from bottom to top:

  • Data
    • Purpose: Represent various data types and sources
  • Document building
    • Purpose: Build document information for indexing
  • Indexing and searching
    • Purpose: Build and query a document index
  • Logic enhancement
    • Purpose: Additional logic for processing search queries and results
  • Search platform service
    • Purpose: Add additional functionalities of search engine core to provide a service platform.
  • UI application
    • Purpose: End-user search interface or applications

Reference article : Enterprise search

Git Push ERROR: Repository not found

The Problem: Github is not familiar with your repository from some reason.

The Error: prompted in git cli like the following:

remote: Repository not found. fatal: repository ‘’ not found

The Solution : 2 Options

  1. Github might not familiar with your credentials: - The first Option is to clone the project with the right credentials user:password in case you forgot this Or generate ssh token and adjust this key in your Github. aka git push https://<userName>:<password>

  2. Repo Permissions Issue with some users - In my Use case, I solved this issue when I realized I don't have the right collaborator permissions on Github in my private repo. Users could clone the project but not perform any actions on origin. In order to solve this:

Go to Repository on Github -> Settings -> Collaborators & Teams -> Add Member/Maintainer your users -> Now they got the permission to commit and push

Bootstrap 3 only for mobile

You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only

function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);


$(document).ready(function() {

if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);

Android getResources().getDrawable() deprecated API 22

For some who still got this issue to solve even after applying the suggestion of this thread(i used to be one like that) add this line on your Application class, onCreate() method


As suggested here and here sometimes this is required to access vectors from resources especially when you're dealing with menu items, etc

Send Mail to multiple Recipients in java

Just use the method message.setRecipients with multiple addresses separated by commas:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected],[email protected],[email protected]"));

message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("[email protected],[email protected],[email protected]"));

works fine with only one address too

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));

What's the most efficient way to check if a record exists in Oracle?

What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.

If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):

    select null into dummy
    from sales
    where sales_type = 'Accessories'
    and rownum = 1;

    --  do things here when record exists

    when no_data_found then
        -- do things here when record doesn't exists

You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.

Getting Raw XML From SOAPMessage in Java

if you have the client code then you just need to add the following two lines to get the XML request/response. Here _call is org.apache.axis.client.Call

String request = _call.getMessageContext().getRequestMessage().getSOAPPartAsString();
String response = _call.getMessageContext().getResponseMessage().getSOAPPartAsString();

Convert java.time.LocalDate into java.util.Date type

Here's a utility class I use to convert the newer java.time classes to java.util.Date objects and vice versa:

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

  public static Date asDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());

  public static Date asDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

  public static LocalDate asLocalDate(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();

  public static LocalDateTime asLocalDateTime(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();

Edited based on @Oliv comment.

How do I list all the columns in a table?

For MS SQL Server:

select * from information_schema.columns where table_name = 'tableName'

How can I list all cookies for the current page with Javascript?

I found this code on, which worked for me better than the other solutions:

function get_cookies_array() {

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);

     return cookies;

What is the exact meaning of Git Bash?

I think the question asker is (was) thinking that git bash is a command like git init or git checkout. Git bash is not a command, it is an interface. I will also assume the asker is not a linux user because bash is very popular the unix/linux world. The name "bash" is an acronym for "Bourne Again SHell". Bash is a text-only command interface that has features which allow automated scripts to be run. A good analogy would be to compare bash to the new PowerShell interface in Windows7/8. A poor analogy (but one likely to be more readily understood by more people) is the combination of the command prompt and .BAT (batch) command files from the days of DOS and early versions of Windows.


Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);


In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

TortoiseSVN icons overlay not showing after updating to Windows 10

I did all of the above and nothing worked. The overlay icons were appearing in Explorer but not in Total Commander.

Eventually what solved the issue for me was that I discovered a command in Total Commander that refreshed the Overlay Icons. To access it, right click on the toolbar and click on "Change...", and add "cm_SwitchOverlayIcons" as shown in the image below.

After adding the command icon to the toolbar, I click it once, and the overlay icon of TortoiseSVN appeared!

enter image description here

Submit form without page reloading

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            

Get width/height of SVG element

SVG has properties width and height. They return an object SVGAnimatedLength with two properties: animVal and baseVal. This interface is used for animation, where baseVal is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.

What happened to Lodash _.pluck?

Use instead of _.pluck. In the latest version the _.pluck has been removed.

The correct way to read a data file into an array

I like...

@data = `cat /var/tmp/somefile`;

It's not as glamorous as others, but, it works all the same. And...

$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ; 
@data = <INFILE> ; 
close INFILE ;


Trigger a keypress/keydown/keyup event in JS/jQuery?

You can trigger any of the events with a direct call to them, like this:

$(function() {

Does that do what you're trying to do?

You should probably also trigger .focus() and potentially .change()

If you want to trigger the key-events with specific keys, you can do so like this:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

jQuery: how to get which button was clicked upon form submission?

When the form is submitted:

  • document.activeElement will give you the submit button that was clicked.

  • document.activeElement.getAttribute('value') will give you that button's value.

Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."

Moment.js - how do I get the number of years since a date, not rounded up?

If you dont want to use any module for age calculation

var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)

How can I simulate an array variable in MySQL?

Another way to see the same problem. Hope helpfull




SET v_tam = (SELECT (LENGTH(v_value) - LENGTH(REPLACE(v_value,',',''))));
SET v_pos = 1;

WHILE (v_tam >= v_pos)
    INSERT INTO split 
    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(v_value,',',v_pos),',', -1);
    SET v_pos = v_pos + 1;

SELECT * FROM split;



CALL ARR('1006212,1006404,1003404,1006505,444,');

Setup a Git server with msysgit on Windows

There may simply not be such a guide. If so, you may not have much luck convincing anybody to write one, because it would be a lot of work.

I would recommend either of two things. The easier one is to follow the guide you have slavishly, which means forgetting about msysgit.

The harder one is to put up a Linux server - perhaps as a guest under Windows using VirtualBox (free) or VMWare or Parallels (pay), and then follow one of the many sets of instructions Google will lead you to. But you will probably find those instructions are insufficient - they usually assume you've already set up an ssh server, for example, so you have to get that info elsewhere. I've done that twice, and can say that unless you're already something of a Linux guru, it will be a struggle.

Convert JS Object to form data

This method convert a JS object to a FormData :

function convertToFormData(params) {_x000D_
    return Object.entries(params)_x000D_
        .reduce((acc, [key, value]) => {_x000D_
            if (Array.isArray(value)) {_x000D_
                value.forEach((v, k) => acc.append(`${key}[${k}]`, value));_x000D_
            } else if (typeof value === 'object' && !(value instanceof File) && !(value instanceof Date)) {_x000D_
                Object.entries(value).forEach((v, k) => acc.append(`${key}[${k}]`, value));_x000D_
            } else {_x000D_
                acc.append(key, value);_x000D_
            return acc;_x000D_
        }, new FormData());_x000D_

Connect to mysql on Amazon EC2 from a remote server

Log into AWS Management Console. Navigate to RDS then select the db instance and go to "security Groups". Adding CIDR/IP under the security group fixed the problem.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

 //Trying to do more than one thing to the object in the same context, 
//the solution is to work on single context objects

public class SingletonContext<TContext>
    where TContext: DbContext,new()
    private static TContext _context;

    private SingletonContext()

    public static TContext GetInstance()
        if (_context == null)
            _context = new TContext();
        return _context;


Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

Random date in C#

I have taken @Joel Coehoorn answer and made the changes he adviced - put the variable out of the method and put all in class. Plus now the time is random too. Here is the result.

class RandomDateTime
    DateTime start;
    Random gen;
    int range;

    public RandomDateTime()
        start = new DateTime(1995, 1, 1);
        gen = new Random();
        range = (DateTime.Today - start).Days;

    public DateTime Next()
        return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));

And example how to use to write 100 random DateTimes to console:

RandomDateTime date = new RandomDateTime();
for (int i = 0; i < 100; i++)

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

        res = math.exp(420000)
    except OverflowError:
        res = float('inf')


Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

Difference between HashMap, LinkedHashMap and TreeMap

Hash map doesn't preserves the insertion order.
Example. Hashmap If you are inserting keys as

1  3
5  9
4   6
7   15
3   10

It can store it as

4  6
5  9
3  10
1  3
7  15

Linked Hashmap preserves the insertion order.

If you are inserting keys

1  3
5  9
4   6
7   15
3   10

It will store it as

1  3
5  9
4   6
7   15
3   10

same as we insert.

Tree map stores the vales in Increasing Order Of Keys. Example.
If you are inserting keys

1  3
5  9
4   6
7   15
3   10

It will store it as

1  3
3  10
4   6
5   9
7   15

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

There is some voodoo-talk in the answers around here among good ideas. Let's try to be a bit more real about what's happening and sum up the good stuff to check:

Basically, when that happens, it is a good idea to enable verbose mode for AVRDUDE, to get a better idea of what's happening. To do so, you only need to go in the preferences and check the verbose mode box. It's also a good idea to move away from the Arduino IDE, and launch a console to be more comfortable on reading AVRDUDE's output, that you'll get on clicking on the upload button.

What's important here to put 3 or 4 -v to the command call. Here's how looks like such AVRDUDE commands, with made up parameters as they are totally dependent on how the Arduino has been installed:

avrdude -v -v -v -v -C /path/to/avrdude.conf -patmega328 -P/dev/usbport -U flash:w:/path/to/firmware.hex

A good way to get the correct command line to use is to copy it from the verbose output of the Arduino IDE output log when verbosity has been enabled.

When you get avrdude: stk500_recv(): programmer is not responding, it basically means that something wrong is happening, before the flashing actually begins.

Basically you have to check (from hardware to software, low level to high level):

  • if the cable and/or connectors does not have microcuts;
  • if no solder points are short circuiting (i.e. touching something metallic around), that means:
    • if there is no short circuit on the PCB between Rx and Tx (usually pins 1 and 0);
    • if there is no contact with a metallic element below the board, or tiny bits between a component's legs (like the FTDI, the ATmega chip or any other);
  • if the ATmega chip is not out of power (GND/VCC shortcut or cut or VCC input being dead…);
  • if the 1 and 0 pins of the Arduino are not being used by some shield or custom design (/!\ does not apply to the Leonardo as it has independent USB handling);
  • if the USB to UART converter does not have a problem (FTDI on older Duemilanove or ATmega16U2 on newer Arduino Unos);
  • if the ATmega328 chip is fried or wrongly installed;
  • if the bootloader has been overwritten or is failing;
  • if the right baudrate is applied for entering the bootloader;
  • if the right settings are set for the target microcontroller and Board;

Usually the avrdude -v -v -v -v can help a lot find at which stage it is failing. Whether it can't make a USB connection at all (cable failing, USB/UART, PCB…), or it is a bootloader problem.

Update: I tried turning the onboard ATmega and fitting it in the other direction. Now, I encounter no problems uploading, but nothing happens afterwards. The onboard LED also does not seem to be blinking.

I'm afraid that if you reversed the position of the ATmega, and then it does not work, the fact that you placed the power source on digital pins may have burnt your chip.

How to get the last characters in a String in Java, regardless of String size

String inputstr = "abcd: efg: 1006746"
int startindex = inputstr.length() - 10;
String outputtendigitstr = inputstr.substring(startindex);

Make sure you check string length is more than 10.

How can I rename a conda environment?

conda create --name new_name --copy --clone old_name is better

I use conda create --name new_name --clone old_name which is without --copy but encountered pip breaks...

the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from

Laravel update model with unique validation rule for attribute

I am calling different validation classes for Store and Update. In my case I don't want to update every fields, so I have baseRules for common fields for Create and Edit. Add extra validation classes for each. I hope my example is helpful. I am using Laravel 4.


public static $baseRules = array(
    'first_name' => 'required',
    'last_name'  => 'required',
    'description' => 'required',
    'description2' => 'required',
    'phone'  => 'required | numeric',
    'video_link'  => 'required | url',
    'video_title'  => 'required | max:87',
    'video_description'  => 'required',
    'sex' => 'in:M,F,B',
    'title'  => 'required'

public static function validate($data)
    $createRule = static::$baseRules;
    $createRule['email'] = 'required | email | unique:musicians';
    $createRule['band'] = 'required | unique:musicians';
    $createRule['style'] = 'required';
    $createRule['instrument'] = 'required';
    $createRule['myFile'] = 'required | image';

    return Validator::make($data, $createRule);

public static function validateUpdate($data, $id)
    $updateRule = static::$baseRules;
    $updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
    $updateRule['band'] = 'required | unique:musicians,band,' . $id;
    return Validator::make($data, $updateRule);

Controller: Store method:

public function store()
    $myInput = Input::all();
    $validation = Musician::validate($myInput);
        $key = "errorMusician";
        return Redirect::to('musician/create')
        ->withErrors($validation, 'musicain')

Update method:

public function update($id) 
    $myInput = Input::all();
    $validation = Musician::validateUpdate($myInput, $id);
        $key = "error";
        $message = $validation->messages();
        return Redirect::to('musician/' . $id)
        ->withErrors($validation, 'musicain')

How to use FormData in react-native?

You can use react-native-image-picker and axios (form-data)

uploadS3 = (path) => {
    var data = new FormData();

        { uri: path, name: 'image.jpg', type: 'image/jpeg' }

    var config = {
        method: 'post',
        url: YOUR_URL,
        headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
        data: data,

        .then((response) => {
        .catch((error) => {


selectPhotoTapped() {
    const options = {
        quality: 1.0,
        maxWidth: 500,
        maxHeight: 500,
        storageOptions: {
            skipBackup: true,

    ImagePicker.showImagePicker(options, response => {
        //console.log('Response = ', response);

        if (response.didCancel) {
            //console.log('User cancelled photo picker');
        } else if (response.error) {
            //console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
            //console.log('User tapped custom button: ', response.customButton);
        } else {
            let source = { uri: response.uri };
            // Call Upload Function

            // You can also display the image using data:
            // let source = { uri: 'data:image/jpeg;base64,' + };
                avatarSource: source,
            // this.imageUpload(source);

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:


For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.

By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:


4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16


4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

Null vs. False vs. 0 in PHP

False, Null, Nothing, 0, Undefined, etc., etc.

Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value.

In C and C++, NULL, False and 0 are overloaded to the same value. In C# they're 3 distinct concepts.

null or NULL usually indicates a lack of value, but usually doesn't specify why. 0 indicates the natural number zero and has type-equivalence to 1, 2, 3, etc. and in languages that support separate concepts of NULL should be treated only a number.

False indicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0. It simply indicates one of two binary values.

Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.

Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.

Enum "Inheritance"

Alternative solution

In my company, we avoid "jumping over projects" to get to non-common lower level projects. For instance, our presentation/API layer can only reference our domain layer, and the domain layer can only reference the data layer.

However, this is a problem when there are enums that need to be referenced by both the presentation and the domain layers.

Here is the solution that we have implemented (so far). It is a pretty good solution and works well for us. The other answers were hitting all around this.

The basic premise is that enums cannot be inherited - but classes can. So...

// In the lower level project (or DLL)...
public abstract class BaseEnums
    public enum ImportanceType
        None = 0,
        Success = 1,
        Warning = 2,
        Information = 3,
        Exclamation = 4

    public enum StatusType : Int32
        None = 0,
        Pending = 1,
        Approved = 2,
        Canceled = 4,
        Accepted = (8 | Approved),
        Rejected = 16,
        Shipped = (32 | Accepted),
        Reconciled = (64 | Shipped)

    public enum Conveyance
        None = 0,
        Feet = 1,
        Automobile = 2,
        Bicycle = 3,
        Motorcycle = 4,
        TukTuk = 5,
        Horse = 6,
        Yak = 7,
        Segue = 8

Then, to "inherit" the enums in another higher level project...

// Class in another project
public sealed class SubEnums: BaseEnums
   private SubEnums()

This has three real advantages...

  1. The enum definitions are automatically the same in both projects - by definition.
  2. Any changes to the enum definitions are automatically echoed in the second without having to make any modifications to the second class.
  3. The enums are based on the same code - so the values can easily be compared (with some caveats).

To reference the enums in the first project, you can use the prefix of the class: BaseEnums.StatusType.Pending or add a "using static BaseEnums;" statement to your usings.

In the second project when dealing with the inherited class however, I could not get the "using static ..." approach to work, so all references to the "inherited enums" would be prefixed with the class, e.g. SubEnums.StatusType.Pending. If anyone comes up with a way to allow the "using static" approach to be used in the second project, let me know.

I am sure that this can be tweaked to make it even better - but this actually works and I have used this approach in working projects.

Please up-vote this if you find it helpful.

count number of characters in nvarchar column


SELECT length(yourfield) FROM table;

Why are my PowerShell scripts not running?

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

The above command worked for me even when the following error happens:

Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

Gridview row editing - dynamic binding to a DropDownList

Quite easy... You're doing it wrong, because by that event the control is not there:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.DataRow && 
        (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        // Here you will get the Control you need like:
        DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");

That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.

Is there a better way to refresh WebView?

Refreshing current webview's URL is not a common usage.
I used this in such a scenario: When user goes to another activity and user come back to webview's activity I reload current URL like this:

public class MyWebviewActivity extends Activity {
    WebView mWebView;
    public void onRestart() {
            String url = mWebView.getUrl();
            String postData = MyUtility.getOptionsDataForPOSTURL(mContext);
            mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));

You can also use WebView's reload() function. But note that if you loaded the webview with postUrl(), then mWebView.reload(); doesn't work. This also works

String webUrl = webView.getUrl();

How can I return the difference between two lists?

I was looking similar but I wanted the difference in either list (uncommon elements between the 2 lists).

Let say I have:

List<String> oldKeys = Arrays.asList("key0","key1","key2","key5");
List<String> newKeys = Arrays.asList("key0","key2","key5", "key6");

And I wanted to know which key has been added and which key is removed i.e I wanted to get (key1, key6)

Using org.apache.commons.collections.CollectionUtils

List<String> list = new ArrayList<>(CollectionUtils.disjunction(newKeys, oldKeys));


["key1", "key6"]

Where does gcc look for C and C++ header files?

The set of paths where the compiler looks for the header files can be checked by the command:-

cpp -v

If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.

If you declare #include <> , the compiler searches directly in those directories obtained from the above command.


oracle sql: update if exists else insert

The way I always do it (assuming the data is never to be deleted, only inserted) is to

  • Firstly do an insert, if this fails with a unique constraint violation then you know the row is there,
  • Then do an update

Unfortunately many frameworks such as Hibernate treat all database errors (e.g. unique constraint violation) as unrecoverable conditions, so it isn't always easy. (In Hibernate the solution is to open a new session/transaction just to execute this one insert command.)

You can't just do a select count(*) .. where .. as even if that returns zero, and therefore you choose to do an insert, between the time you do the select and the insert someone else might have inserted the row and therefore your insert will fail.

Producing a new line in XSLT

I couldn't just use the <xsl:text>&#xa;</xsl:text> approach because if I format the XML file using XSLT the entity will disappear. So I had to use a slightly more round about approach using variables

<xsl:variable name="nl" select="'&#10;'"/>
<xsl:template match="/">
    <xsl:value-of select="$nl" disable-output-escaping="no"/>
    <xsl:apply-templates select="*"/>

How to iterate over the keys and values with ng-repeat in AngularJS?

If you would like to edit the property value with two way binding:

<tr ng-repeat="(key, value) in data">
    <td>{{key}}<input type="text" ng-model="data[key]"></td>

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Convert base-2 binary number string to int

For the record to go back and forth in basic python3:

a = 10
# '0b1010'

int(bin(a), 2)
# 10
# 10

How do I 'foreach' through a two-dimensional array?

Here's a simple extension method that returns each row as an IEnumerable<T>. This has the advantage of not using any extra memory:

public static class Array2dExt
    public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] array)
        for (int r = array.GetLowerBound(0); r <= array.GetUpperBound(0); ++r)
            yield return row(array, r);

    static IEnumerable<T> row<T>(T[,] array, int r)
        for (int c = array.GetLowerBound(1); c <= array.GetUpperBound(1); ++c)
            yield return array[r, c];

Sample usage:

static void Main()
    string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };

    foreach (var row in siblings.Rows())
        Console.WriteLine("{" + string.Join(", ", row) + "}");

How to remove application from app listings on Android Developer Console

you can remove an App from the store or "Unpublish" by clicking a tiny label bellow your app's title, right side of the "PUBLISHED" green status label.

enter image description here

Works even if your app was live (published) for long time, mine was.


Changing file extension in Python

os.path.splitext(), os.rename()

for example:

# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)

ORACLE and TRIGGERS (inserted, updated, deleted)

I've changed my code like this and it works:

  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);

  Operation := 3;
  CustomerCode := :old_buffer.field1;

  Operation := 1;
  CustomerCode := :new_buffer.field1;

  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;    




Check if a path represents a file or a folder

   private static boolean isValidFolderPath(String path) {
    File file = new File(path);
    if (!file.exists()) {
      return file.mkdirs();
    return true;

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I don't think you can, the only other configuration alternative is to enumerate the paths that you want to be filtered, so instead of /* you could add some for /this/* and /that/* etc, but that won't lead to a sufficient solution when you have alot of those paths.

What you can do is add a parameter to the filter providing an expression (like a regular expression) which is used to skip the filter functionality for the paths matched. The servlet container will still call your filter for those url's but you will have better control over the configuration.


Now that you mention you have no control over the filter, what you could do is either inherit from that filter calling super methods in its methods except when the url path you want to skip is present and follow the filter chain like @BalusC proposed, or build a filter which instantiates your filter and delegates under the same circumstances. In both cases the filter parameters would include both the expression parameter you add and those of the filter you inherit from or delegate to.

The advantage of building a delegating filter (a wrapper) is that you can add the filter class of the wrapped filter as parameter and reuse it in other situations like this one.

TypeError: unhashable type: 'list' when using built-in set function

Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.

Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:

def uniq(lst):
    last = object()
    for item in lst:
        if item == last:
        yield item
        last = item

def sort_and_deduplicate(l):
    return list(uniq(sorted(l, reverse=True)))

Android java.lang.NoClassDefFoundError


Go to Order and export from project properties and make sure you're including the required jars in the export, this did it for me

Maximum value of maxRequestLength?

These two settings worked for me to upload 1GB mp4 videos.

    <httpRuntime maxRequestLength="2097152" requestLengthDiskThreshold="2097152" executionTimeout="240"/>
            <requestLimits maxAllowedContentLength="2147483648" />

Websocket connections with Postman

I ran into the exact same problem. Had to make a Web Socket call. I was able to accomplish this using Advanced Rest Client. I'm using ARC version : 12.1.3

enter image description here

psql: server closed the connection unexepectedly

Solved by setting a password for the user first.

In terminal

sudo -u <username> psql

ALTER USER <username> PASSWORD 'SetPassword';


In pgAdmin


Host name/address:
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX

Python "\n" tag extra line

Add , after the print "\n" line

so that it reads print "\n",

How get value from URL

You can access those values with the global $_GET variable

print $_GET['id']; // prints "7"

You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).

Split string by single spaces

If you are not averse to boost, boost.tokenizer is flexible enough to solve this

#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>

void split_and_show(const std::string s)
    boost::char_separator<char> sep(" ", "", boost::keep_empty_tokens);
    boost::tokenizer<boost::char_separator<char> > tok(s, sep);
    for(auto i = tok.begin(); i!=tok.end(); ++i)
            std::cout << '"' << *i << "\"\n";
int main()
    split_and_show("This is a string");
    split_and_show("This  is a string");



The page cannot be displayed because an internal server error has occurred on server

Modify your web.config to display the server error details:

  <customErrors mode="Off" />

You may also need to remove/comment out the follow httpErrors section

    <httpErrors errorMode="Custom">
      <remove statusCode="404" />
      <error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" />
      <remove statusCode="500" />
      <error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" />
      <remove statusCode="403" />
      <error statusCode="403" path="/Error/Error403" responseMode="ExecuteURL" />

From my experience if you directly have a server error, this may be caused from an assembly version mismatch.

Check what is declared in the web.config and the actual ddl in the bin folder's project.

What are the specific differences between .msi and setup.exe file?

.msi files are windows installer files without the windows installer runtime, setup.exe can be any executable programm (probably one that installs stuff on your computer)

What does the Visual Studio "Any CPU" target mean?

I recommend reading this post.

When using AnyCPU, the semantics are the following:

  • If the process runs on a 32-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
  • If the process runs on a 64-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
  • If the process runs on an ARM Windows system, it runs as a 32-bit process. CIL is compiled to ARM machine code.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.

  public static String toCamelCase(String value) {
    StringBuilder sb = new StringBuilder();

    final char delimChar = '_';
    boolean lower = false;
    for (int charInd = 0; charInd < value.length(); ++charInd) {
      final char valueChar = value.charAt(charInd);
      if (valueChar == delimChar) {
        lower = false;
      } else if (lower) {
      } else {
        lower = true;

    return sb.toString();

A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.

Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.

How to get the current date and time

The Java Date and Calendar classes are considered by many to be poorly designed. You should take a look at Joda Time, a library commonly used in lieu of Java's built-in date libraries.

The equivalent of DateTime.Now in Joda Time is:

DateTime dt = new DateTime();


As noted in the comments, the latest versions of Joda Time have a method, so:

DateTime dt =;

how to check for datatype in node js- specifically for integer

I just made some tests in node.js v4.2.4 (but this is true in any javascript implementation):

> typeof NaN
> isNaN(NaN)
> isNaN("hello")

the surprise is the first one as type of NaN is "number", but that is how it is defined in javascript.

So the next test brings up unexpected result

> typeof Number("hello")

because Number("hello") is NaN

The following function makes results as expected:

function isNumeric(n){
  return (typeof n == "number" && !isNaN(n));

Line break in HTML with '\n'

Simple and linear:

 <p> my phrase is this..<br>
 the other line is this<br>
 the end is this other phrase..

How do I import modules or install extensions in PostgreSQL 9.1+?

For the postgrersql10

I have solved it with

yum install postgresql10-contrib

Don't forget to activate extensions in postgresql.conf

shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all

then of course restart

systemctl restart postgresql-10.service 

all of the needed extensions you can find here


Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 //Your Logic here

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 //Your Logic here