Programs & Examples On #Packet sniffers

A software or a piece of computer hardware that can intercept and log traffic passing over a digital network or part of a network

iPhone and WireShark

The following worked for iPhone 4S (iOS 5) and Macbook Pro (10.8.2)

  1. On your Mac, go to System Preferences > Sharing > Internet Sharing internetSharing

  2. On your iPhone, go to Settings > Wifi and choose your Mac as the Wifi Access Point. Press the blue detail disclosure next to it to and note down the IP Address ( in my case). At this point, the wifi icon on Mac's your taskbar should change to the following: wifi

  3. Open wireshark. Click on start capture, and use the new bridge interface that should now be available among the options. wshark

  4. ???

  5. Profit!

As with all stuff networking related, you might have to restart wifi etc and repeat steps and invoke your favorite deity to get this incantation working :)

Wireshark localhost traffic capture

You cannot capture loopback on Solaris, HP-UX, or Windows, however you can very easily work around this limitation by using a tool like RawCap.

RawCap can capture raw packets on any ip including (localhost/loopback). Rawcap can also generate a pcap file. You can open and analyze the pcap file with Wireshark.

See here for full details on how to monitor localhost using RawCap and Wireshark.

How can you get the Manifest Version number from the App's (Layout) XML variables?

I solved this issue by extending the Preference class.


import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;

Then in my preferences XML:

<PreferenceScreen xmlns:android="">
    < android:title="Version" />

What's the fastest way to loop through an array in JavaScript?

A basic while loop is often the fastest. is a great sandbox to test these types of concepts.

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);

Refer here to know more about Array of ES6:

How to apply slide animation between two activities in Android?

You could use overridePendingTransition in startActivity instead of onCreate. At least, that works for me!

See a full example here. It's including an (reverse) animation onBackPressed, so while returning to the previous activity! In your specific example (fade-in and -out) that might be unnecessary though.

ASP.NET Bundles how to disable minification

Just to supplement the answers already given, if you also want to NOT minify/obfuscate/concatenate SOME files while still allowing full bundling and minification for other files the best option is to go with a custom renderer which will read the contents of a particular bundle(s) and render the files in the page rather than render the bundle's virtual path. I personally required this because IE 9 was $*%@ing the bed when my CSS files were being bundled even with minification turned off.

Thanks very much to this article, which gave me the starting point for the code which I used to create a CSS Renderer which would render the files for the CSS but still allow the system to render my javascript files bundled/minified/obfuscated.

Created the static helper class:

using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;

namespace Helpers
  public static class OptionalCssBundler
    const string CssTemplate = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";

    public static MvcHtmlString ResolveBundleUrl(string bundleUrl, bool bundle)
      return bundle ? BundledFiles(BundleTable.Bundles.ResolveBundleUrl(bundleUrl)) : UnbundledFiles(bundleUrl);

    private static MvcHtmlString BundledFiles(string bundleVirtualPath)
      return new MvcHtmlString(string.Format(CssTemplate, bundleVirtualPath));

    private static MvcHtmlString UnbundledFiles(string bundleUrl)
      var bundle = BundleTable.Bundles.GetBundleFor(bundleUrl);

      StringBuilder sb = new StringBuilder();
      var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

      foreach (BundleFile file in bundle.EnumerateFiles(new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundleUrl)))
        sb.AppendFormat(CssTemplate + Environment.NewLine, urlHelper.Content(file.VirtualFile.VirtualPath));

      return new MvcHtmlString(sb.ToString());

    public static MvcHtmlString Render(string bundleUrl, bool bundle)
      return ResolveBundleUrl(bundleUrl, bundle);


Then in the razor layout file:

@OptionalCssBundler.Render("~/Content/css", false)

instead of the standard:


I am sure creating an optional renderer for javascript files would need little to update to this helper as well.

Python assigning multiple variables to same value? list behavior

What you need is this:

a, b, c = [0,3,5] # Unpack the list, now a, b, and c are ints
a = 1             # `a` did equal 0, not [0,3,5]

How do I capture SIGINT in Python?

From Python's documentation:

import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10) # Press Ctrl+c here

Get Selected value from Multi-Value Select Boxes by jquery-select2?

You should try this code.

 $("#multiple_Package_Ids_checkboxes").on('change', function (e) { 
        var totAmt = 0;
        $.each($(this).find(":selected"), function (i, item) { 
            totAmt += $(item).data("price");

Link vs compile vs controller

  • compile: used when we need to modify directive template, like add new expression, append another directive inside this directive
  • controller: used when we need to share/reuse $scope data
  • link: it is a function which used when we need to attach event handler or to manipulate DOM.

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID


global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();

Ruby: Merging variables in to a string

You can use it with your local variables, like this:

@animal = "Dog"
@action = "licks"
@second_animal = "Bird"

"The #{@animal} #{@action} the #{@second_animal}"

the output would be: "The Dog licks the Bird"

Best solution to protect PHP code without encryption

I have not looked at the VBulletin source code in some time, but the way they used to do it around 2003 was to embed a call to their server inside the code. IIRC, it was on a really long code line (like 200-300+ chars long) and was broken up over several string concatenations and such.

It did nothing "bad" if you pirated it - the forum still worked 100%. But your server's IP was logged along with other info and they used that to investigate and take legal action.

Your license number was embedded in this call, so they could easily track how many IPs/websites a given licensed copy was running on.

How can I remove file extension from a website address?

First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.

You don't hide urls or extensions. What you do is create a NEW url that directs to the old one, for example

The URL to put on your web site will be

or better yet

Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /play.php [L] 

Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be

/Some-Cool-Video (which equals product ID asdf)

The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?

I can't give you specifics of how to program this, but take the query string, strip off the end 

turns into "asdf"

Then set the m variable to this


So both URL's will still go to the same product 

mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

Java Enum Methods - return opposite direction enum

public enum Direction {

    public Direction getOppositeDirection(){
        return Direction.values()[(this.ordinal() + 2) % 4];

Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared. source

since NORTH gets 1, EAST gets 2, SOUTH gets 3, WEST gets 4; you can create a simple equation to get the opposite one:

(value + 2) % 4

HTML/CSS: Making two floating divs the same height

Several years ago, the float property used to solve that problem with the table approach using display: table; and display: table-row; and display: table-cell;.

But now with the flex property, you can solve it with 3 lines of code: display: flex; and flex-wrap: wrap; and flex: 1 0 50%;

.parent {
    display: flex;
    flex-wrap: wrap;

.child {
 // flex: flex-grow flex-shrink flex-basis;
    flex: 1 0 50%;

1 0 50% are the flex values we gave to: flex-grow flex-shrink flex-basis respectively. It's a relatively new shortcut in flexbox to avoid typing them individually. I hope this helps someone out there

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [

After this, restart ng serve if it is already started.

How to set an environment variable in a running docker container

You could set an environment variable to a running Docker container by

docker exec -it -e "your environment Key"="your new value" <container> /bin/bash

Verify it using below command


This will update your key with the new value provided.

Note: This will get reverted back to old on if docker gets restarted.

Set cURL to use local virtual hosts

Actually, curl has an option explicitly for this: --resolve

Instead of curl -H 'Host:'

use curl --resolve ''

What's the difference, you ask?

Among others, this works with HTTPS. Assuming your local server has a certificate for, the first example above will fail because the certificate doesn't match the hostname in the URL.

The second example works correctly with HTTPS.

In essence, passing a "Host" header via -H does hack your Host into the header set, but bypasses all of curl's host-specific intelligence. Using --resolve leverages all of the normal logic that applies, but simply pretends the DNS lookup returned the data in your command-line option. It works just like /etc/hosts should.

Note --resolve takes a port number, so for HTTPS you would use

curl --resolve ''

What does MissingManifestResourceException mean and how to fix it?

The solution given by BlaM worked for me too.

I am a VS 2013 User. After going through many fixes but no luck, I tried this:

  1. Right-click the resource file, one-by-one, in case of multiple-files.
  2. Make sure, the property "Build Action" is set to "Embedded Resource".

That's it! :)

How to set the Android progressbar's height?

You can set progress bar's style to this:


Double free or corruption after queue::push

You can also try to check null before delete such that

if(myArray) { delete[] myArray; myArray = NULL; }

or you can define all delete operations ina safe manner like this:

#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }

#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p) = NULL; } }

and then use


How to switch text case in visual studio code

For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.

  1. Open "File -> Preferences -> Keyboard Shortcuts" or "Code -> Preferences -> Keyboard Shortcuts" for Mac Users

  2. In the search bar type transform.

  3. By default you will not have anything under Keybinding. Now double-click on Transform to Lowercase or Transform to Uppercase.

  4. Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u for uppercase or ctrl+shift+l for lowercase.

  5. Press Enter on your keyboard to save and exit. Do same for the other option.


Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

What happens if you mount to a non-empty mount point with fuse?

force it with -l

    sudo umount -l ${HOME}/mount_dir

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Jquery to open Bootstrap v3 modal of remote url

So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a> tag and load that in modal-body.

<a  href='/site/login' class='ls-modal'>Login</a>

//JS script
$('.ls-modal').on('click', function(e){

Validation for 10 digit mobile number and focus input field on invalid

Use jquery validator in your script tag DEMO

<script src="js/jquery.validate.min.js"></script> 

and validate your element by like this

   <form name="enquiry_form" method="post" id="enquiry_form">

    Full Name *
    <input class="input-style" name="name"  id="name" type="text"/>
    Email *
    <input class="input-style" name="email"  id="email" type="email"><br>
    Phone * 
        <input id="mobile" name="mobile"  id="mobile"></input><br>

    <input type="submit" value="SUBMIT"  id="enq_submit">


      name:"Please enter your username..!",
      email:"Please enter your email..!",
          mobile:"Enter your mobile no"

      submitHandler: function(form) {
      //write your success code here  

What's the equivalent of Java's Thread.sleep() in JavaScript?

Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:

async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));

You can then use the sleep function in any other async function like this:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log

This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.

From MDN:

The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.

For a full explanation see:

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Your code would then look like: -> "result" /* or your function */)

I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant:

public String getString(Object yourObject) {
  if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
     throw new MyCustomException();
  String result = ...
  // your string mapping function
  return result;

If you already have the Optional-object due to another call, I would still recommend you to use the map-method, instead of isPresent, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).

How can I check for an empty/undefined/null string in JavaScript?

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

Convert InputStream to JSONObject

The best solution in my opinion is to encapsulate the InputStream in a JSONTokener object. Something like this:

JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));

How to resolve "Input string was not in a correct format." error?

Replace with

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Handling click events on a drawable within an EditText

Extending on the idea by RyanM I have created a more flexible version, which supports all the drawable types (top, bottom, left, right). While the code below extends TextView, adapting it for an EditText is just a case of swapping "extends TextView" with "extends EditText". Instantiation the widget from XML is identical as in RyanM's example, bar the widget name.

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;

import com.example.DrawableClickListener.DrawablePosition;

public class ButtonTextView extends TextView {

private Drawable    drawableRight;
private Drawable    drawableLeft;
private Drawable    drawableTop;
private Drawable    drawableBottom;

private int     actionX, actionY;

private DrawableClickListener clickListener;

public ButtonTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

public ButtonTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

public ButtonTextView(Context context) {

public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
    if (right != null) {
        drawableRight = right;

    if (left != null) {
        drawableLeft = left;

    if (top != null) {
        drawableTop = top;

    if (bottom != null) {
        drawableBottom = bottom;

    super.setCompoundDrawables(left, top, right, bottom);

public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        actionX = (int) event.getX();
        actionY = (int) event.getY();

        if (drawableBottom != null && drawableBottom.getBounds().contains(actionX, actionY)) {
            return super.onTouchEvent(event);

        if (drawableTop != null && drawableTop.getBounds().contains(actionX, actionY)) {
            return super.onTouchEvent(event);

        if (drawableLeft != null && drawableLeft.getBounds().contains(actionX, actionY)) {
            return super.onTouchEvent(event);

        if (drawableRight != null && drawableRight.getBounds().contains(actionX, actionY)) {
            return super.onTouchEvent(event);

    return super.onTouchEvent(event);

protected void finalize() throws Throwable {
    drawableRight = null;
    drawableBottom = null;
    drawableLeft = null;
    drawableTop = null;

public void setDrawableClickListener(DrawableClickListener listener) {
    this.clickListener = listener;

The DrawableClickListener is as simple as this:

public interface DrawableClickListener {

public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
public void onClick(DrawablePosition target); }

And then the actual implementation:

class example implements DrawableClickListener {
public void onClick(DrawablePosition target) {
    switch (target) {
        case LEFT:

        case RIGHT:

        case BOTTOM:

        case TOP:


p.s.: If you don't set the listener, touching the TextView will cause a NullPointerException. You may want to add some more paranoia into the code.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

I have created a table in hive, I would like to know which directory my table is created in?

in hive 0.1 you can use SHOW CREATE TABLE to find the path where hive store data.

in other versions, there is no good way to do this.


thanks Joe K

use DESCRIBE FORMATTED <table> to show table information.

ps: database.tablename is not supported here.

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do


   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:


enter image description here

CSS: Truncate table cells, but fit as much as possible

Given that 'table-layout:fixed' is the essential layout requirement, that this creates evenly spaced non-adjustable columns, but that you need to make cells of different percentage widths, perhaps set the 'colspan' of your cells to a multiple?

For example, using a total width of 100 for easy percentage calculations, and saying that you need one cell of 80% and another of 20%, consider:

<TABLE width=100% style="table-layout:fixed;white-space:nowrap;overflow:hidden;">
          <td colspan=100>
               text across entire width of table
          <td colspan=80>
               text in lefthand bigger cell
          <td colspan=20>
               text in righthand smaller cell

Of course, for columns of 80% and 20%, you could just set the 100% width cell colspan to 5, the 80% to 4, and the 20% to 1.

GROUP BY to combine/concat a column

     [User], Activity,
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Create list or arrays in Windows Batch

@echo off
set "list=a b c d"
 for %%i in (%list%) do (

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command


will produce a report of the ECHO state (ECHO is on/off) whereas


will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

JavaScript hashmap equivalent

Yet another map implementation by me. With randomizer, 'generics' and 'iterator' =)

var HashMap = function (TKey, TValue) {
    var db = [];
    var keyType, valueType;

    (function () {
        keyType = TKey;
        valueType = TValue;

    var getIndexOfKey = function (key) {
        if (typeof key !== keyType)
            throw new Error('Type of key should be ' + keyType);
        for (var i = 0; i < db.length; i++) {
            if (db[i][0] == key)
                return i;
        return -1;

    this.add = function (key, value) {
        if (typeof key !== keyType) {
            throw new Error('Type of key should be ' + keyType);
        } else if (typeof value !== valueType) {
            throw new Error('Type of value should be ' + valueType);
        var index = getIndexOfKey(key);
        if (index === -1)
            db.push([key, value]);
            db[index][1] = value;
        return this;

    this.get = function (key) {
        if (typeof key !== keyType || db.length === 0)
            return null;
        for (var i = 0; i < db.length; i++) {
            if (db[i][0] == key)
                return db[i][1];
        return null;

    this.size = function () {
        return db.length;

    this.keys = function () {
        if (db.length === 0)
            return [];
        var result = [];
        for (var i = 0; i < db.length; i++) {
        return result;

    this.values = function () {
        if (db.length === 0)
            return [];
        var result = [];
        for (var i = 0; i < db.length; i++) {
        return result;

    this.randomize = function () {
        if (db.length === 0)
            return this;
        var currentIndex = db.length, temporaryValue, randomIndex;
        while (0 !== currentIndex) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            temporaryValue = db[currentIndex];
            db[currentIndex] = db[randomIndex];
            db[randomIndex] = temporaryValue;
        return this;

    this.iterate = function (callback) {
        if (db.length === 0)
            return false;
        for (var i = 0; i < db.length; i++) {
            callback(db[i][0], db[i][1]);
        return true;


var a = new HashMap("string", "number");
a.add('test', 1132)
 .add('test14', 666)
 .add('1421test14', 12312666)
 .iterate(function (key, value) {console.log('a['+key+']='+value)});

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
  "success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            return False

    return persist

and :

def insert_or_update(table_object):
    return session.merge(table_object)

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: (7 Update 25 )

and here: (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.


Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body = filename;
        link.href = uri;;
        document.body.removeChild(link); // remove the link when done
    } else {

include antiforgerytoken in ajax post ASP.NET MVC

In Asp.Net Core you can request the token directly, as documented:

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf    
    public string GetAntiXsrfRequestToken()
        return Xsrf.GetAndStoreTokens(Context).RequestToken;

And use it in javascript:

function DoSomething(id) {
               { "__RequestVerificationToken": '@GetAntiXsrfRequestToken()' });

You can add the recommended global filter, as documented:

services.AddMvc(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());


The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.

My workaround, still using GetAntiXsrfRequestToken:

When there is no form:

<input type="hidden" id="RequestVerificationToken" value="@GetAntiXsrfRequestToken()">

The name attribute can be omitted since I use the id attribute.

Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name. Please note: there can be multiple forms inside a document, so name is in that case not unique. Unlike an id attribute that should be unique.

In the script, find by id:

function DoSomething(id) {
       { "__RequestVerificationToken": $('#RequestVerificationToken').val() });

An alternative, without having to reference the token, is to submit the form with script.

Sample form:

<form id="my_form" action="/something/todo/create" method="post">

The token is automatically added to the form as a hidden field:

<form id="my_form" action="/something/todo/create" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Cf..." /></form>

And submit in the script:

function DoSomething() {

Or using a post method:

function DoSomething() {
    var form = $('#my_form');

    $.post("/something/todo/create", form.serialize());

SQL how to increase or decrease one for a int column in one command

The single-step answer to the first question is to use something like:

update TBL set CLM = CLM + 1 where key = 'KEY'

That's very much a single-instruction way of doing it.

As for the second question, you shouldn't need to resort to DBMS-specific SQL gymnastics (like UPSERT) to get the result you want. There's a standard method to do update-or-insert that doesn't require a specific DBMS.

    insert into TBL (key,val) values ('xyz',0)
    do nothing
update TBL set val = val + 1 where key = 'xyz'

That is, you try to do the creation first. If it's already there, ignore the error. Otherwise you create it with a 0 value.

Then do the update which will work correctly whether or not:

  • the row originally existed.
  • someone updated it between your insert and update.

It's not a single instruction and yet, surprisingly enough, it's how we've been doing it successfully for a long long time.

How to put sshpass command inside a bash script?

I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.

After your provided script commands, execute additional commands like below:

sshpass -p 'password' ssh user@host "ls; whois;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command

In your script:

#! /bin/bash

sshpass -p 'password' ssh user@host "ls; whois;"

How to highlight text using javascript

Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.

function styleSelected() {
  bg = document.createElement("span"); = "yellow";

Is div inside list allowed?

I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.

Cannot catch toolbar home button click event

If you want to know when home is clicked is an AppCompatActivity then you should try it like this:

First tell Android you want to use your Toolbar as your ActionBar:


Then set Home to be displayed via setDisplayShowHomeEnabled like this:


Finally listen for click events on like usual:

public boolean onOptionsItemSelected(MenuItem menuItem) {
    if (menuItem.getItemId() == {
        Timber.d("Home pressed");
    return super.onOptionsItemSelected(menuItem);

If you want to know when the navigation button is clicked on a Toolbar in a class other than AppCompatActivity you can use these methods to set a navigation icon and listen for click events on it. The navigation icon will appear on the left side of your Toolbar where the the "home" button used to be.

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Log.d("cek", "home selected");

If you want to know when the hamburger is clicked and when the drawer opens, you're already listening for these events via onDrawerOpened and onDrawerClosed so you'll want to see if those callbacks fit your requirements.

How to hide first section header in UITableView (grouped style)

easiest by far is to return nil, or "" in func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? for a section where you do not wish to display header.

Merge a Branch into Trunk

Do an svn update in the trunk, note the revision number.

From the trunk:

svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName

You can check where the branch was cut from the trunk by doing an svn log

svn log --stop-on-copy

PHP - cannot use a scalar as an array warning

You need to set$final[$id] to an array before adding elements to it. Intiialize it with either

$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];


$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];

How to refresh a page with jQuery by passing a parameter to URL

if window.location.hash is empty, you cant assign to location.href a new value without using a correct function (at least tested in chrome).

try the window.location.replace:

if (!window.location.hash) 
        window.location.replace(window.location.href + "?single")

How to update Ruby to 1.9.x on Mac?

As previously mentioned, the bundler version may be too high for your version of rails.

I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22

Check your bundler version using: gem list bundler

If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler

Note: rvm is required for this solution... another case for why you should be using rvm in the first place.

Android: disabling highlight on listView click

As an alternative:



listView.setSelector(new StateListDrawable());

Best way to parseDouble with comma as decimal separator?

This would do the job:


Format XML string to print friendly XML string

Check the following link: How to pretty-print XML (Unfortunately, the link now returns 404 :()

The method in the link takes an XML string as an argument and returns a well-formed (indented) XML string.

I just copied the sample code from the link to make this answer more comprehensive and convenient.

public static String PrettyPrint(String XML)
    String Result = "";

    MemoryStream MS = new MemoryStream();
    XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
    XmlDocument D   = new XmlDocument();

        // Load the XmlDocument with the XML.

        W.Formatting = Formatting.Indented;

        // Write the XML into a formatting XmlTextWriter

        // Have to rewind the MemoryStream in order to read
        // its contents.
        MS.Position = 0;

        // Read MemoryStream contents into a StreamReader.
        StreamReader SR = new StreamReader(MS);

        // Extract the text from the StreamReader.
        String FormattedXML = SR.ReadToEnd();

        Result = FormattedXML;
    catch (XmlException)


    return Result;

What are the options for (keyup) in Angular2?

Have hit the same problem today.

These are poorly documented, an open issue exist.

Some for keyup, like space:

<input ("doSomething()">
<input (keyup.spacebar)="doSomething()">  

Some for keydown
(may work for keyup too):

<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.alt)="...">
<input (keydown.shift.esc)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.f4)="...">

All above are from below links:

How do I add an element to array in reducer of React native redux?

If you need to insert into a specific position in the array, you can do this:

case ADD_ITEM :
    return { 
        arr: [
            ...state.arr.slice(0, action.pos),

What is it exactly a BLOB in a DBMS context

A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.

You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.

Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.

Retrofit and GET using parameters

I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is,147, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:

public interface LocationService {    
    void getLocation(@Query(value="latlng", encoded=true) String latlng);

Note the encoded=true is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:

String latlng = location.getLatitude() + "," + location.getLongitude();

"Fatal error: Cannot redeclare <function>"

This errors says your function is already defined ; which can mean :

  • you have the same function defined in two files
  • or you have the same function defined in two places in the same file
  • or the file in which your function is defined is included two times (so, it seems the function is defined two times)

I think your facing problem at 3rd position the script including this file more than one time.So, you can solve it by using require_once instead of require or include_once instead of include for including your functions.php file -- so it cannot be included more than once.

Stop node.js program from command line

To end the program, you should be using Ctrl + C. If you do that, it sends SIGINT, which allows the program to end gracefully, unbinding from any ports it is listening on.

See also:

Windows Scheduled task succeeds but returns result 0x1

On our servers it was a problem with the system path. After upgrading PHP runtime (using installation directory whose name includes version number) and updating the path in system variable PATH we were getting status 0x1. System restart corrected the issue. Restarting Task Manager service might have done it, too.

Change bundle identifier in Xcode when submitting my first app in IOS

Just change Product Name in your project's build settings. This will change the bundle identifier with no need to manually touch xcode configuration files.

TSQL Pivot without aggregate function

WITH pivot_data AS
SELECT customerid, -- Grouping Column
dbcolumnname, -- Spreading Column
data -- Aggregate Column
FROM pivot2 
SELECT customerid, [firstname], [middlename], [lastname]
FROM pivot_data
PIVOT (max(data) FOR dbcolumnname IN ([firstname],[middlename],[lastname])) AS p;

Seaborn plots not showing up

I come to this question quite regularly and it always takes me a while to find what I search:

import seaborn as sns
import matplotlib.pyplot as plt  # <--- This is what you are looking for

Please note: In Python 2, you can also use, but not in Python 3.

Complete Example

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

"""Visualize C_0.99 for all languages except the 10 with most characters."""

import seaborn as sns
import matplotlib.pyplot as plt

l = [41, 44, 46, 46, 47, 47, 48, 48, 49, 51, 52, 53, 53, 53, 53, 55, 55, 55,
     55, 56, 56, 56, 56, 56, 56, 57, 57, 57, 57, 57, 57, 57, 57, 58, 58, 58,
     58, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 60, 60, 60, 60, 61,
     61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 62, 62, 62, 62, 62, 62, 62, 62,
     62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 64, 64, 64, 64, 64, 64, 64, 65,
     65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 66, 66, 66, 66, 66, 66, 66,
     67, 67, 67, 67, 67, 67, 67, 67, 68, 68, 68, 68, 68, 69, 69, 69, 70, 70,
     70, 70, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 73, 73, 73,
     74, 74, 74, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 79, 79, 79, 79, 80,
     80, 80, 80, 81, 81, 81, 81, 83, 84, 84, 85, 86, 86, 86, 86, 87, 87, 87,
     87, 87, 88, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91, 91, 91, 91, 91, 92,
     92, 93, 93, 93, 94, 95, 95, 96, 98, 98, 99, 100, 102, 104, 105, 107, 108,
     109, 110, 110, 113, 113, 115, 116, 118, 119, 121]

sns.distplot(l, kde=True, rug=False)


enter image description here

serialize/deserialize java 8 java.time with Jackson JSON mapper

For those who use Spring Boot 2.x

There is no need to do any of the above - Java 8 LocalDateTime is serialised/de-serialised out of the box. I had to do all of the above in 1.x, but with Boot 2.x, it works seamlessly.

See this reference too JSON Java 8 LocalDateTime format in Spring Boot

making a paragraph in html contain a text from a file

Here is a javascript code I have tested successfully :

    var txtFile = new XMLHttpRequest();
    var allText = "file not found";
    txtFile.onreadystatechange = function () {
        if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
            allText = txtFile.responseText;
            allText = allText.split("\n").join("<br>");

        document.getElementById('txt').innerHTML = allText;
    }"GET", '/result/client.txt', true);

Scala list concatenation, ::: vs ++

::: works only with lists, while ++ can be used with any traversable. In the current implementation (2.9.0), ++ falls back on ::: if the argument is also a List.

Upload a file to Amazon S3 with NodeJS

So it looks like there are a few things going wrong here. Based on your post it looks like you are attempting to support file uploads using the connect-multiparty middleware. What this middleware does is take the uploaded file, write it to the local filesystem and then sets req.files to the the uploaded file(s).

The configuration of your route looks fine, the problem looks to be with your items.upload() function. In particular with this part:

var params = {
  Body: file

As I mentioned at the beginning of my answer connect-multiparty writes the file to the local filesystem, so you'll need to open the file and read it, then upload it, and then delete it on the local filesystem.

That said you could update your method to something like the following:

var fs = require('fs');
exports.upload = function (req, res) {
    var file = req.files.file;
    fs.readFile(file.path, function (err, data) {
        if (err) throw err; // Something went wrong!
        var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
        s3bucket.createBucket(function () {
            var params = {
                Key: file.originalFilename, // doesn't exist as a property
                Body: data
            s3bucket.upload(params, function (err, data) {
                // Whether there is an error or not, delete the temp file
                fs.unlink(file.path, function (err) {
                    if (err) {
                    console.log('Temp File Delete');

                console.log("PRINT FILE:", file);
                if (err) {
                    console.log('ERROR MSG: ', err);
                } else {
                    console.log('Successfully uploaded data');

What this does is read the uploaded file from the local filesystem, then uploads it to S3, then it deletes the temporary file and sends a response.

There's a few problems with this approach. First off, it's not as efficient as it could be, as for large files you will be loading the entire file before you write it. Secondly, this process doesn't support multi-part uploads for large files (I think the cut-off is 5 Mb before you have to do a multi-part upload).

What I would suggest instead is that you use a module I've been working on called S3FS which provides a similar interface to the native FS in Node.JS but abstracts away some of the details such as the multi-part upload and the S3 api (as well as adds some additional functionality like recursive methods).

If you were to pull in the S3FS library your code would look something like this:

var fs = require('fs'),
    S3FS = require('s3fs'),
    s3fsImpl = new S3FS('mybucketname', {
        accessKeyId: XXXXXXXXXXX,
        secretAccessKey: XXXXXXXXXXXXXXXXX

// Create our bucket if it doesn't exist

exports.upload = function (req, res) {
    var file = req.files.file;
    var stream = fs.createReadStream(file.path);
    return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {
        fs.unlink(file.path, function (err) {
            if (err) {

What this will do is instantiate the module for the provided bucket and AWS credentials and then create the bucket if it doesn't exist. Then when a request comes through to upload a file we'll open up a stream to the file and use it to write the file to S3 to the specified path. This will handle the multi-part upload piece behind the scenes (if needed) and has the benefit of being done through a stream, so you don't have to wait to read the whole file before you start uploading it.

If you prefer, you could change the code to callbacks from Promises. Or use the pipe() method with the event listener to determine the end/errors.

If you're looking for some additional methods, check out the documentation for s3fs and feel free to open up an issue if you are looking for some additional methods or having issues.

Xcode 6 iPhone Simulator Application Support location

Open finder>Library>Developer>CoreSimulator>Devices

Then Change Arrangement icon from finder select Date Added

Select your app >data>Container>data>Applications>

choose your app >Documents>Here is your db file

In my case:


Otherwise do this :

NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]); 

- It will print the full path to data folder.


let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
println("App Path: \(dirPaths)")

Removing credits link

It's said here that you should be able to add the following to your chart config:

  credits: {
    enabled: false

that will remove the "" text from the bottom of the chart.

Dart: mapping a list (

you can use => Tab(text: title)).toList()


    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs: => Tab(text: title)).toList()

Best way to implement keyboard shortcuts in a Windows Forms application?

If you have a menu then changing ShortcutKeys property of the ToolStripMenuItem should do the trick.

If not, you could create one and set its visible property to false.

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals


SQL Query Where Date = Today Minus 7 Days

Using dateadd to remove a week from the current date.


"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

please chceck the type of file growth of the database, if its restricted make it unrestricted

Set background image on grid in WPF using C#

All of this can easily be acheived in the xaml by adding the following code in the grid

        <ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>     

Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'

Save PL/pgSQL output from PostgreSQL to a CSV file

Do you want the resulting file on the server, or on the client?

Server side

If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;

This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

  1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
  2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.

Client side

The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

\copy (Select * From foo) To '/tmp/test.csv' With CSV

Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

From the docs:

Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.

How to Allow Remote Access to PostgreSQL database

In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:


Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)

First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf (usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter

listen_addresses = '*'

Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have IP address, add in the pg_hba.conf file:

host all all md5

this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.

Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.


Standard SQL syntax is

DROP TABLE table_name;

IF EXISTS is not standard; different platforms might support it with different syntax, or not support it at all. In PostgreSQL, the syntax is


The first one will throw an error if the table doesn't exist, or if other database objects depend on it. Most often, the other database objects will be foreign key references, but there may be others, too. (Views, for example.) The second will not throw an error if the table doesn't exist, but it will still throw an error if other database objects depend on it.

To drop a table, and all the other objects that depend on it, use one of these.


Use CASCADE with great care.

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

How to ftp with a batch file?


ftp -s:FileName 

as decribed in Windows XP Professional Product Documentation.

The file name that you have to specify in place of FileName must contain FTP commands that you want to send to the server. Among theses commands are

  • open Computer [Port] to connect to an FTP server,
  • user UserName [Password] [Account] to authenticate with the FTP server,
  • get RemoteFile [LocalFile] to retrieve a file,
  • quit to end the FTP session and terminate the ftp program.

More commands can be found under Ftp subcommands.

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

Create ul and li elements in javascript.

Try out below code snippet:

 var list = [];
 var text;

function update() {

    for (var i = 0; i < list.length; i++) {
       console.log( i );
       var letters;
       var ul = document.getElementById("list");
       var li = document.createElement("li");


       letters += "<li>"  + list[i] + "</li>";

 document.getElementById("list").innerHTML = letters;


function myFunction() {
    text = prompt("enter TODO");  

How to serialize an Object into a list of URL query parameters?

This one-liner also handles nested objects and JSON.stringify them as needed:

let qs = Object.entries(obj).map(([k, v]) => `${k}=${encodeURIComponent(typeof (v) === "object" ? JSON.stringify(v) : v)}`).join('&')

Python recursive folder read

Agree with Dave Webb, os.walk will yield an item for each directory in the tree. Fact is, you just don't have to care about subFolders.

Code like this should work:

import os
import sys

rootdir = sys.argv[1]

for folder, subs, files in os.walk(rootdir):
    with open(os.path.join(folder, 'python-outfile.txt'), 'w') as dest:
        for filename in files:
            with open(os.path.join(folder, filename), 'r') as src:

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I got the same problem just doing an npm install. Run with antivirus disabled (if you use Windows Defender, turn off Real-Time protection and Cloud-based protection). That worked for me!

Load image from resources

You can do this using the ResourceManager:

public bool info(string channel)
   object o = Properties.Resources.ResourceManager.GetObject(channel);
   if (o is Image)
       channelPic.Image = o as Image;
       return true;
   return false;

How to add leading zeros?

Here is another alternative for adding leading to 0s to strings such as CUSIPs which can sometimes look like a number and which many applications such as Excel will corrupt and remove the leading 0s or convert them to scientific notation.

When I tried the answer provided by @metasequoia the vector returned had leading spaces and not 0s. This was the same problem mentioned by @user1816679 -- and removing the quotes around the 0 or changing from %d to %s did not make a difference either. FYI, I am using RStudio Server running on an Ubuntu Server. This little two-step solution worked for me:

gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))

using the %>% pipe function from the magrittr package it could look like this:

sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)

I'd prefer a one-function solution, but it works.

Objective-C - Remove last character from string

The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.

In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:

Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters

See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

Use the auto keyword in C++ STL

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.


auto a = 0.0f;  // a is float
auto b = std::vector<int>();  // b is std::vector<int>()

MyType foo()  { return MyType(); }

auto c = foo();  // c is MyType

Setting the value of checkbox to true or false with jQuery

You can do (jQuery 1.6 onwards):

$('#idCheckbox').prop('checked', true);
$('#idCheckbox').prop('checked', false);

to remove you can also use:


with jQuery < 1.6 you must do

$('#idCheckbox').attr('checked', true);

Android map v2 zoom to show all the markers

Working fine for me.

From this code, I am displaying multiple markers with particular zoom on map screen.

// Declared variables

private LatLngBounds bounds;
private LatLngBounds.Builder builder;

// Method for adding multiple marker points with drawable icon

private void drawMarker(LatLng point, String text) {

        MarkerOptions markerOptions = new MarkerOptions();


// For adding multiple markers visible on map

    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        builder = new LatLngBounds.Builder();
    for (int i = 0; i < locationList.size(); i++) {

        drawMarker(new LatLng(Double.parseDouble(locationList.get(i).getLatitude()), Double.parseDouble(locationList.get(i).getLongitude())), locationList.get(i).getNo());

     bounds =;
     CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0);

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

In command line/CLI, you will get this error if your current directory is NOT the repository. So, you have to first CD into the repo.

Mapping US zip code to time zone

Google has a specific API for this:


  dstOffset: 0,
  rawOffset: -18000,
  status: "OK",
  timeZoneId: "America/New_York",
  timeZoneName: "Eastern Standard Time"

They require a unix timestamp on the querystring. From the response returned it appears that timeZoneName takes into account daylight savings, based on the timestamp, while timeZoneId is a DST-independent name for the timezone.

For my use, in Python, I am just passing timestamp=0 and using the timeZoneId value to get a tz_info object from pytz, I can then use that to localize any particular datetime in my own code.

I believe for PHP similarly you can find "America/New_York" in

Better way to find control in ASP.NET

Recursively find all controls matching the specified predicate (do not include root Control):

    public static IEnumerable<Control> FindControlsRecursive(this Control control, Func<Control, bool> predicate)
        var results = new List<Control>();

        foreach (Control child in control.Controls)
            if (predicate(child))

        return results;


myControl.FindControlsRecursive(c => c.ID == "findThisID");

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

bool to int: x = (x == 'true') + 0

Now the x contains 1 if x == 'true' else 0.

Note: x == 'true' will return bool which then will be typecasted to int having value (1 if bool value is True else 0) when added with 0.

Split page vertically using CSS

Check out this fiddle:

CSS/HTML code:

.wrap {_x000D_
    width: 100%;_x000D_
.fleft {_x000D_
    float:left; _x000D_
    width: 33%;_x000D_
    height: 400px;_x000D_
    width: 33%;_x000D_
.fright {_x000D_
float: right;_x000D_
    height: 400px;_x000D_
    width: 33.5%;_x000D_
<div class="wrap">_x000D_
    <!--Updated on 10/8/2016; fixed center alignment percentage-->_x000D_
    <div class="fleft">Left</div>_x000D_
    <div class="fcenter">Center</div>_x000D_
    <div class="fright">Right</div>_x000D_

This uses the CSS float property for left, right, and center alignments of divs on a page.

Fastest way to reset every value of std::vector<int> to 0

As always when you ask about fastest: Measure! Using the Methods above (on a Mac using Clang):

Method      |  executable size  |  Time Taken (in sec) |
            |  -O0    |  -O3    |  -O0      |  -O3     |  
1. memset   | 17 kB   | 8.6 kB  | 0.125     | 0.124    |
2. fill     | 19 kB   | 8.6 kB  | 13.4      | 0.124    |
3. manual   | 19 kB   | 8.6 kB  | 14.5      | 0.124    |
4. assign   | 24 kB   | 9.0 kB  | 1.9       | 0.591    |

using 100000 iterations on an vector of 10000 ints.

Edit: If changeing this numbers plausibly changes the resulting times you can have some confidence (not as good as inspecting the final assembly code) that the artificial benchmark has not been optimized away entirely. Of course it is best to messure the performance under real conditions. end Edit

for reference the used code:

#include <vector>

#define TEST_METHOD 1
const size_t TEST_ITERATIONS = 100000;
const size_t TEST_ARRAY_SIZE = 10000;

int main(int argc, char** argv) {

   std::vector<int> v(TEST_ARRAY_SIZE, 0);

   for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
   #if TEST_METHOD == 1 
      memset(&v[0], 0, v.size() * sizeof v[0]);
   #elif TEST_METHOD == 2
      std::fill(v.begin(), v.end(), 0);
   #elif TEST_METHOD == 3
      for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
         *it = 0;
   #elif TEST_METHOD == 4

   return EXIT_SUCCESS;

Conclusion: use std::fill (because, as others have said its most idiomatic)!

How to read a PEM RSA private key from .NET

You might take a look at JavaScience's source for OpenSSLKey

There's code in there that does exactly what you want to do.

In fact, they have a lot of crypto source code available here.

Source code snippet:

//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider  ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        MemoryStream  mem = new MemoryStream(privkey) ;
        BinaryReader binr = new BinaryReader(mem) ;    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();        //advance 1 byte
                else if (twobytes == 0x8230)
                        binr.ReadInt16();       //advance 2 bytes
                        return null;

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                        return null;
                bt = binr.ReadByte();
                if (bt !=0x00)
                        return null;

                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems) ;

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems) ;

                Console.WriteLine("showing components ..");
                if (verbose) {
                        showBytes("\nModulus", MODULUS) ;
                        showBytes("\nExponent", E);
                        showBytes("\nD", D);
                        showBytes("\nP", P);
                        showBytes("\nQ", Q);
                        showBytes("\nDP", DP);
                        showBytes("\nDQ", DQ);
                        showBytes("\nIQ", IQ);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus =MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                return RSA;
        catch (Exception) {
                return null;
        finally {

How do I use Ruby for shell scripting?

The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.

Some helper function can be used for testing execution result

#!/usr/bin/env ruby
module ShellHelper
  def test(command)
    `#{command} 2> /dev/null`

  def execute(command, raise_on_error = true)
    result = `#{command}`
    raise "execute command failed\n" if (not $?.success?) and raise_on_error
    return $?.success?

  def print_exit(message)
    print "#{message}\n"

  module_function :execute, :print_exit, :test

With helper, the ruby script could be bash alike:

#!/usr/bin/env ruby
require './shell_helper'
include ShellHelper

print_exit "config already exists" if test "ls config"

things.each do |thing|
  next if not test "ls #{thing}/config"
  execute "cp -fr #{thing}/config_template config/#{thing}"

com.jcraft.jsch.JSchException: UnknownHostKey

Has anyone been able to solve this problem? I am using Jscp to scp files using public key authentication (i dont want to use password authentication). Help will be appreciated!!!

This stackoverflow entry is about the host-key checking, and there is no relation to the public key authentication.

As for the public key authentication, try the following sample with your plain(non ciphered) private key,

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.

For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

public class AppCorsConfiguration {
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        return bean;

Unable to convert MySQL date/time value to System.DateTime

I also faced the same problem, and get the columns name and its types. Then cast(col_Name as Char) from table name. From this way i get the problem as '0000-00-00 00:00:00' then I Update as valid date and time the error gets away for my case.

Android Activity without ActionBar

If you're using AppCompat, declare your activity in AndroidManifest.xml as follows:

    android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

Which type of folder structure should be used with Angular 2?

I’ve been using ng cli lately, and it was really tough to find a good way to structure my code.

The most efficient one I've seen so far comes from mrholek repository (

This folder structure allows you to keep your root project clean and structure your components, it avoids redundant (sometimes useless) naming convention of the official Style Guide.

Also it’s, this structure is useful to group import when it’s needed and avoid having 30 lines of import for a single file.

|___ app
|   |___ components/shared
|   |   |___ header
|   |
|   |___ containers/layout
|   |   |___ layout1
|   |
|   |___ directives
|   |   |___ sidebar
|   |
|   |___ services
|   |   |___ *user.service.ts* 
|   | 
|   |___ guards
|   |   |___ *auth.guard.ts* 
|   |
|   |___ views
|   |   |___ about  
|   |
|   |___ *app.component.ts*
|   |
|   |___ *app.module.ts*
|   |
|   |___ *app.routing.ts*
|___ assets
|___ environments
|___ img
|___ scss
|___ *index.html*
|___ *main.ts*

How to clear an EditText on click?

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setCompoundDrawables(null, null, null, null);
        return false;
et.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);

    public void afterTextChanged(Editable arg0) {

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

When should I use the Visitor Design Pattern?

Everyone here is correct, but I think it fails to address the "when". First, from Design Patterns:

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Now, let's think of a simple class hierarchy. I have classes 1, 2, 3 and 4 and methods A, B, C and D. Lay them out like in a spreadsheet: the classes are lines and the methods are columns.

Now, Object Oriented design presumes you are more likely to grow new classes than new methods, so adding more lines, so to speak, is easier. You just add a new class, specify what's different in that class, and inherits the rest.

Sometimes, though, the classes are relatively static, but you need to add more methods frequently -- adding columns. The standard way in an OO design would be to add such methods to all classes, which can be costly. The Visitor pattern makes this easy.

By the way, this is the problem that Scala's pattern matches intends to solve.

get number of columns of a particular row in given excel using Java

There are two Things you can do


int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();


int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Unsupported major.minor version 52.0 when rendering in Android Studio

I had to update Java version to JDK 8 at Jenkins->Manage Jenkins->Global Tool Configuration->JDK.

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

This is what postgres does when a query produces an error and you try to run another query without first rolling back the transaction. (You might think of it as a safety feature, to keep you from corrupting your data.)

To fix this, you'll want to figure out where in the code that bad query is being executed. It might be helpful to use the log_statement and log_min_error_statement options in your postgresql server.

How do I compare version numbers in Python?

What's wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me

>>> (2,3,1) < (10,1,1)
>>> (2,3,1) < (10,1,1,1)
>>> (2,3,1,10) < (10,1,1,1)
>>> (10,3,1,10) < (10,1,1,1)
>>> (10,3,1,10) < (10,4,1,1)

@kindall's solution is a quick example of how good the code would look.

How do I make a simple makefile for gcc on Linux?

Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.

Confirmation dialog on ng-click - AngularJS

ng-click return confirm 100% works

in html file call delete_plot() function

<i class="fa fa-trash delete-plot" ng-click="delete_plot()"></i> 

Add this to your controller

    $scope.delete_plot = function(){
        check = confirm("Are you sure to delete this plot?")
            console.log("yes, OK pressed")
            console.log("No, cancel pressed")


Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

How to use particular CSS styles based on screen size / device

I created a little javascript tool to style elements on screen size without using media queries or recompiling bootstrap css:

Just add class responsive-breakpoints to any element, and it will automagically add xs sm md lg xl classes to those elements.


Pass a javascript variable value into input type hidden value

Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:

Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:

on some event; assign or set the value of the input:



<input id = "inputid" type = "hidden" />

<div id = "idB">This text will be passed to the input</div>

Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.

Beware the differences betwen .html() and .text() when dealing with html forms.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

You need to tell Eclipse which JDK/JRE's you have installed and where they are located.

This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.

Its easier than the description may make it look.

How to open a new file in vim in a new window

Check out gVim. You can launch that in its own window.

gVim makes it really easy to manage multiple open buffers graphically.

You can also do the usual :e to open a new file, CTRL+^ to toggle between buffers, etc...

Another cool feature lets you open a popup window that lists all the buffers you've worked on.

This allows you to switch between open buffers with a single click.

To do this, click on the Buffers menu at the top and click the dotted line with the scissors.

enter image description here

Otherwise you can just open a new tab from your terminal session and launch vi from there.

You can usually open a new tab from terminal with CTRL+T or CTRL+ALT+T

Once vi is launched, it's easy to open new files and switch between them.

Calling class staticmethod within the class body?

This is the way I prefer:

class Klass(object):

    def stat_func():
        return 42

    _ANS = stat_func.__func__()

    def method(self):
        return self.__class__.stat_func() + self.__class__._ANS

I prefer this solution to Klass.stat_func, because of the DRY principle. Reminds me of the reason why there is a new super() in Python 3 :)

But I agree with the others, usually the best choice is to define a module level function.

For instance with @staticmethod function, the recursion might not look very good (You would need to break DRY principle by calling Klass.stat_func inside Klass.stat_func). That's because you don't have reference to self inside static method. With module level function, everything will look OK.

Can I get image from canvas element and use it in img src tag?

Do this. Add this to the bottom of your doc just before you close the body tag.

    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document

    canvasToImg(); //execute the function

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" />

Numpy: find index of the elements within range

This may not be the prettiest, but works for any dimension

a = np.array([[-1,2], [1,5], [6,7], [5,2], [3,4], [0, 0], [-1,-1]])
ranges = (0,4), (0,4) 

def conditionRange(X : np.ndarray, ranges : list) -> np.ndarray:
    idx = set()
    for column, r in enumerate(ranges):
        tmp = np.where(np.logical_and(X[:, column] >= r[0], X[:, column] <= r[1]))[0]
        if idx:
            idx = idx & set(tmp)
            idx = set(tmp)
    idx = np.array(list(idx))
    return X[idx, :]

b = conditionRange(a, ranges)

How to maintain state after a page refresh in React.js?

You can "persist" the state using local storage as Omar Suggest, but it should be done once the state has been set. For that you need to pass a callback to the setState function and you need to serialize and deserialize the objects put into local storage.

constructor(props) {
  this.state = {
    allProjects: JSON.parse(localStorage.getItem('allProjects')) || []

addProject = (newProject) => {

    allProjects: this.state.allProjects.concat(newProject)
  },() => {
    localStorage.setItem('allProjects', JSON.stringify(this.state.allProjects))

Using DISTINCT inner join in SQL

  LEFT JOIN B ON = B.lookupC
  LEFT JOIN A ON = A.lookupB

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.

EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(;

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after &&{
    const data =;

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(;

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

Can a class member function template be virtual?

At least with gcc 5.4 virtual functions could be template members but has to be templates themselves.

#include <iostream>
#include <string>
class first {
    virtual std::string  a1() { return "a1"; }
    virtual std::string  mixt() { return a1(); }

class last {
    virtual std::string a2() { return "a2"; }

template<class T>  class mix: first , T {
    virtual std::string mixt() override;

template<class T> std::string mix<T>::mixt() {
   return a1()+" before "+T::a2();

class mix2: public mix<last>  {
    virtual std::string a1() override { return "mix"; }

int main() {
    std::cout << mix2().mixt();
    return 0;


mix before a2
Process finished with exit code 0

comparing elements of the same array in java

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            System.out.println(a[i] + " not the same with  " + a[k + 1] + "\n");

You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.

How to check Grants Permissions at Run-Time?

Check out the below library in git :


Implementation :

        allprojects {
            repositories {
                maven { url '' }
        dependencies {
            implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
        new RuntimePermission({Current Class Object}, String[] , {ActvityContext});
          String[] : permission array.
          example  : String[] permissionArray = {Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,...} 
    Implement : {PermissionNotify}
    interface notifier methods.
    public void notifyPermissionGrant() {
    public void notifyPermissionDeny() {

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

    isSetFirst = true;

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    isSetLast = true;

public void addPart(final String key, final String value) {
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {


public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = != -1) {
            out.write(tmp, 0, l);
    } catch (final IOException e) {

    } finally {
        try {
        } catch (final IOException e) {


public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {


public long getContentLength() {
    return out.toByteArray().length;

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);

public boolean isChunked() {
    return false;

public boolean isRepeatable() {
    return false;

public boolean isStreaming() {
    return false;

public void writeTo(final OutputStream outstream) throws IOException {

public Header getContentEncoding() {
    return null;

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());


Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        Log.e("Upload Exception", "");

Service for uploading

$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    

if (file_exists("Images/".$new_image_name))
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
                     $email = $_REQUEST['email'];

    $sql ="insert into alert(images) values('$static_url')";


    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));

How to iterate over the files of a certain directory, in Java?

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders

Grouping functions (tapply, by, aggregate) and the *apply family

It is maybe worth mentioning ave. ave is tapply's friendly cousin. It returns results in a form that you can plug straight back into your data frame.

dfr <- data.frame(a=1:20, f=rep(LETTERS[1:5], each=4))
means <- tapply(dfr$a, dfr$f, mean)
##  A    B    C    D    E 
## 2.5  6.5 10.5 14.5 18.5 

## great, but putting it back in the data frame is another line:

dfr$m <- means[dfr$f]

dfr$m2 <- ave(dfr$a, dfr$f, FUN=mean) # NB argument name FUN is needed!
##   a f    m   m2
##   1 A  2.5  2.5
##   2 A  2.5  2.5
##   3 A  2.5  2.5
##   4 A  2.5  2.5
##   5 B  6.5  6.5
##   6 B  6.5  6.5
##   7 B  6.5  6.5
##   ...

There is nothing in the base package that works like ave for whole data frames (as by is like tapply for data frames). But you can fudge it:

dfr$foo <- ave(1:nrow(dfr), dfr$f, FUN=function(x) {
    x <- dfr[x,]
##     a f    m   m2    foo
## 1   1 A  2.5  2.5    25
## 2   2 A  2.5  2.5    25
## 3   3 A  2.5  2.5    25
## ...

Where is the kibana error log? Is there a kibana error log?

For kibana 6.x on Windows, edit the shortcut to "kibana -l " folder must exist.

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 does LayoutInflater in Android do?

When you use a custom view in a ListView you must define the row layout. You create an xml where you place android widgets and then in the adapter's code you have to do something like this:

public MyAdapter(Context context, List<MyObject> objects) extends ArrayAdapter {
  super(context, 1, objects);
  /* We get the inflator in the constructor */
  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

public View getView(int position, View convertView, ViewGroup parent) {
  View view;
  /* We inflate the xml which gives us a view */
  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

  /* Get the item in the adapter */
  MyObject myObject = getItem(position);

  /* Get the widget with id name which is defined in the xml of the row */
  TextView name = (TextView) view.findViewById(;

  /* Populate the row's xml with info from the item */

  /* Return the generated view */
  return view;

Read more in the official documentation.

Is there a way I can capture my iPhone screen as a video?

i guess it is so obvious now that no one has posted this but for the noobs.... note: iPhone 4S only

just airplay to an apple tv and video mirror then output the atv to a device that can record - like tivo, dvr etc. you can also use a video out cable on the iPad [1 and 2] now

not sure if the cable works on the iPhone 4S as I havent tested that myself

its clunky but there is no other way i can see atm.

Transposing a 1D NumPy array

It's working exactly as it's supposed to. The transpose of a 1D array is still a 1D array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.)

If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with np.newaxis (or None, they're the same, newaxis is just more readable).

import numpy as np
a = np.array([5,4])[np.newaxis]

Generally speaking though, you don't ever need to worry about this. Adding the extra dimension is usually not what you want, if you're just doing it out of habit. Numpy will automatically broadcast a 1D array when doing various calculations. There's usually no need to distinguish between a row vector and a column vector (neither of which are vectors. They're both 2D!) when you just want a vector.

How do I integrate Ajax with Django applications?

Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin and assumes an Author model.

import json

from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class AjaxableResponseMixin(object):
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
            return self.render_to_json_response(data)
            return response

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author
    fields = ['name']

Source: Django documentation, Form handling with class-based views

The link to version 1.6 of Django is no longer available updated to version 1.11

How to set column header text for specific column in Datagridview C#

If you work with visual studio designer, you will probably have defined fields for each columns in the YourForm.Designer.cs file e.g.:

private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;    
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; 

If you give them useful names, you can set the HeaderText easily:

usefulNameForDataGridViewTextBoxColumn.HeaderText = "Useful Header Text";

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:


Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.


Here's what would happen trying to access the following URLs from

URL                                             RESULT       -> Success -> Success                    -> Success (default port for HTTP)                  -> Failure: different port       -> Failure: different hostname   -> Failure: different protocol                     -> Failure: different protocol & port       -> Failure: different protocol, port & hostname 


Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, '');

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

How to sort an associative array by its values in Javascript?

Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.

The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:

var tuples = [];

for (var key in obj) tuples.push([key, obj[key]]);

tuples.sort(function(a, b) {
    a = a[1];
    b = b[1];

    return a < b ? -1 : (a > b ? 1 : 0);

for (var i = 0; i < tuples.length; i++) {
    var key = tuples[i][0];
    var value = tuples[i][1];

    // do something with key and value

You may find it more natural to wrap this in a function which takes a callback:

function bySortedValue(obj, callback, context) {_x000D_
  var tuples = [];_x000D_
  for (var key in obj) tuples.push([key, obj[key]]);_x000D_
  tuples.sort(function(a, b) {_x000D_
    return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0_x000D_
  var length = tuples.length;_x000D_
  while (length--), tuples[length][0], tuples[length][1]);_x000D_
  foo: 1,_x000D_
  bar: 7,_x000D_
  baz: 3_x000D_
}, function(key, value) {_x000D_
  document.getElementById('res').innerHTML += `${key}: ${value}<br>`_x000D_
<p id='res'>Result:<br/><br/><p>

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Best way to make WPF ListView/GridView sort on column-header clicking?

After search alot, finaly i found simple here

private GridViewColumnHeader listViewSortCol = null;
private SortAdorner listViewSortAdorner = null;
private void GridViewColumnHeader_Click(object sender, RoutedEventArgs e)
  GridViewColumnHeader column = (sender as GridViewColumnHeader);
  string sortBy = column.Tag.ToString();
  if (listViewSortCol != null)

  ListSortDirection newDir = ListSortDirection.Ascending;
  if (listViewSortCol == column && listViewSortAdorner.Direction == newDir)
    newDir = ListSortDirection.Descending;

  listViewSortCol = column;
  listViewSortAdorner = new SortAdorner(listViewSortCol, newDir);
  yourListView.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir));


public class SortAdorner : Adorner
    private static Geometry ascGeometry =
        Geometry.Parse("M 0 4 L 3.5 0 L 7 4 Z");

    private static Geometry descGeometry =
        Geometry.Parse("M 0 0 L 3.5 4 L 7 0 Z");

    public ListSortDirection Direction { get; private set; }

    public SortAdorner(UIElement element, ListSortDirection dir)
        : base(element)
        this.Direction = dir;

    protected override void OnRender(DrawingContext drawingContext)

        if(AdornedElement.RenderSize.Width < 20)

        TranslateTransform transform = new TranslateTransform
                AdornedElement.RenderSize.Width - 15,
                (AdornedElement.RenderSize.Height - 5) / 2

        Geometry geometry = ascGeometry;
        if(this.Direction == ListSortDirection.Descending)
            geometry = descGeometry;
        drawingContext.DrawGeometry(Brushes.Black, null, geometry);



<GridViewColumn Width="250">
    <GridViewColumnHeader Tag="Name" Click="GridViewColumnHeader_Click">Name</GridViewColumnHeader>
        <TextBlock Text="{Binding Name}" ToolTip="{Binding Name}"/>

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
>>> print(mystring[:1])
>>> print(mystring[3])
>>> print(mystring[-1])
>>> print(mystring[2:3])
>>> print(mystring[2:4])

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
>>> myarray[0][-1]
>>> myarray[0][1:3]

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015:

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc:

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

from   person p
where LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

from   person p
where  UPPER( LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

from   person p
where LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
        public CustomerGroupingKey(string country, string gender)
            Country = country;
            Gender = gender;

        public string Country { get; }

        public string Gender { get; }

What is a monad?

You should first understand what a functor is. Before that, understand higher-order functions.

A higher-order function is simply a function that takes a function as an argument.

A functor is any type construction T for which there exists a higher-order function, call it map, that transforms a function of type a -> b (given any two types a and b) into a function T a -> T b. This map function must also obey the laws of identity and composition such that the following expressions return true for all p and q (Haskell notation):

map id = id
map (p . q) = map p . map q

For example, a type constructor called List is a functor if it comes equipped with a function of type (a -> b) -> List a -> List b which obeys the laws above. The only practical implementation is obvious. The resulting List a -> List b function iterates over the given list, calling the (a -> b) function for each element, and returns the list of the results.

A monad is essentially just a functor T with two extra methods, join, of type T (T a) -> T a, and unit (sometimes called return, fork, or pure) of type a -> T a. For lists in Haskell:

join :: [[a]] -> [a]
pure :: a -> [a]

Why is that useful? Because you could, for example, map over a list with a function that returns a list. Join takes the resulting list of lists and concatenates them. List is a monad because this is possible.

You can write a function that does map, then join. This function is called bind, or flatMap, or (>>=), or (=<<). This is normally how a monad instance is given in Haskell.

A monad has to satisfy certain laws, namely that join must be associative. This means that if you have a value x of type [[[a]]] then join (join x) should equal join (map join x). And pure must be an identity for join such that join (pure x) == x.

How to set a variable inside a loop for /F

You probably want SETLOCAL ENABLEDELAYEDEXPANSION. See for details.

Basically: Normal %variables% are expanded right aftercmd.exe reads the command. In your case the "command" is the whole

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo %z%
    echo %%a

loop. At that point z has no value yet, so echo %z% turns into echo. Then the loop is executed and z is set, but its value isn't used anymore.

SETLOCAL ENABLEDELAYEDEXPANSION enables an additional syntax, !variable!. This also expands variables but it only does so right before each (sub-)command is executed.

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo !z!
    echo %%a

This gives you the current value of z each time the echo runs.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Draw on HTML5 Canvas using a mouse

Here is a working sample.

    <script type="text/javascript">_x000D_
    var canvas, ctx, flag = false,_x000D_
        prevX = 0,_x000D_
        currX = 0,_x000D_
        prevY = 0,_x000D_
        currY = 0,_x000D_
        dot_flag = false;_x000D_
    var x = "black",_x000D_
        y = 2;_x000D_
    function init() {_x000D_
        canvas = document.getElementById('can');_x000D_
        ctx = canvas.getContext("2d");_x000D_
        w = canvas.width;_x000D_
        h = canvas.height;_x000D_
        canvas.addEventListener("mousemove", function (e) {_x000D_
            findxy('move', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mousedown", function (e) {_x000D_
            findxy('down', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseup", function (e) {_x000D_
            findxy('up', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseout", function (e) {_x000D_
            findxy('out', e)_x000D_
        }, false);_x000D_
    function color(obj) {_x000D_
        switch ( {_x000D_
            case "green":_x000D_
                x = "green";_x000D_
            case "blue":_x000D_
                x = "blue";_x000D_
            case "red":_x000D_
                x = "red";_x000D_
            case "yellow":_x000D_
                x = "yellow";_x000D_
            case "orange":_x000D_
                x = "orange";_x000D_
            case "black":_x000D_
                x = "black";_x000D_
            case "white":_x000D_
                x = "white";_x000D_
        if (x == "white") y = 14;_x000D_
        else y = 2;_x000D_
    function draw() {_x000D_
        ctx.moveTo(prevX, prevY);_x000D_
        ctx.lineTo(currX, currY);_x000D_
        ctx.strokeStyle = x;_x000D_
        ctx.lineWidth = y;_x000D_
    function erase() {_x000D_
        var m = confirm("Want to clear");_x000D_
        if (m) {_x000D_
            ctx.clearRect(0, 0, w, h);_x000D_
            document.getElementById("canvasimg").style.display = "none";_x000D_
    function save() {_x000D_
        document.getElementById("canvasimg").style.border = "2px solid";_x000D_
        var dataURL = canvas.toDataURL();_x000D_
        document.getElementById("canvasimg").src = dataURL;_x000D_
        document.getElementById("canvasimg").style.display = "inline";_x000D_
    function findxy(res, e) {_x000D_
        if (res == 'down') {_x000D_
            prevX = currX;_x000D_
            prevY = currY;_x000D_
            currX = e.clientX - canvas.offsetLeft;_x000D_
            currY = e.clientY - canvas.offsetTop;_x000D_
            flag = true;_x000D_
            dot_flag = true;_x000D_
            if (dot_flag) {_x000D_
                ctx.fillStyle = x;_x000D_
                ctx.fillRect(currX, currY, 2, 2);_x000D_
                dot_flag = false;_x000D_
        if (res == 'up' || res == "out") {_x000D_
            flag = false;_x000D_
        if (res == 'move') {_x000D_
            if (flag) {_x000D_
                prevX = currX;_x000D_
                prevY = currY;_x000D_
                currX = e.clientX - canvas.offsetLeft;_x000D_
                currY = e.clientY - canvas.offsetTop;_x000D_
    <body onload="init()">_x000D_
        <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
        <div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
        <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
        <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
        <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
        <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
        <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_

Can Google Chrome open local links?

The LocalLinks extension from the most popular answer didn't work for me (given, I was trying to use file:// to open a directory in windows explorer, not a file), so I looked into another workaround. I found that this "Open in IE" extension is a good workaround:

This isn't an ideal fix, as instead of clicking the link, users will have to right-click and choose Open in IE, but it at least makes the link functional.

One thing to note though, in IE10 (and IE9 after a certain update point) you will have to add the site to your Trusted Sites (Internet Options > Security > Trusted sites). If the site is not in trusted sites, the file:// link does not work in IE either.

How do I update all my CPAN modules to their latest versions?

An alternative method to using upgrade from the default CPAN shell is to use cpanminus and cpan-outdated.

These are so easy and nimble to use that I hardly ever go back to CPAN shell. To upgrade all of your modules in one go, the command is:

cpan-outdated -p | cpanm

I recommend you install cpanminus like the docs describe:

curl -L | perl - App::cpanminus

And then install cpan-outdated along with all other CPAN modules using cpanm:

cpanm App::cpanoutdated

BTW: If you are using perlbrew then you will need to repeat this for every Perl you have installed under it.

You can find out more about cpanminus and cpan-outdated at the Github repos here:

Line Break in XML?

<description><![CDATA[first line<br/>second line<br/>]]></description>

Importing packages in Java

Here is the right way to do imports in Java.

import Dan.Vik;
class Kab
public static void main(String args[])
    Vik Sam = new Vik();

You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

How can I debug a Perl script?

The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.

Brian Kernighan, "Unix for Beginners" (1979)

(And enhancing print statements with Data::Dumper)

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
        'not running'
    end as run_status from processes

How to write a basic swap function in Java

Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.

In Java there aren't really pointers, so this won't work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection.

We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn't help you, try posting the calling code as we'll probably have a good idea of how to solve the real problem Java-style.

What is difference between XML Schema and DTD?

DTD can have only two types of data, the CDATA and the PCDATA. But in a schema you can use all the primitive data type that you use in the programming language and you have the flexibility of defining your own custom data types.

The developer building a schema can create custom data types based on the core data types and by using different operators and modifiers.

How do I create a shortcut via command-line in Windows?

I would like to propose different solution which wasn't mentioned here which is using .URL files:

set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%


  • By default .url files are intended to open web pages but they are working fine for any properly constructed URI
  • Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
  • IconFile and IconIndex are optional
  • For reference you can check An Unofficial Guide to the URL File Format of Edward Blake

error MSB6006: "cmd.exe" exited with code 1

error MSB6006: "cmd.exe" exited with code -Solved

I also face this problem . In my case it is due to output exe already running .I solved my problem simply close the application instance before building.

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';

HTML radio buttons allowing multiple selections

Try this way of formation, it is rather fancy ...

Have a look at this jsfiddle


The idea is to choose a the radio as a button instead of the normal circle image.

Get array elements from index to end

The [:-1] removes the last element. Instead of




You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Powershell script does not run via Scheduled Tasks

One more idea that worked. It's really silly, but, apparently, the default target OS setting (bottom right corner of the screen) is Vista / Windows Server 2008. As we're past the 10 year mark, it is likely that your Powershell script will not be compatible to these.

Changing the target to Windows Server 2016, as shown on the screenshot below, did the trick for me.

Change the setting on the screenshot

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How do I get the last day of a month?

You can find the last date of any month by this code:

var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);

Disable double-tap "zoom" option in browser on touch devices

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> 

I've used that very recently and it works fine on iPad. Haven't tested on Android or other devices (because the website will be displayed on iPad only).

Pretty-Print JSON Data to a File using Python

You could redirect a file to python and open using the tool and to read it use more.

The sample code will be,

cat filename.json | python -m json.tool | more

Check whether a path is valid

Try Uri.IsWellFormedUriString():

  • The string is not correctly escaped. name
  • The string is an absolute Uri that represents an implicit file Uri.

  • The string is an absolute URI that is missing a slash before the path.

  • The string contains unescaped backslashes even if they are treated as forward slashes.

  • The string represents a hierarchical absolute Uri and does not contain "://".
  • The parser for the Uri.Scheme indicates that the original string was not well-formed.

      The example depends on the scheme of the URI.

What is Dispatcher Servlet in Spring?

You can say Dispatcher Servlet acts as an entry and exit point for any request. Whenever a request comes it first goes to the Dispatcher Servlet(DS) where the DS then tries to identify its handler method ( the methods you define in the controller to handle the requests ), once the handler mapper (The DS asks the handler mapper) returns the controller the dispatcher servlet knows the controller which can handle this request and can now go to this controller to further complete the processing of the request. Now the controller can respond with an appropriate response and then the DS goes to the view resolver to identify where the view is located and once the view resolver tells the DS it then grabs that view and returns it back to you as the final response. I am adding an image which I took from YouTube from the channel Java Guides.

Dispatcher Servlet in Action

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

The following worked for me. Just add the following snippet:

android {
        compileSdkVersion 25
        buildToolsVersion '25.0.1'

defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
dexOptions {
        javaMaxHeapSize "4g"

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

On Windows Vista/7, with UAC, administrator accounts run programs in unprivileged mode by default.

Programs must prompt for administrator access before they run as administrator, with the ever-so-familiar UAC dialog. Since Python scripts aren't directly executable, there's no "Run as Administrator" context menu option.

It's possible to use ctypes.windll.shell32.IsUserAnAdmin() to detect whether the script has admin access, and ShellExecuteEx with the 'runas' verb on python.exe, with sys.argv[0] as a parameter to prompt the UAC dialog if needed.

How to put a component inside another component in Angular2?

You don't put a component in directives

You register it in @NgModule declarations:

  imports: [ BrowserModule ],
  declarations: [ App , MyChildComponent ],
  bootstrap: [ App ]

and then You just put it in the Parent's Template HTML as : <my-child></my-child>

That's it.

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;



public class Q7704827_SimpleRead
    public static void
    main(String[] args)
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);

The library and its documentation are at

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

If you happen to use LuaSocket in your project, or just have it installed and don't mind to use it, you can use the socket.sleep(time) function which sleeps for a given amount of time (in seconds).

This works both on Windows and Unix, and you do not have to compile additional modules.

I should add that the function supports fractional seconds as a parameter, i.e. socket.sleep(0.5) will sleep half a second. It uses Sleep() on Windows and nanosleep() elsewhere, so you may have issues with Windows accuracy when time gets too low.

Center button under form in bootstrap

If you're using Bootstrap 4, try this:

<div class="mx-auto text-center">
    <button id="button" name="button" class="btn btn-primary">Press Me!</button>

Rounding a variable to two decimal places C#

Use Math.Round and specify the number of decimal places.


Math.Round Method (Double, Int32)

Rounds a double-precision floating-point value to a specified number of fractional digits.

Or Math.Round Method (Decimal, Int32)

Rounds a decimal value to a specified number of fractional digits.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

The following trick resolved this issue for me:

  • Right click on the code editor
  • Hover on Maven and expand
  • Click on Reimport

My idea version is 12.0.4

How to calculate a logistic sigmoid function in Python?

Use the numpy package to allow your sigmoid function to parse vectors.

In conformity with Deeplearning, I use the following code:

import numpy as np
def sigmoid(x):
    s = 1/(1+np.exp(-x))
    return s

Difference between abstraction and encapsulation?

  • Abstraction lets you focus on what the object does instead of how it does it
  • Encapsulation means hiding the internal details or mechanics of how an object does something.

Like when you drive a car, you know what the gas pedal does but you may not know the process behind it because it is encapsulated.

Let me give an example in C#. Suppose you have an integer:

int Number = 5;
string aStrNumber = Number.ToString();

you can use a method like Number.ToString() which returns you characters representation of the number 5, and stores that in a string object. The method tells you what it does instead of how it does it.

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:


Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …

How to empty ("truncate") a file on linux that already exists and is protected in someway?

Since sudo will not work with redirection >, I like the tee command for this purpose

echo "" | sudo tee fileName

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

Best way to alphanumeric check in JavaScript

I would create a String prototype method:

String.prototype.isAlphaNumeric = function() {
  var regExp = /^[A-Za-z0-9]+$/;
  return (this.match(regExp));

Then, the usage would be:

var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username = email

    def __repr__(self):
        return '<User %r>' % self.username


admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User


admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your _you also need to import the db object from this module.

Rename multiple columns by names

If the table contains two columns with the same name then the code goes like this,


How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:


In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Specifying content of an iframe instead of the src attribute to a page

In combination with what Guffa described, you could use the technique described in Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.

CASE .. WHEN expression in Oracle SQL


How to access cookies in AngularJS?

This is how you can set and get cookie values. This is what I was originally looking for when I found this question.

Note we use $cookieStore instead of $cookies

<!DOCTYPE html>
<html ng-app="myApp">
  <script src=""></script>
  <script src=""></script>
    angular.module('myApp', ['ngCookies']);
    function CookieCtrl($scope, $cookieStore) {
      $scope.lastVal = $cookieStore.get('tab');

      $scope.changeTab = function(tabName){
          $scope.lastVal = tabName;
          $cookieStore.put('tab', tabName);
<body ng-controller="CookieCtrl">
    <!-- ... -->