Programs & Examples On #Zebra printers

Zebra printers are generally thermal bar code label and receipt printers which can understand ZPL, EPL, CPCL, or KPL languages

.NET code to send ZPL to Zebra printers

@liquide's answer works great.

System.IO.File.Copy(inputFilePath, printerPath);

Which I found from the Zebra's ZPL Programmer's Guide Volume 1 (2005) enter image description here

Send raw ZPL to Zebra printer via USB

ZPL is the correct way to go. In most cases it is correct to use a driver that abstracts to GDI commands; however Zebra label printers are a special case. The best way to print to a Zebra printer is to generate ZPL directly. Note that the actual printer driver for a Zebra printer is a "plain text" printer - there is not a "driver" that could be updated or changed in the sense we think of most printers having drivers. It's just a driver in the absolute minimalist sense.

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

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

You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.

In some cases a StringBuffer might help you instead.

axios post request to send form data

i needed to calculate the content length aswell

const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()

const config = {headers: formHeaders}

return, form, config)
.then(res => {
    console.log(`form uploaded`)

How to access parent Iframe from JavaScript

you can use parent to access the parent page. So to access a function it would be:

var obj = parent.getElementById('foo');

Facebook API: Get fans of / people who like a page

Technically this FQL query should work, but for some reason Facebook disallows it because of a missing index. Not sure if that is because of policy or they just forgot.

SELECT uid FROM page_fans WHERE page_id="YOUR_PAGE_ID"

ORA-00054: resource busy and acquire with NOWAIT specified

You'll have to wait. The session that was killed was in the middle of a transaction and updated lots of records. These records have to be rollbacked and some background process is taking care of that. In the meantime you cannot modify the records that were touched.

What is a loop invariant?

Loop invariant is a mathematical formula such as (x=y+1). In that example, x and y represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible to x and y values and see if they produce any bug. Lets say x is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables. After all, we just try to understand the behavior of the program.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .

Simplest way to download and unzip files in Node.js cross-platform?

I found success with the following, works with .zip
(Simplified here for posting: no error checking & just unzips all files to current folder)

function DownloadAndUnzip(URL){
    var unzip = require('unzip');
    var http = require('http');
    var request = http.get(URL, function(response) {

Binding to static property

As of WPF 4.5 you can bind directly to static properties and have the binding automatically update when your property is changed. You do need to manually wire up a change event to trigger the binding updates.

public class VersionManager
    private static String _filterString;        

    /// <summary>
    /// A static property which you'd like to bind to
    /// </summary>
    public static String FilterString
            return _filterString;

            _filterString = value;

            // Raise a change event

    // Declare a static event representing changes to your static property
    public static event EventHandler FilterStringChanged;

    // Raise the change event through this static method
    protected static void OnFilterStringChanged(EventArgs e)
        EventHandler handler = FilterStringChanged;

        if (handler != null)
            handler(null, e);

    static VersionManager()
        // Set up an empty event handler
        FilterStringChanged += (sender, e) => { return; };


You can now bind your static property just like any other:

<TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>

What does the "@" symbol do in SQL?

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Trim spaces from start and end of string

ECMAScript 5 supports trim and this has been implemented in Firefox.

trim - MDC

addEventListener not working in IE8


if (_checkbox.addEventListener) {
    _checkbox.addEventListener("click", setCheckedValues, false);
else {
    _checkbox.attachEvent("onclick", setCheckedValues);

Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

What really confused me was that there are two different sets of build settings: 1) for the Project 2) for the Target

In the sidebar (top left) there is a blue icon that represents your project. Click that: enter image description here

Then in the main panel to the right, in the top bar, just to the left of the word, "General," there is a small icon of your Project. Click that, and now select the Target in the pop-up menu that appears:

the Target selection

Once you've selected the Target, now the build settings for the target can be changed. They are different than the ones for the Project itself... weird! I'm not sure why there are build settings for the Project as a whole, that are different from the Target, since the Target's settings are what gets used during building. So why even have settings for the Project? Not sure.

But that's how you change them. This solved the issue for me: go into the Target (not the Project!) under Code Signing > Provisioning Profile > and change the settings to the proper profile. For a long time I was just changing them in the Project only, since I didn't know I was supposed to select the Target, and I kept having this issue. This fixes it!

"/usr/bin/ld: cannot find -lz"

I just encountered this problem and contrary to the accepted solution of "your make files are broken" and "host includes should never be included in a cross compile"

The android build includes many host executables used by the SDK to build an android app. In my case the make stopped while building zipalign, which is used to optimize an apk before installing on an android device.

Installing lib32z1-dev solved my problem, under Ubuntu you can install it with the following command:

sudo apt-get install lib32z1-dev

How to do join on multiple criteria, returning all combinations of both criteria

SELECT  aa.*,
FROM    table1 aa
        INNER JOIN table2 bb
            ON aa.tableseat = bb.tableseat AND
                aa.weddingtable = bb.weddingtable
        INNER JOIN
            SELECT  a.tableSeat
            FROM    table1 a
                    INNER JOIN table2 b
                        ON a.tableseat = b.tableseat AND
                            a.weddingtable = b.weddingtable
            WHERE b.meal IN ('chicken', 'steak')
            GROUP by a.tableSeat
            HAVING COUNT(DISTINCT b.Meal) = 2
        ) c ON aa.tableseat = c.tableSeat

How to get array keys in Javascript?

If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:


Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

Saving an Object (Data persistence)

You could use the pickle module in the standard library. Here's an elementary application of it to your example:

import pickle

class Company(object):
    def __init__(self, name, value): = name
        self.value = value

with open('company_data.pkl', 'wb') as output:
    company1 = Company('banana', 40)
    pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as input:
    company1 = pickle.load(input)
    print(  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(input)
    print( # -> spam
    print(company2.value)  # -> 42

You could also define your own simple utility like the following which opens a file and writes a single object to it:

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

# sample usage
save_object(company1, 'company1.pkl')


Since this is such a popular answer, I'd like touch on a few slightly advanced usage topics.

cPickle (or _pickle) vs pickle

It's almost always preferable to actually use the cPickle module rather than pickle because the former is written in C and is much faster. There are some subtle differences between them, but in most situations they're equivalent and the C version will provide greatly superior performance. Switching to it couldn't be easier, just change the import statement to this:

import cPickle as pickle

In Python 3, cPickle was renamed _pickle, but doing this is no longer necessary since the pickle module now does it automatically—see What difference between pickle and _pickle in python 3?.

The rundown is you could use something like the following to ensure that your code will always use the C version when it's available in both Python 2 and 3:

    import cPickle as pickle
except ModuleNotFoundError:
    import pickle

Data stream formats (protocols)

pickle can read and write files in several different, Python-specific, formats, called protocols as described in the documentation, "Protocol version 0" is ASCII and therefore "human-readable". Versions > 0 are binary and the highest one available depends on what version of Python is being used. The default also depends on Python version. In Python 2 the default was Protocol version 0, but in Python 3.8.1, it's Protocol version 4. In Python 3.x the module had a pickle.DEFAULT_PROTOCOL added to it, but that doesn't exist in Python 2.

Fortunately there's shorthand for writing pickle.HIGHEST_PROTOCOL in every call (assuming that's what you want, and you usually do), just use the literal number -1 — similar to referencing the last element of a sequence via a negative index. So, instead of writing:

pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

You can just write:

pickle.dump(obj, output, -1)

Either way, you'd only have specify the protocol once if you created a Pickler object for use in multiple pickle operations:

pickler = pickle.Pickler(output, -1)

Note: If you're in an environment running different versions of Python, then you'll probably want to explicitly use (i.e. hardcode) a specific protocol number that all of them can read (later versions can generally read files produced by earlier ones).

Multiple Objects

While a pickle file can contain any number of pickled objects, as shown in the above samples, when there's an unknown number of them, it's often easier to store them all in some sort of variably-sized container, like a list, tuple, or dict and write them all to the file in a single call:

tech_companies = [
    Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
save_object(tech_companies, 'tech_companies.pkl')

and restore the list and everything in it later with:

with open('tech_companies.pkl', 'rb') as input:
    tech_companies = pickle.load(input)

The major advantage is you don't need to know how many object instances are saved in order to load them back later (although doing so without that information is possible, it requires some slightly specialized code). See the answers to the related question Saving and loading multiple objects in pickle file? for details on different ways to do this. Personally I like @Lutz Prechelt's answer the best. Here's it adapted to the examples here:

class Company:
    def __init__(self, name, value): = name
        self.value = value

def pickled_items(filename):
    """ Unpickle a file of pickled data. """
    with open(filename, "rb") as f:
        while True:
                yield pickle.load(f)
            except EOFError:

print('Companies in pickle file:')
for company in pickled_items('company_data.pkl'):
    print('  name: {}, value: {}'.format(, company.value))

Changing directory in Google colab (breaking out of the python interpreter)

Use os.chdir. Here's a full example:


!mkdir abc
!echo "file" > abc/123.txt

import os

# Now the directory 'abc' is the current working directory.
# and will show 123.txt.

How to convert minutes to hours/minutes and add various time values together using jQuery?

As the above answer of ConnorLuddy can be slightly improved, there are a minor change to formula to convert minutes to hours:mins format

const convertMinsToHrsMins = (mins) => {
  let h = Math.floor(mins / 60);
  let m = Math.round(mins % 60);
  h = (h < 10) ? ('0' + h) : (h);
  m = (m < 10) ? ('0' + m) : (m);
  return `${h}:${m}`;

My theory is that we can not predict that `mins` value will always be an integer.
The added `Math.round` to function will correct the output.
For example: when the minutes=125.3245, the output will be 02:05 with this fix, and 02:05.3245000000000005 without the fix.

Hope that someone need this!

How to detect if a stored procedure already exists

You can write a query as follows:

IF OBJECT_ID('ProcedureName','P') IS NOT NULL
    DROP PROC ProcedureName

CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....

To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P

This query will find the procedure and if it is available it will drop it and create new one.

For detailed information about OBJECT_ID and Object types please visit : SYS.Objects

dropdownlist set selected value in MVC3 Razor

For anyone that dont want to or dont make sense to use dropdownlistfor, here is how I did it in jQuery with .NET MVC set up.

  1. Front end Javascript -> getting data from model:
    var settings = @Html.Raw(Json.Encode(Model.GlobalSetting.NotificationFrequencySettings)); 


    function SelectNotificationSettings(settings) {
                $.each(settings, function (i, value) {
                    $("#" + value.NotificationItemTypeId + " option[value=" + value.NotificationFrequencyTypeId + "]").prop("selected", true);
  1. In razor html, you going to have few dropdownlist
    notificationFrequencyOptions, optionLabel:=DbRes.T("Default", "CommonLabels"),
    htmlAttributes:=New With {.class = "form-control notification-item-type", .id = Convert.ToInt32(NotificationItemTypeEnum.GenerateSubscriptionNotification)})

And when page load, you js function is going to set the selected option based on value that's stored in @model.


How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/");
header("Content-Disposition: attachment; filename=$file");
echo $test;

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

"Register" an .exe so you can run it from any command line in Windows

In order to make it work

You need to modify the value of the environment variable with the name key Path, you can add as many paths as you want separating them with ;. The paths you give to it can't include the name of the executable file.

If you add a path to the variable Path all the excecutable files inside it can be called from cmd or porweshell by writing their name without .exe and these names are not case sensitive.

Here is how to create a system environment variable from a python script:

It is important to run it with administrator privileges in order to make it work. To better understand the code, just read the comments on it.

Tested on Windows 10

import winreg

# Create environment variable for call the program from shell, only works with compiled version
def environment_var(AppPath):

    # Point to the registry key of the system environment variables
    key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')

    def add_var(path):
        # Add the variable
        winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, path)

        # Try to get the value of the Path variable
        allPaths = winreg.QueryValueEx(key, 'Path')[0]
    except Exception:
        # Create the Path variable if it doesn't exist

    # Get all the values of the existing paths

    # If the Path is empty, add the application path
    if Path == ['']:

    # Check if the application path is in the Path variable
    if AppPath not in Path:
        # Add the application path to the Path environment variable and add keep the others existing paths

# Only run this if the module is not imported by another
if __name__ == "__main__":
    # Run the function

You can find more information in the winreg documentation

PHP write file from input to txt

A possible solution:

$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file

You were closing the script before close de file.

How to jQuery clone() and change id?

This is the simplest solution working for me.

$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works. The find command can output many parameters. For example, add the following to the --printf clause:

%a for attributes in the octal format
%n for the file name including a complete path


find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file

Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.

Matplotlib scatter plot legend

Here's an easier way of doing this (source: here):

import matplotlib.pyplot as plt
from numpy.random import rand

fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')


And you'll get this:

enter image description here

Take a look at here for legend properties

How to reset Jenkins security settings from the command line?

To reset it without disabling security if you're using matrix permissions (probably easily adaptable to other login methods):

  1. In config.xml, set disableSignup to false.
  2. Restart Jenkins.
  3. Go to the Jenkins web page and sign up with a new user.
  4. In config.xml, duplicate one of the <permission>hudson.model.Hudson.Administer:username</permission> lines and replace username with the new user.
  5. If it's a private server, set disableSignup back to true in config.xml.
  6. Restart Jenkins.
  7. Go to the Jenkins web page and log in as the new user.
  8. Reset the password of the original user.
  9. Log in as the original user.

Optional cleanup:

  1. Delete the new user.
  2. Delete the temporary <permission> line in config.xml.

No securities were harmed during this answer.

How to apply filters to *ngFor?

For this requirement, I implement and publish a generic component. See

For use this components, before, install this package with npm:

npm install w-ng5 --save

After, import module in app.module

import { PipesModule } from 'w-ng5';

In the next step, add in declare section of app.module:

imports: [

Sample use

Filtering simple string

<input type="text"  [(ngModel)]="filtroString">
  <li *ngFor="let s of getStrings() | filter:filtroString">

Filtering complex string - field 'Value' in level 2

<input type="text"  [(ngModel)]="search">
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}

Filtering complex string - middle field - 'Value' in level 1

<input type="text"  [(ngModel)]="search3">
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.valor1', value: search3}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}

Filtering complex array simple - field 'Nome' level 0

<input type="text"  [(ngModel)]="search2">
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'nome', value: search2}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}

Filtering in tree fields - field 'Valor' in level 2 or 'Valor' in level 1 or 'Nome' in level 0

<input type="text"  [(ngModel)]="search5">
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search5}, {field:'n1.valor1', value: search5}, {field:'nome', value: search5}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}

Filtering nonexistent field - 'Valor' in nonexistent level 3

<input type="text"  [(ngModel)]="search4">
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.n3.valor3', value: search4}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}

This component work with infinite attribute level...

Why not use tables for layout in HTML?

I'm going to go through your arguments one after another and try to show the errors in them.

It's good to separate content from layout But this is a fallacious argument; Cliché Thinking.

It's not fallacious at all because HTML was designed intentionally. Misuse of an element might not be completely out of question (after all, new idioms have developed in other languages, as well) but possible negative implications have to be counterbalanced. Additionally, even if there were no arguments against misusing the <table> element today, there might be tomorrow because of the way browser vendors apply special treatment to the element. After all, they know that “<table> elements are for tabular data only” and might use this fact to improve the rendering engine, in the process subtly changing how <table>s behave, and thus breaking cases where it was previously misused.

So what? Does my boss care? Do my users care?

Depends. Is your boss pointy-haired? Then he might not care. If she's competent, then she will care, because the users will.

Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and css.

The majority of professional web developers seem to oppose you[citation needed]. That tables are in fact less maintainable should be obvious. Using tables for layout means that changing the corporate layout will in fact mean changing every single page. This can be very expensive. On the other hand, judicious use of semantically meaningful HTML combined with CSS might confine such changes to the CSS and the pictures used.

By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs.

Deeply nested <div>s are an anti-pattern just as table layouts. Good web designers don't need many of them. On the other hand, even such deep-nested divs don't have many of the problems of table layouts. In fact, they can even contribute to a semantic structure by logically dividing the content in parts.

Readability of the code I think it's the other way around. Most people understand html, little understand css. It's simpler.

“Most people” don't matter. Professionals matter. For professionals, table layouts create many more problems than HTML + CSS. This is like saying I shouldn't use GVim or Emacs because Notepad is simpler for most people. Or that I shouldn't use LaTeX because MS Word is simpler for most people.

It's better for SEO not to use tables

I don't know if this is true and wouldn't use this as an argument but it would be logical. Search engines search for relevant data. While tabular data could of course be relevant, it's rarely what users search for. Users search for terms used in the page title or similarly prominent positions. It would therefore be logical to exclude tabular content from filtering and thus cutting the processing time (and costs!) by a large factor.

Tables are slower. An extra tbody element has to be inserted. This is peanuts for modern web browsers.

The extra element has got nothing to do with tables being slower. On the other hand, the layout algorithm for tables is much harder, the browser often has to wait for the whole table to load before it can begin to layout the content. Additionally, caching of the layout won't work (CSS can easily be cached). All this has been mentioned before.

Show me some benchmarks where the use of a table significantly slows down a page.

Unfortunately, I don't have any benchmark data. I would be interested in it myself because it's right that this argument lacks a certain scientific rigour.

Most web sites that need an upgrade need new content (html) as well. Scenarios where a new version of a web site only needs a new css file are not very likely.

Not at all. I've worked on several cases where changing the design was simplified by a separation of content and design. It's often still necessary to change some HTML code but the changes will always be much more confined. Additionally, design changes must on occasion be made dynamically. Consider template engines such as the one used by the WordPress blogging system. Table layouts would literally kill this system. I've worked on a similar case for a commercial software. Being able to change the design without changing the HTML code was one of the business requirements.

Another thing. Table layout makes automated parsing of websites (screen scraping) much harder. This might sound trivial because, after all, who does it? I was surprised myself. Screen scraping can help a lot if the service in question doesn't offer a WebService alternative to access its data. I'm working in bioinformatics where this is a sad reality. Modern web techniques and WebServices have not reached most developers and often, screen scraping is the only way to automate the process of getting data. No wonder that many biologists still perform such tasks manually. For thousands of data sets.

How to put more than 1000 values into an Oracle IN clause

select column_X, ... from my_table
where ('magic', column_X ) in (
        ('magic', 1),
        ('magic', 2),
        ('magic', 3),
        ('magic', 4),
        ('magic', 99999)
    ) ...

How to code a BAT file to always run as admin mode?

go get


sudo Example1Server.exe

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

XOR operation with two strings in java

This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.

import android.util.Base64;

public class StringXORer {

public String encode(String s, String key) {
    return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));

public String decode(String s, String key) {
    return new String(xorWithKey(base64Decode(s), key.getBytes()));

private byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
        out[i] = (byte) (a[i] ^ key[i%key.length]);
    return out;

private byte[] base64Decode(String s) {
    return Base64.decode(s,Base64.DEFAULT);

private String base64Encode(byte[] bytes) {
    return new String(Base64.encode(bytes,Base64.DEFAULT));


want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

The following code gives expected output. Is that you want?

import java.util.Calendar;
import java.util.Date;

public class DateAndTime {

    public static void main(String[] args) throws Exception {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
        String strDate = sdf.format(cal.getTime());
        System.out.println("Current date in String Format: " + strDate);

        SimpleDateFormat sdf1 = new SimpleDateFormat();
        sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
        Date date = sdf1.parse(strDate);
        String string=sdf1.format(date);
        System.out.println("Current date in Date Format: " + string);


GitHub center image

Just jump straight down to look at the 4 examples (1.1, 1.2, 1.3, and 1.4) in the section below called "1. Centering and aligning images in GitHub readmes using the deprecated HTML align attribute"!

Also, view actual examples of this on GitHub in a couple readme markdown files in my repositories here:

  2. and
    1. enter image description here

Background on how to center and align images in markdown:

So, it turns out that GitHub explicitly blocks/filters out all attempts at editing any form of CSS (Cascading Style Sheets) styles (including external, internal, and inline) inside GitHub *.md markdown files, such as readmes. See here (emphasis added):

  1. Custom css file for in a Github repo

    GitHub does not allow for CSS to affect files through CSS for security reasons...


    Unfortunately you cannot use CSS in GitHub markdown as it is a part of the sanitization process.

    The HTML is sanitized, aggressively removing things that could harm you and your kin—such as script tags, inline-styles, and class or id attributes.


So, that means to center or align images in GitHub readmes, your only solution is to use the deprecated HTML align attribute (that happens to still function), as this answer shows.

I should also point out that although that solution does indeed work, it is causing a lot of confusion for that answer to claim to use inline css to solve the problem, since, like @Poikilos points out in the comments, that answer has no CSS in it whatsoever. Rather, the align="center" part of the <p> element is a deprecated HTML attribute (that happens to still function) and is NOT CSS. All CSS, whether external, internal, or inline is banned from GitHub readmes and explicitly removed, as indicated through trial-and-error and in the two references above.

This leads me to split my answer into two answers here:

  1. "Centering and aligning images in GitHub readmes using the deprecated HTML align attribute", and
  2. "Centering and aligning images using modern CSS in any markdown document where you also have control over CSS styles".

Option 2 only works in places where you have full control over CSS styles, such as in a custom GitHub Pages website you make maybe?

1. Centering and aligning images in GitHub readmes using the deprecated HTML align attribute:

This works in any GitHub *.md markdown file, such as a GitHub file. It relies on the deprecated HTML align attribute, but still works fine. You can see a full demo of this in an actual GitHub readme in my eRCaGuy_hello_world repo here:


  1. Be sure to set width="100%" inside each of your <p> paragraph elements below, or else the entire paragraph tries to allow word wrap around it, causing weird and less-predicable effects.
  2. To resize your image, simly set width="30%", or whatever percent you'd like between 0% and 100%, to get the desired effect! This is much easier than trying to set a pixel size, such as width="200" height="150", as using a width percent automatically adjusts to your viewer's screen and to the page display width, and it automatically resizes the image as you resize your browser window as well. It also avoids skewing the image into unnatural proportions. It's a great feature!
  3. Options for the (deprecated) HTML align attribute include left, center, right, and justify.

1.1. Align images left, right, or centered, with NO WORD WRAP:


**Align left:**
<p align="left" width="100%">
    <img width="33%" src=""> 

**Align center:**
<p align="center" width="100%">
    <img width="33%" src=""> 

**Align right:**
<p align="right" width="100%">
    <img width="33%" src=""> 

Produces this:

enter image description here

If you'd like to set the text itself to left, center, or right, you can include the text inside the <p> element as well, as regular HTML, like this:

<p align="right" width="100%">
    This text is also aligned to the right.<br>
    <img width="33%" src=""> 

To produce this:

enter image description here

1.2. Align images left, right, or centered, WITH word wrap:


**Align left (works fine):**

<img align="left" width="33%" src=""> 

[Arduino]( (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.

**Align center (doesn't really work):**

<img align="center" width="33%" src=""> 

[Arduino]( (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.

**Align right (works fine):**

<img align="right" width="33%" src=""> 

[Arduino]( (/??r'dwi?no?/) is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. Its hardware products are licensed under a CC-BY-SA license, while software is licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially from the official website or through authorized distributors. Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards ('shields') or breadboards (for prototyping) and other circuits.

Produces this:

enter image description here

1.3. Align images side-by-side:

Reminder: MAKE SURE TO GIVE THE entire <p> paragraph element the full 100% column width (width="100%", as shown below) or else text gets word-wrapped around it, botching your vertical alignment and vertical spacing/formatting you may be trying to maintain!


33% width each (_possibly_ a little too wide to fit all 3 images side-by-side, depending on your markdown viewer):
<p align="center" width="100%">
    <img width="33%" src=""> 
    <img width="33%" src=""> 
    <img width="33%" src=""> 

32% width each (perfect size to just barely fit all 3 images side-by-side):
<p align="center" width="100%">
    <img width="32%" src=""> 
    <img width="32%" src=""> 
    <img width="32%" src=""> 

31% width each:
<p align="center" width="100%">
    <img width="31%" src=""> 
    <img width="31%" src=""> 
    <img width="31%" src=""> 

30% width each:
<p align="center" width="100%">
    <img width="30%" src=""> 
    <img width="30%" src=""> 
    <img width="30%" src=""> 

Produces this:

enter image description here

I am aligning all paragraph <p> elements above to the center, but you can also align left or right, as shown in previous examples, to force the row of images to get aligned that way too. Example:


Align the whole row of images to the right this time:
<p align="right" width="100%">
    <img width="25%" src=""> 
    <img width="25%" src=""> 
    <img width="25%" src=""> 

Produces this (aligning the whole row of images according to the align attribute set above, or to the right in this case). Generally, center is preferred, as done in the examples above.

enter image description here

1.4. Use a markdown table to improve vertical spacing of odd-sized/odd-shaped images:

Sometimes, with odd-sized or different-shaped images, using just the "row of images" methods above produces slightly awkward-looking results.

This code produces two rows of images which have good horizontal spacing, but bad vertical spacing. This code:

<p align="center" width="100%">
    <img width="32%" src="photos/pranksta1.jpg"> 
    <img width="32%" src="photos/pranksta2.jpg"> 
    <img width="32%" src="photos/pranksta3.jpg"> 
<p align="center" width="100%">
    <img width="32%" src="photos/pranksta4.jpg"> 
    <img width="32%" src="photos/pranksta5.jpg"> 
    <img width="32%" src="photos/pranksta6.jpg"> 

Produces this, since the last image in row 1 ("pranksta3.jpg") is a very tall image with 2x the height as the other images:

enter image description here

So, placing those two rows of images inside a markdown table forces nice-looking vertical spacing. Notice in the markdown table below that each image is set to have an HTML width attribute set to 100%. This is because it is relative to the table cell the image sits in, NOT relative to the page column width anymore. Since we want each image to fill the entire width of each cell, we set their widths all to width="100%".

This markdown table with images in it:

|                                               |                                               |                                               |
| <img width="100%" src="photos/pranksta1.jpg"> | <img width="100%" src="photos/pranksta2.jpg"> | <img width="100%" src="photos/pranksta3.jpg"> |
| <img width="100%" src="photos/pranksta4.jpg"> | <img width="100%" src="photos/pranksta5.jpg"> | <img width="100%" src="photos/pranksta6.jpg"> |

Produces this, which looks much nicer and more well-spaced in my opinion, since vertical spacing is also centered for each row of images:

enter image description here

2. Centering and aligning images using modern CSS in any markdown document where you also have control over CSS styles:

This works in any markdown file, such as a GitHub Pages website maybe?, where you do have full control over CSS styles. This does NOT work in any GitHub *.md markdown file, such as a, therefore, because GitHub expliclty scans for and disables all custom CSS styling you attempt to use. See above.


Use this HTML/CSS to add and center an image and set its size to 60% of the screen space width inside your markdown file, which is usually a good starting value:

<img src="" 

Change the width CSS value to whatever percent you want, or remove it altogether to use the markdown default size, which I think is 100% of the screen width if the image is larger than the screen, or it is the actual image width otherwise.


Or, keep reading for a lot more information.

Here are various HTML and CSS options which work perfectly inside markdown files, so long as CSS is not explicitly forbidden:

1. Center and configure (resize) ALL images in your markdown file:

Just copy and paste this to the top of your markdown file to center and resize all images in the file (then just insert any images you want with normal markdown syntax):


Or, here is the same code as above but with detailed HTML and CSS comments to explain exactly what is going on:

<!-- (This is an HTML comment). Copy and paste this entire HTML `<style>...</style>` element (block)
to the top of your markdown file -->
/* (This is a CSS comment). The below `img` style sets the default CSS styling for all images
hereafter in this markdown file. */
    /* Default display value is `inline-block`. Set it to `block` to prevent surrounding text from
    wrapping around the image. Instead, `block` format will force the text to be above or below the
    image, but never to the sides. */
    /* Common float options are `left`, `right`, and `none`. Set to `none` to override any previous
    settings which might have been `left` or `right`. `left` causes the image to be to the left,
    with text wrapped to the right of the image, and `right` causes the image to be to the right,
    with text wrapped to its left, so long as `display:inline-block` is also used. */
    /* Set both the left and right margins to `auto` to cause the image to be centered. */
    /* You may also set the size of the image, in percent of width of the screen on which the image
    is being viewed, for example. A good starting point is 60%. It will auto-scale and auto-size
    the image no matter what screen or device it is being viewed on, maintaining proporptions and 
    not distorting it. */
    /* You may optionally force a fixed size, or intentionally skew/distort an image by also 
    setting the height. Values for `width` and `height` are commonly set in either percent (%) 
    or pixels (px). Ex: `width:100%;` or `height:600px;`. */
    /* height:400px; */

Now, whether you insert an image using markdown:


Or HTML in your markdown file:

<img src=""> will be automatically centered and sized to 60% of the screenview width, as described in the comments within the HTML and CSS above. (Of course the 60% size is really easily changeable too, and I present simple ways below to do it on an image-by-image basis as well).

2. Center and configure images on a case-by-case basis, one at a time:

Whether or not you have copied and pasted the above <style> block into the top of your markdown file, this will also work, as it overrides and takes precedence over any file-scope style settings you may have set above:

<img src="" style="display:block;float:none;margin-left:auto;margin-right:auto;width:60%"> 

You can also format it on multiple lines, like this, and it will still work:

<img src="" 
     alt="this is an optional description of the image to help the blind and show up in case the 
          image won't load" 
     style="display:block; /* override the default display setting of `inline-block` */ 
            float:none; /* override any prior settings of `left` or `right` */ 
            /* set both the left and right margins to `auto` to center the image */
            width:60%; /* optionally resize the image to a screen percentage width if you want too */

3. In addition to all of the above, you can also create CSS style classes to help stylize individual images:

Add this whole thing to the top of your markdown file.


/* By default, make all images center-aligned, and 60% of the width 
of the screen in size */

/* Create a CSS class to style images to left-align, or "float left" */
    /* provide a 15 pixel gap between the image and the text to its right */

/* Create a CSS class to style images to right-align, or "float right" */
    /* provide a 15 pixel gap between the image and the text to its left */


Now, your img CSS block has set the default setting for images to be centered and 60% of the width of the screen space in size, but you can use the leftAlign and rightAlign CSS classes to override those settings on an image-by-image basis.

For example, this image will be center-aligned and 60% in size (the default I set above):

<img src=""> 

This image will be left-aligned, however, with text wrapping to its right, using the leftAlign CSS class we just created above!

<img src="" class="leftAlign">

It might look like this:

enter image description here

You can still override any of its CSS properties via the style attribute, however, such as width, like this:

<img src="" class="leftAlign" style="width:20%">

And now you'll get this:

enter image description here

4. Create 3 CSS classes, but don't change the img markdown defaults

Another option to what we just showed above, where we modified the default img property:value settings and created 2 classes, is to just leave all the default markdown img properties alone, but create 3 custom CSS classes, like this:


/* Create a CSS class to style images to center-align */
    /* Set both the left and right margins to `auto` to cause the image to be centered. */

/* Create a CSS class to style images to left-align, or "float left" */
    /* provide a 15 pixel gap between the image and the text to its right */

/* Create a CSS class to style images to right-align, or "float right" */
    /* provide a 15 pixel gap between the image and the text to its left */


Use them, of course, like this:

<img src="" class="centerAlign" style="width:20%">

Notice how I manually set the width property using the CSS style attribute above, but if I had something more complicated I wanted to do, I could also create some additional classes like this, adding them inside the <style>...</style> block above:

/* custom CSS class to set a predefined "small" size for an image */
    /* set any other properties, as desired, inside this class too */

Now you can assign multiple classes to the same object, like this. Simply [separate class names by a space, NOT a comma][11]. In the event of conflicting settings, I believe whichever setting comes last will be the one that takes effect, overriding any previously-set settings. This should also be the case in the event you set the same CSS properties multiple times in the same CSS class or inside the same HTML style attribute.

<img src="" class="centerAlign small">

5. Consolidate Common Settings in CSS Classes:

The last trick is one I learned in this answer here: How can I use CSS to style multiple images differently?. As you can see above, all 3 of the CSS align classes set the image width to 60%. Therefore, this common setting can be set all at once like this if you wish, then you can set the specific settings for each class afterwards:


/* set common properties for multiple CSS classes all at once */
.centerAlign, .leftAlign, .rightAlign {

/* Now set the specific properties for each class individually */

/* Create a CSS class to style images to center-align */
    /* Set both the left and right margins to `auto` to cause the image to be centered. */

/* Create a CSS class to style images to left-align, or "float left" */
    /* provide a 15 pixel gap between the image and the text to its right */

/* Create a CSS class to style images to right-align, or "float right" */
    /* provide a 15 pixel gap between the image and the text to its left */

/* custom CSS class to set a predefined "small" size for an image */
    /* set any other properties, as desired, inside this class too */


More Details:

1. My thoughts on HTML and CSS in Markdown

As far as I'm concerned, anything which can be written in a markdown document and get the desired result is all we are after, not some "pure markdown" syntax.

In C and C++, the compiler compiles down to assembly code, and the assembly is then assembled down to binary. Sometimes, however, you need the low-level control that only assembly can provide, and so you can write inline assembly right inside of a C or C++ source file. Assembly is the "lower level" language and it can be written right inside C and C++.

So it is with markdown. Markdown is the high-level language which is interpreted down to HTML and CSS. However, where we need extra control, we can just "inline" the lower-level HTML and CSS right inside of our markdown file, and it will still be interpreted correctly. In a sense, therefore, HTML and CSS are valid "markdown" syntax.

So, to center an image in markdown, use HTML and CSS.

2. Standard image insertion in markdown:

How to add a basic image in markdown with default "behind-the-scenes" HTML and CSS formatting:

This markdown:


Will produce this output:

This is my fire-shooting hexacopter I made.

You can also optionally add a description in the opening square brackets. Honestly I'm not even sure what that does, but perhaps it gets converted into an [HTML <img> element alt attribute][12], which gets displayed in case the image can't load, and may be read by screen readers for the blind. So, this markdown:

![this is my hexacopter I built](

will also produce this output:

this is my hexacopter I built

3. More details on what's happening in the HTML/CSS when centering and resizing an image in markdown:

Centering the image in markdown requires that we use the extra control that HTML and CSS can give us directly. You can insert and center an individual image like this:

<img src="" 
     alt="this is my hexacopter I built" 

PHP, display image with Header()

Though weirdly named, you can use the getimagesize() function. This will also give you mime information:

    [0] => 295 // width
    [1] => 295 // height
    [2] => 3 //
    [3] => width="295" height="295" // width and height as attr's
    [bits] => 8
    [mime] => image/png

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

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

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

Step-by-step debugging with IPython

(Update on May 28, 2016) Using RealGUD in Emacs

For anyone in Emacs, this thread shows how to accomplish everything described in the OP (and more) using

  1. a new important debugger in Emacs called RealGUD which can operate with any debugger (including ipdb).
  2. The Emacs package isend-mode.

The combination of these two packages is extremely powerful and allows one to recreate exactly the behavior described in the OP and do even more.

More info on the wiki article of RealGUD for ipdb.

Original answer:

After having tried many different methods for debugging Python, including everything mentioned in this thread, one of my preferred ways of debugging Python with IPython is with embedded shells.

Defining a custom embedded IPython shell:

Add the following on a script to your PYTHONPATH, so that the method ipsh() becomes available.

import inspect

# First import the embed function
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config

# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = '   .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '

# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")   
exit_msg = '**Leaving Nested interpreter'

# Wrap it in a function that gives me more context:
def ipsh():
    ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg   = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)

    # Go back one level! 
    # This is needed because the call to ipshell is inside the function ipsh()

Then, whenever I want to debug something in my code, I place ipsh() right at the location where I need to do object inspection, etc. For example, say I want to debug my_function below

Using it:

def my_function(b):
  a = b
  ipsh() # <- This will embed a full-fledged IPython interpreter
  a = 4

and then I invoke my_function(2) in one of the following ways:

  1. Either by running a Python program that invokes this function from a Unix shell
  2. Or by invoking it directly from IPython

Regardless of how I invoke it, the interpreter stops at the line that says ipsh(). Once you are done, you can do Ctrl-D and Python will resume execution (with any variable updates that you made). Note that, if you run the code from a regular IPython the IPython shell (case 2 above), the new IPython shell will be nested inside the one from which you invoked it, which is perfectly fine, but it's good to be aware of. Eitherway, once the interpreter stops on the location of ipsh, I can inspect the value of a (which be 2), see what functions and objects are defined, etc.

The problem:

The solution above can be used to have Python stop anywhere you want in your code, and then drop you into a fully-fledged IPython interpreter. Unfortunately it does not let you add or remove breakpoints once you invoke the script, which is highly frustrating. In my opinion, this is the only thing that is preventing IPython from becoming a great debugging tool for Python.

The best you can do for now:

A workaround is to place ipsh() a priori at the different locations where you want the Python interpreter to launch an IPython shell (i.e. a breakpoint). You can then "jump" between different pre-defined, hard-coded "breakpoints" with Ctrl-D, which would exit the current embedded IPython shell and stop again whenever the interpreter hits the next call to ipsh().

If you go this route, one way to exit "debugging mode" and ignore all subsequent breakpoints, is to use ipshell.dummy_mode = True which will make Python ignore any subsequent instantiations of the ipshell object that we created above.

Export data from Chrome developer tool

from Chrome 76, you have Import/Export buttons.

enter image description here

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

Docker - alternative approach

Docker is some-kind of super-fast virtual machine which can be use to run tools like node (instead install them directly on mac-os). Advantages to do it are following

  • all stuff ('milions' node files) are install inside docker image/container (they encapsulated in few inner-docker files)

  • you can map your mac directory with project to your docker container and have access to node - but outside docker, mac-os sytem don't even know that node is installed. So you get some kind of 'virtual' console with available node commands which can works on real files

  • you can easily kill node by find it by docker ps and kill by docker rm -f name_or_num

  • you can easily uninstall docker image/containers by one command docker rmi ... and get free space - and install it again by run script (below)

  • your node is encapsulated inside docker and don't have access to whole system - only to folders you map to it

  • you can run node services and easily map they port to mac port and have access to it from web browser

  • you can run many node versions at the same time

  • in similar way you can install other tools like (in many versions in same time): php, databases, redis etc. - inside docker without any interaction with mac-os (which not notice such software at all). E.g. you can run at the same time 3 mysql db with different versions and 3 php application with different php version ... - so you can have many tools but clean system

  • TEAM WORK: such enviroment can be easily cloned into other machines (and even to windows/linux systems - with some modifications) and provide identical docker-level environment - so you can easily set up and reuse you scripts/dockerfiles, and setup environment for new team member in very fast way (he just need to install docker and create similar folder-structure and get copy of scripts - thats all). I work this way for 2 year and with my team - and we are very happy


  • Install docker using e.g. this instructions

  • Prepare 'special' directory for work e.g. my directory is /Users/kamil/work (I will use this directory further - but it can be arbitrary) - this directory will be 'interface' between docker containers and your mac file ststem. Inside this dir create following dir structure:

    /Users/kamil/work/code - here you put your projects with code


    /Users/kamil/work/tools/docker-data - here we map containers output data like logs (or database files if someone ouse db etc.)


    /Users/kamil/work/tools/docker/node-cmd - here we put docker node scripts

  • inside tools create file .env which will contain in one place global-paths used in other scripts


  • innside dir ../node-cmd create file dockerfile with following content

    # default  /var/www/html (mapped to .../code folder with projects)
    FROM node
    WORKDIR /work
    # Additional arbitrary tools (ng, gulp, bower)
    RUN npm install -g n @angular/cli bower gulp grunt
    CMD while true; do sleep 10000; done
    # below ports are arbitrary
    EXPOSE 3002 3003 3004 4200

  • innside dir ../node-cmd create file run-container with following content (this file should be executable e.g. by chmod +x run-container) - (notice how we map port-s and directories form external 'world' to internal docker filesystem)

    set -e
    cd -- "$(dirname "$0")" # this script dir (not set on doubleclick)
    source ../../.env
    if [ ! "$(docker ps | grep node-cmd)" ] 
      docker build -t node-cmd .
      docker rm -f node-cmd |:
      docker run -d --name node-cmd -p 4200:4200 -p 4201:4201 -p 3002:3002 -p 3003:3003 -p 3004:3004 -v $toolsdir/node-cmd/logs:/root/.npm/_logs -v $workdir:/work node-cmd

  • ok now you can add some project e.g. work/code/myProject and add to it following file 'run-cmd' (must be executable)

    cd -- "$(dirname "$0")"
    docker exec -it node-cmd bash -c "cd /work/code/myProject; bash"

  • then if you run above script (by double-click), you will see console with available node commands in project directory e.g. npm install

  • to run project in background (e.g some serwice) e.g. run web-server angular-cli application you can use following script (named run-front -must be executable) - (you must also edit /etc/hosts file to add proper domain)

    cd -- "$(dirname "$0")"
    open "http://my-angular.local:3002"
    docker exec -it node-cmd  /bin/sh -c "cd /work/code/my-angular-project; npm start"
    cat         # for block script and wait for user ctrl+C

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')

writeObject('blue') ? enter image description here

Finding Key associated with max Value in a Java Map

For my project, I used a slightly modified version of Jon's and Fathah's solution. In the case of multiple entries with the same value, it returns the last entry it finds:

public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map) {        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();

        if(null != value && max == value) {
            maxEntry = entry;

    return maxEntry;

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

How to normalize a vector in MATLAB efficiently? Any related built-in function?

I took Mr. Fooz's code and also added Arlen's solution too and here are the timings that I've gotten for Octave:

clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V);         end; toc % 7.0 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 6.4 s
tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 5.5 s
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.6 s
tic; for i=1:N, V1 = V/norm(V);         end; toc % 7.1 s
tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.7 s

Then, because of something I'm currently looking at, I tested out this code for ensuring that each row sums to 1:

clc; clear all;
m = 2048;
V = rand(m);
N = 100;
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m));                end; toc % 8.2 s
tic; for i=1:N, V2 = bsxfun(@rdivide, V, sum(V,2));            end; toc % 5.8 s
tic; for i=1:N, V3 = bsxfun(@rdivide, V, V*ones(m,1));         end; toc % 5.7 s
tic; for i=1:N, V4 = V ./ (V*ones(m,m));                       end; toc % 77.5 s
tic; for i=1:N, d = 1./sum(V,2);V5 = bsxfun(@times, V, d);     end; toc % 2.83 s
tic; for i=1:N, d = 1./(V*ones(m,1));V6 = bsxfun(@times, V, d);end; toc % 2.75 s
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m));                end; toc % 8.2 s

How to get the mobile number of current sim card in real device?

I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?

Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...

Add permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>


import android.telephony.TelephonyManager;

Use the below code:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         // get IMEI
         imei = tm.getDeviceId();

         // get SimSerialNumber
         simSerialNumber = tm.getSimSerialNumber();

What is makeinfo, and how do I get it?

Need to install texinfo. configure will still have the cache of its results so it will still think makeinfo is missing. Blow away your source and unpack it again from the tarball. run configure then make.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

Look at android-tablayouthelper

Automatically switch TabLayout.MODE_FIXED and TabLayout.MODE_SCROLLABLE depends on total tab width.

How to get my project path?

This gives you the root folder:


You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)


For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

In R, how to find the standard error of the mean?

The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:

> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972

node.js string.replace doesn't work?

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");  

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");  

What happened to console.log in IE8?

I'm using Walter's approach from above (see:

I mix in a solution I found here to properly show Objects.

This means the trap function becomes:

function trap(){
        // create an Array from the arguments Object           
        var args =;
        // console.raw captures the raw args, without converting toString
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
        var message = args.join(' ');
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));

I hope this is helpful:-)

PHP - Copy image to my server direct from URL

Two ways, if you're using PHP5 (or higher)

copy('', '/tmp/file.png');

If not, use file_get_contents

//Get the file
$content = file_get_contents("");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.png", "w");
fwrite($fp, $content);

From this SO post

How to save username and password with Mercurial?

You can make an auth section in your .hgrc or Mercurial.ini file, like so:

bb.prefix =
bb.username = foo
bb.password = foo_passwd

The ‘bb’ part is an arbitrary identifier and is used to match prefix with username and password - handy for managing different username/password combos with different sites (prefix)

You can also only specify the user name, then you will just have to type your password when you push.

I would also recommend to take a look at the keyring extension. Because it stores the password in your system’s key ring instead of a plain text file, it is more secure. It is bundled with TortoiseHg on Windows, and there is currently a discussion about distributing it as a bundled extension on all platforms.

How to initialise memory with new operator in C++?

you can always use memset:

int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Very easy, forget CSS targeting the input["type"] thing, it doesn't work for me. I don't know why. I got my solution in my HTML tag

<input type="file" style="color:transparent; width:70px;"/>

End of the problem

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

I posted a general approach for troubleshooting the "DLL load failed" problem in this post on Windows systems. For reference:

  1. Use the DLL dependency analyzer Dependencies to analyze <Your Python Dir>\Lib\site-packages\tensorflow\python\_pywrap_tensorflow_internal.pyd and determine the exact missing DLL (indicated by a ? beside the DLL). The path of the .pyd file is based on the TensorFlow 1.9 GPU version that I installed. I am not sure if the name and path is the same in other TensorFlow versions.

  2. Look for information of the missing DLL and install the appropriate package to resolve the problem.

Can I change the color of Font Awesome's icon color?

just give and text style whatever you want like :D HTML:

<a href="javascript:;" class="fa fa-trash" style="color:#d9534f;">
   <span style="color:black;">Text Name</span>

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

I was facing same issue for changing default gradle version from 5.0 to 4.7, Below are the steps to change default gradle version in intellij enter image description here
1) Change gradle version in gradle/wrapper/ in this property distributionUrl

2) Hit refresh button in gradle projects menu so that it will start downloading new gradle zip version

Clean up a fork and restart it from the upstream

Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.

remote: error: GH003: Sorry, force-pushing to master is not allowed.

If you get an error message like this one please try the following steps.

To effectively reset your fork you need to follow these steps :

git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin

Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :

git checkout master
git push --force origin

Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :

git push origin --delete tmp_master
git branch -D tmp_master

Other answers warning about lossing your change still apply, be carreful.

Static linking vs dynamic linking

One reason to do a statically linked build is to verify that you have full closure for the executable, i.e. that all symbol references are resolved correctly.

As a part of a large system that was being built and tested using continuous integration, the nightly regression tests were run using a statically linked version of the executables. Occasionally, we would see that a symbol would not resolve and the static link would fail even though the dynamically linked executable would link successfully.

This was usually occurring when symbols that were deep seated within the shared libs had a misspelt name and so would not statically link. The dynamic linker does not completely resolve all symbols, irrespective of using depth-first or breadth-first evaluation, so you can finish up with a dynamically linked executable that does not have full closure.

Regex Last occurrence?

A negative look ahead is a correct answer, but it can be written more cleanly like:


This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.

Why do I have ORA-00904 even when the column is present?

Check the username credential used to login to the database. (persistence.xml ??). The problem mostly is, the username\password used to login to the database, does not have visiblity to the object (table_name in this case). ( try logging in to sql developer, using the same username\password available in your data source)

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

Cannot declare instance members in a static class in C#

It is not legal to declare an instance member in a static class. Static class's cannot be instantiated hence it makes no sense to have an instance members (they'd never be accessible).

Importing csv file into R - numeric values read as characters

Including this in the read.csv command worked for me: strip.white = TRUE

(I found this solution here.)

Call php function from JavaScript

PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -


Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

history.replaceState() example?

I really wanted to respond to @Sev's answer.

Sev is right, there is a bug inside the window.history.replaceState

To fix this simply rewrite the constructor to set the title manually.

var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
    var title_ = document.getElementsByTagName('title')[0];
    if(title_ != undefined){
        title_.innerHTML = title;
        var title__ = document.createElement('title');
        title__.innerHTML = title;
        var head_ = document.getElementsByTagName('head')[0];
        if(head_ != undefined){
            var head__ = document.createElement('head');
    replaceState_tmp(obj,title, url);

Efficient way to Handle ResultSet in Java

this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.

private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    Map<String, List<Object>> map = new HashMap<>(columns);
    for (int i = 1; i <= columns; ++i) {
        map.put(md.getColumnName(i), new ArrayList<>());
    while ( {
        for (int i = 1; i <= columns; ++i) {

    return map;

Explain ExtJS 4 event handling

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
             * describe the event


Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

How to create a QR code reader in a HTML5 website?

The algorithm that drives is a JavaScript implementation of I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

What is the difference between UTF-8 and Unicode?

If I may summarise what I gathered from this thread:

Unicode 'translates' characters to ordinal numbers (in decimal form).

à -> 224

UTF-8 is an encoding that 'translates' these ordinal numbers (in decimal form) to binary representations.

224 -> 11000011 10100000

Note that we're talking about the binary representation of 224, not its binary form, which is 0b11100000.

How to close the current fragment by using Button like the back button?

Try this:

public void removeFragment(Fragment fragment){ fragmentManager = getSupportFragmentManager(); fragmentTransaction = fragmentManager.beginTransaction();


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

Root cause: Corrupted user profile of user account used to start database

The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:


According to the link provided by @royki:

The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.

This would explain why other respondents had success after changing to different accounts:

  • bmjjr suggests changing to "NT AUTHORITY\NETWORK SERVICE"
  • comments to @bmjjr indicate different accounts "I used NT AUTHORITY\LOCAL SERVICE. That helped too"
  • @Julio Nobre had success with "NT Authority\System "

Fix: reset the corrupt user profile

To fix the user profile that's causing the error, follow the steps listed KB947215.

The main steps from KB947215 are summarized as follows:-

  1. Open regedit
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
  3. Navigate to the SID for the corrupted profile

    To find the SID, click on each SID GUID, review the value for the ProfileImagePath value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:

The main system account SIDs of interest are:

SID          Name               Also Known As
S-1-5-18     Local System       NT AUTHORITY\SYSTEM
S-1-5-19     LocalService       NT AUTHORITY\LOCAL SERVICE
S-1-5-20     NetworkService     NT AUTHORITY\NETWORK SERVICE

For information on additional SIDs, see Well-known security identifiers in Windows operating systems.

  1. If there are two entries (e.g. with a .bak) at the end for the SID in question, or the SID in question ends in .bak, ensure to follow carefully the steps in the KB947215 article.
  2. Reset the values for RefCount and State to be 0.
  3. Reboot.
  4. Retry the SQL Server installation.

Turn a number into star rating display using jQuery and CSS

Try this jquery helper function/file


$.fn.stars = function() {
    return $(this).each(function() {
        var rating = $(this).data("rating");
        var fullStar = new Array(Math.floor(rating + 1)).join('<i class="fas fa-star"></i>');
        var halfStar = ((rating%1) !== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
        var noStar = new Array(Math.floor($(this).data("numStars") + 1 - rating)).join('<i class="far fa-star"></i>');
        $(this).html(fullStar + halfStar + noStar);

$.fn.stars = function() {
    return $(this).each(function() {
        const rating = $(this).data("rating");
        const numStars = $(this).data("numStars");
        const fullStar = '<i class="fas fa-star"></i>'.repeat(Math.floor(rating));
        const halfStar = (rating%1!== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
        const noStar = '<i class="far fa-star"></i>'.repeat(Math.floor(numStars-rating));


   <!DOCTYPE html>
    <html lang="en">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Star Rating</title>
        <link href="" rel="stylesheet">
        <script src=""></script>
        <script src="js/jquery.Rating.js"></script>

        <span class="stars" data-rating="3.5" data-num-stars="5" ></span>



Save internal file in my own internal folder in Android


public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        return true;
    } catch (IOException e) {
        return false;


public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        return line;
    } catch (IOException e) {
        Log.i("TESTE", "FILE - false");
        return null;

Tooltips with Twitter Bootstrap

Simple use of this:

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip">

Using jQuery:


You can left side of tooltip u can simple add this->data-placement="left"

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip" data-placement="left">tooltip</a>

Multiple lines of text in UILabel

Swift 4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 

How to restore SQL Server 2014 backup in SQL Server 2008

It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.

Find duplicate lines in a file and count how many time each line was duplicated?

Assuming there is one number per line:

sort <file> | uniq -c

You can use the more verbose --count flag too with the GNU version, e.g., on Linux:

sort <file> | uniq --count

Create controller for partial view in ASP.NET MVC

Why not use Html.RenderAction()?

Then you could put the following into any controller (even creating a new controller for it):

public ActionResult MyActionThatGeneratesAPartial(string parameter1)
    var model = repository.GetThingByParameter(parameter1);
    var partialViewModel = new PartialViewModel(model);
    return PartialView(partialViewModel); 

Then you could create a new partial view and have your PartialViewModel be what it inherits from.

For Razor, the code block in the view would look like this:

@{ Html.RenderAction("Index", "Home"); }

For the WebFormsViewEngine, it would look like this:

<% Html.RenderAction("Index", "Home"); %>

Shortcut to comment out a block of code with sublime text

Just an important note. If you have HTML comment and your uncomment doesn't work
(Maybe it's a PHP file), so don't mark all the comment but just put your cursor at the end or at the beginning of the comment (before ) and try again (Ctrl+/).

did you register the component correctly? For recursive components, make sure to provide the "name" option

I had this error as well. I triple checked that names were correct.

However I got this error simply because I was not terminating the script tag.

    <p>My Form</p>

import PageA from "./PageA.vue"

export default {
  name: "MyForm",
  components: {

Notice there is no </script> at the end.

So be sure to double check this.

Executing JavaScript after X seconds

I believe you are looking for the setTimeout function.

To make your code a little neater, define a separate function for onclick in a <script> block:

function myClick() {
    function() {
    }, 5000);

then call your function from onclick


How do I bind to list of checkbox values with AngularJS?

You can combine AngularJS and jQuery. For example, you need to define an array, $scope.selected = [];, in the controller.

<label ng-repeat="item in items">
    <input type="checkbox" ng-model="selected[$index]" ng-true-value="'{{item}}'">{{item}}

You can get an array owning the selected items. Using method alert(JSON.stringify($scope.selected)), you can check the selected items.

Visual Studio 2012 Web Publish doesn't copy files

I finally found the answer by myself. All of the above solutions doesnt work for me.

What i had done is that i move the project to drive c change the project folder to something shorter and boom it publish..

the reason that it failed on my side is that i had very long project name/heirarchy.

C:\Users\user\Desktop\Compliance Management System\ComplianceIssueManagementSystem\ComplianceIssueManagementSystem

I had thought of this because sometimes when i extracted rar file it says that the name/path is too long. I thought it will be the same as visual studio 2012 publish. and it does!

hope it will help you guys.

What is HEAD in Git?

HEAD refers to the current commit that your working copy points to, i.e. the commit you currently have checked-out. From the official Linux Kernel documentation on specifying Git revisions:

HEAD names the commit on which you based the changes in the working tree.

Note, however, that in the upcoming version 1.8.4 of Git, @ can also be used as a shorthand for HEAD, as noted by Git contributor Junio C Hamano in his Git Blame blog:

Instead of typing "HEAD", you can say "@" instead, e.g. "git log @".

Stack Overflow user VonC also found some interesting information on why @ was chosen as a shorthand in his answer to another question.

Also of interest, in some environments it's not necessary to capitalize HEAD, specifically in operating systems that use case-insensitive file systems, specifically Windows and OS X.

How can I list ALL DNS records?

In the absence of the ability to do zone transfers, I wrote this small bash script, dg:

COMMON_SUBDOMAINS=(www mail smtp pop imap blog en ftp ssh login)
if [[ "$2" == "x" ]]; then
    dig +nocmd "$1" +noall +answer "${3:-any}"
    wild_ips="$(dig +short "*.$1" "${3:-any}" | tr '\n' '|')"
    for sub in "${COMMON_SUBDOMAINS[@]}"; do
        dig +nocmd "$sub.$1" +noall +answer "${3:-any}"
    done | grep -vE "${wild_ips}"
    dig +nocmd "*.$1" +noall +answer "${3:-any}"
    dig +nocmd "$1" +noall +answer "${2:-any}"

Now I use dg to get a nice, clean list of DNS records, or dg x to include a bunch of other popular subdomains.

grep -vE "${wild_ips}" filters out records that could be the result of a wildcard DNS entry such as * 10800 IN A Otherwise, a wildcard entry would make it appear as if there were records for each $COMMON_SUBDOMAN.

Note: This relies on ANY queries, which are blocked by some DNS providers such as CloudFlare.


You don't say what platform you're targeting. Referring to tables as files, though, leads me to believe that you're NOT running DB2 on Linux, UNIX or Windows (LUW).

However, if you are on DB2 LUW, see the MERGE statement:

For your example statement, this would be written as:

merge into file1 a
   using (select anotherfield, something from file2) b
   on substr(a.firstfield,10,20) = substr(b.anotherfield,1,10)
when matched and a.firstfield like 'BLAH%'
   then update set a.firstfield = 'BIT OF TEXT' || b.something;

Please note: For DB2, the third argument of the SUBSTR function is the number of bytes to return, not the ending position. Therefore, SUBSTR(a.firstfield,10,20) returns CHAR(20). However, SUBSTR(b.anotherfield,1,10) returns CHAR(10). I'm not sure if this was done on purpose, but it may affect your comparison.

how to get multiple checkbox value using jquery

Try this

<input name="selector[]" id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" />
<input name="selector[]" id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" />
<input name="selector[]" id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" />
<input name="selector[]" id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" />
<input type="button" id="save_value" name="save_value" value="Save" />


        var val = [];
          val[i] = $(this).val();

How can I print the contents of an array horizontally?

You are probably using Console.WriteLine for printing the array.

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)

If you don't want to have every item on a separate line use Console.Write:

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)

or string.Join<T> (in .NET Framework 4 or later):

int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));

How do I convert Long to byte[] and back in java

public byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    return buffer.array();

public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.flip();//need flip 
    return buffer.getLong();

Or wrapped in a class to avoid repeatedly creating ByteBuffers:

public class ByteUtils {
    private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);    

    public static byte[] longToBytes(long x) {
        buffer.putLong(0, x);
        return buffer.array();

    public static long bytesToLong(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();//need flip 
        return buffer.getLong();

Since this is getting so popular, I just want to mention that I think you're better off using a library like Guava in the vast majority of cases. And if you have some strange opposition to libraries, you should probably consider this answer first for native java solutions. I think the main thing my answer really has going for it is that you don't have to worry about the endian-ness of the system yourself.

Double value to round up in Java

Note the comma in your string: "1,07". DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is ",", you can't parse your number back.

However, you can use the same DecimalFormat to parse it back:

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

But you really should do this instead:

double finalValue = Math.round( value * 100.0 ) / 100.0;

Note: As has been pointed out, you should only use floating point if you don't need a precise control over accuracy. (Financial calculations being the main example of when not to use them.)

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

To compare each item with the next one in an iterator without instantiating a list:

import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
for a, b in itertools.izip(data1, data2):
  print a, b

CSS Classes & SubClasses

you can also have two classes within an element like this

<div class = "item1 item2 item3"></div>

each item in the class is its own class

.item1 {

.item2 {

.item3 {

ToList()-- does it create a new list?

Yes, it creates a new list. This is by design.

The list will contain the same results as the original enumerable sequence, but materialized into a persistent (in-memory) collection. This allows you to consume the results multiple times without incurring the cost of recomputing the sequence.

The beauty of LINQ sequences is that they are composable. Often, the IEnumerable<T> you get is the result of combining multiple filtering, ordering, and/or projection operations. Extension methods like ToList() and ToArray() allow you to convert the computed sequence into a standard collection.

Open the terminal in visual studio?

Visual Studio 2019 update:

Now vs has built-in terminal


View > Terminal (Ctrl+")

To change default terminal

Tools > Options - Terminal > Set As Default

enter image description here

Before Visual Studio 2019

From comments best answer is from @Hans Passant

  1. Add an external tool.

Tools > External Tools > Add

Title: Terminal (or name it yourself)

Command=cmd.exe Or Command=powershell.exe

Arguments= /k

Initial Directory=$(ProjectDir)

  1. Tools > Terminal (or whatever you put in title)

  2. Enjoy!

How to filter by string in JSONPath?

''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:


DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:

var person =, "//people[category='Politician']");
console.log( person[0].name );
// Barack Obama

Creating a BAT file for python script

You can use python code directly in batch file,

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

See explanation, Python command line -x option.

YAML mapping values are not allowed in this context

The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:

 - - name: A
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120
 - - name: B
   - schedule: "0 0/5 * 1/1 * ? *"
   - - type: mongodb.cluster
     - config:
       - host: mongodb://localhost:27017/admin?replicaSet=rs
       - minSecondaries: 2
       - minOplogHours: 100
       - maxSecondaryDelay: 120

Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.

Interface/enum listing standard mime-type constants

Java 7 to the rescue!

You can either pass the file or the file name and it will return the MIME type.

String mimeType = MimetypesFileTypeMap

Fixing a systemd service 203/EXEC failure (no such file or directory)

When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

If you do not have restrictions on the use of HTML 5, you can use the <button> tag with formaction Attribute:

<form action="demo_form.asp" method="get">
   First name: <input type="text" name="fname" /><br />
   Last name: <input type="text" name="lname" /><br />
   <button type="submit">Submit</button><br />
   <button type="submit" formaction="demo_admin.asp">Submit as admin</button>


What's the simplest way to list conflicted files in Git?

If you attempt to commit, and if there are conflicts, then git will give you the list of the currently unresolved conflicts... but not as a plain list. This is usually what you want when working interactively because the list gets shorter as you fix the conflicts.

Difference between static memory allocation and dynamic memory allocation

Static Memory Allocation:

  • Variables get allocated permanently
  • Allocation is done before program execution
  • It uses the data structure called stack for implementing static allocation
  • Less efficient
  • There is no memory reusability

Dynamic Memory Allocation:

  • Variables get allocated only if the program unit gets active
  • Allocation is done during program execution
  • It uses the data structure called heap for implementing dynamic allocation
  • More efficient
  • There is memory reusability . Memory can be freed when not required

What does the exclamation mark do before the function?

There is a good point for using ! for function invocation marked on airbnb JavaScript guide

Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using ! will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.

!function abc(){}();
!function bca(){}();

Will work the same as

!function abc(){}();
(function bca(){})();

but saves one character and arbitrary looks better.

And by the way any of +,-,~,void operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.

abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?

but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction

!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()

Will do safe code execution, same as a very first code sample.

This one will throw error cause JavaScript ASI will not be able to do its work.

!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()

One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.

This works:

!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()

This not:

^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

How to add a TextView to LinearLayout in Android

for(int j=0;j<30;j++) {
    LinearLayout childLayout = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(

    TextView mType = new TextView(MainActivity.this);
    TextView mValue = new TextView(MainActivity.this);

    mType.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, 1f));
    mValue.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, 1f));

    mType.setPadding(5, 3, 0, 3);
    mType.setGravity(Gravity.LEFT | Gravity.CENTER);

    mValue.setPadding(5, 3, 0, 3);
    mValue.setTypeface(null, Typeface.ITALIC);
    mValue.setGravity(Gravity.LEFT | Gravity.CENTER);


    childLayout.addView(mValue, 0);
    childLayout.addView(mType, 0);


How to download python from command-line?

apt-get install python2.7 will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.

How to terminate a thread when main program ends?

Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.

E.g. for Python 3:

while threading.main_thread().isAlive():

See Check if the Main Thread is still alive from another thread.

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;

/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Backup/Restore a dockerized PostgreSQL database

Backup Database

generate sql:

  • docker exec -t your-db-container pg_dumpall -c -U your-db-user > dump_$(date +%Y-%m-%d_%H_%M_%S).sql

to reduce the size of the sql you can generate a compress:

  • docker exec -t your-db-container pg_dumpall -c -U your-db-user | gzip > ./dump_$(date +"%Y-%m-%d_%H_%M_%S").gz

Restore Database

  • cat your_dump.sql | docker exec -i your-db-container psql -U your-db-user -d your-db-name

to restore a compressed sql:

  • gunzip < your_dump.sql.gz | docker exec -i your-db-container psql -U your-db-user -d your-db-name

PD: this is a compilation of what worked for me, and what I got from here and elsewhere. I am beginning to make contributions, any feedback will be appreciated.

Android Room - simple select query - Cannot access database on the main thread

Database access on main thread locking the UI is the error, like Dale said.

--EDIT 2--

Since many people may come across this answer... The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta).

--EDIT 1--

For people wondering... You have other options. I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room.

Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData.

--Original answer--

Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.

private static class AgentAsyncTask extends AsyncTask<Void, Void, Integer> {

    //Prevent leak
    private WeakReference<Activity> weakActivity;
    private String email;
    private String phone;
    private String license;

    public AgentAsyncTask(Activity activity, String email, String phone, String license) {
        weakActivity = new WeakReference<>(activity); = email; = phone;
        this.license = license;

    protected Integer doInBackground(Void... params) {
        AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
        return agentDao.agentsCount(email, phone, license);

    protected void onPostExecute(Integer agentsCount) {
        Activity activity = weakActivity.get();
        if(activity == null) {

        if (agentsCount > 0) {
            //2: If it already exists then prompt user
            Toast.makeText(activity, "Agent already exists!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(activity, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show();

Or you can create a final class on its own file.

Then execute it in the signUpAction(View view) method:

new AgentAsyncTask(this, email, phone, license).execute();

In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.

Also, your question about the Google's test example... They state in that web page:

The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.

No Activity, no UI.

Get full path of the files in PowerShell

Add | select FullName to the end of your line above. If you need to actually do something with that afterwards, you might have to pipe it into a foreach loop, like so:

get-childitem "C:\windows\System32" -recurse | where {$_.extension -eq ".txt"} | % {
     Write-Host $_.FullName

"The file "" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I got this issue in Xcode 10.1 after adding objective c files to my swift project. Got this working by following the below steps,

  • Add .m file to compile sources under Target -> Build Phases
  • Add -objc to the compiler flags right next to the .m file

Package php5 have no installation candidate (Ubuntu 16.04)

Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.

Mine PHP version is 7.0, so i tried the below command.

apt-get install php-pgsql

Remember to restart Apache.

/etc/init.d/apache2 restart

swift How to remove optional String Character

You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:

if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
    println(color) // "Red"

    let imageURLString = "\(color)"
    println(imageURLString) //

SQLRecoverableException: I/O Exception: Connection reset

I had a similar situation when reading from Oracle in a Spark job. This connection reset error was caused by an incompatibility between the Oracle server and the JDBC driver used. Worth checking it.

What is a good way to handle exceptions when trying to read a file in python?

Adding to @Josh's example;

fName = [FILE TO OPEN]
if os.path.exists(fName):
    with open(fName, 'rb') as f:
        #add you code to handle the file contents here.
elif IOError:
    print "Unable to open file: "+str(fName)

This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

SQL query for today's date minus two months

    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Create a hidden field in JavaScript

You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.

You can also add multiple hidden fields. Use this way:

        "hidden" : 
            'fieldinFORM' : 'thisdata201' , 
            'fieldinFORM2' : 'this3' //multiple hidden fields
            'nNoOfFields' : 'nthData'
    "form" : 
        "status" : "true",
        "formID" : "form3"
} );

var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
    var request = [];_x000D_
 var container = '';_x000D_
 request = arguments[0].hidden;_x000D_
 if(arguments[0].hasOwnProperty('form') == true)_x000D_
  if(arguments[0].form.status == 'true'){_x000D_
   var parent = document.getElementById("container");_x000D_
   container = document.createElement('form');_x000D_
   Object.assign(container, {'id':arguments[0].form.formID});_x000D_
   container = document.getElementById("container");_x000D_
 //var container = document.getElementById("container");_x000D_
  if($('#'+elem).length <= 0){_x000D_
   console.log("Hidden Field created");_x000D_
   var input = document.createElement('input');_x000D_
   Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
   console.log("Hidden Field Exists and value is below" );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
<script src=""></script>_x000D_
<div id='container'>_x000D_

Is it possible to have multiple statements in a python lambda expression?

There actually is a way you can use multiple statements in lambda. Here's my solution:

lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]

x = lambda l: exec("l.sort(); return l[1]")

map(x, lst)

List of tuples to dictionary

Just call dict() on the list of tuples directly

>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}

How to enable CORS in Core WebAPI

below is the settings which works for me: enter image description here

Best way to check for IE less than 9 in JavaScript without library

var ie = !-[1,]; // true if IE less than 9

This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.

How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.

This is the shortest hack by now. And I am the author ;)

Wordpress plugin install: Could not create directory

wordpressProject is the project name.

/var/www/html/wordpressProject sudo chmod -R 777 wp-content

Thanks. It will work.

How to insert spaces/tabs in text using HTML/CSS

user8657661's answer is closest to my needs (of lining things up across several lines). However, I couldn't get the example code to work as provided, but I needed to change it as follows:

            .tab9 {position:absolute;left:150px; }

        Dog Food: <span class="tab9"> $30</span><br/>
        Milk of Magnesia:<span class="tab9"> $30</span><br/>
        Pizza Kit:<span class="tab9"> $5</span><br/>
        Mt Dew <span class="tab9"> $1.75</span><br/>

If you need right-aligned numbers you can change left:150px to right:150px, but you'll need to alter the number based on the width of the screen (as written the numbers would be 150 pixels from the right edge of the screen).

jquery input select all on focus

Found a awesome solution reading this thread




jQuery.extend( {
    selectText: function(s) { 
        $(s).live('focus',function() {
            var self = $(this);
            setTimeout(function() {;}, 0);

Set min-width in HTML table's <td>

min-width and max-width properties do not work the way you expect for table cells. From spec:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.

This hasn't changed in CSS3.

The target principal name is incorrect. Cannot generate SSPI context

I had this problem and it grabbed my around 4-5 hours to find the root cause of this error message. Only difference is, i was getting this error while connecting DB from Visual Studio only, not direct via SQL Server Management Studio.

Reason behind error is, my application was hosted on local IIS and I had changed my system password one day ago, but didn't update it to IIS Application Pool of my hosted application.

I went to IIS, clicked on application pools, in pool list right click on appropriate app pool, go to "Advanced Settings", select "Identity" and changed its value (Domain\AccountName & New Password) under "Custom Account" and it solved my problem.


Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))

if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "", "nw_dst": "", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

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

Into psql terminal put:

\i <path to contrib files>

in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Reading a simple text file

In Mono For Android....

    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
            Content = StrRead.ReadToEnd();
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
          StrIn = null;
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }

Get Character value from KeyCode in JavaScript... then trim

In my experience String.fromCharCode(e.keyCode) is unreliable. String.fromCharCode expects unicode charcodes as an argument; e.keyCode returns javascript keycodes. Javascript keycodes and unicode charcodes are not the same thing! In particular, the numberpad keys return a different keycode from the ordinary number keys (since they are different keys) while the same keycode is returned for both upper and lowercase letters (you pressed the same key in both cases), despite them having different charcodes.

For example, the ordinary number key 1 generates an event with keycode 49 while numberpad key 1 (with Numlock on) generates keycode 97. Used with String.fromCharCode we get the following:

String.fromCharCode(49) returns "1"
String.fromCharCode(97) returns "a"

String.fromCharCode expects unicode charcodes, not javascript keycodes. The key a generates an event with a keycode of 65, independentant of the case of the character it would generate (there is also a modifier for if the Shift key is pressed, etc. in the event). The character a has a unicode charcode of 61 while the character A has a charcode of 41 (according to, for example, However, those are hex values, converting to decimal gives us a charcode of 65 for "A" and 97 for "a".[1] This is consistent with what we get from String.fromCharCode for these values.

My own requirement was limited to processing numbers and ordinary letters (accepting or rejecting depending on the position in the string) and letting control characters (F-keys, Ctrl-something) through. Thus I can check for the control characters, if it's not a control character I check against a range and only then do I need to get the actual character. Given I'm not worried about case (I change all letters to uppercase anyway) and have already limited the range of keycodes, I only have to worry about the numberpad keys. The following suffices for that:

String.fromCharCode((96 <= key && key <= 105)? key-48 : key)

More generally, a function to reliably return the character from a charcode would be great (maybe as a jQuery plugin), but I don't have time to write it just now. Sorry.

I'd also mention e.which (if you're using jQuery) which normalizes e.keyCode and e.charCode, so that you don't need to worry about what sort of key was pressed. The problem with combining it with String.fromCharCode remains.

[1] I was confused for a while -. all the docs say that String.fromCharCode expects a unicode charcode, while in practice it seemed to work for ASCII charcodes, but that was I think due to the need to convert to decimal from hex, combined with the fact that ASCII charcodes and unicode decimal charcodes overlap for ordinary latin letters.

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;

Your display property is being overridden by bootstrap to display: block.


HTML Button Close Window

Use the code below. It works every time.

<button onclick="self.close()">Close</button>

It works every time in Chrome and also works on Firefox.

Select all occurrences of selected word in VSCode

I needed to extract all the matched search lines (using regex) in a file

  1. Ctrl+F Open find. Select regex icon and enter search pattern
  2. (optional) Enable select highlights by opening settings and search for selectHighlights (Ctrl+,, selectHighlights)
  3. Ctrl+L Select all search items
  4. Ctrl+C Copy all selected lines
  5. Ctrl+N Open new document
  6. Ctrl+V Paste all searched lines.

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

Comparing chars in Java

Option 2 will work. You could also use a Set<Character> or

char[] myCharSet = new char[] {'A', 'B', 'C', ...};
if (Arrays.binarySearch(myCharSet, symbol) >= 0) { ... }

Difference between "as $key => $value" and "as $value" in PHP foreach

Say you have an array like this:

$array = (0=>'123',1=>'abc','test'=>'hi there!')

In your foreach loop, each loop would be:

$key = 0, $value = '123'
$key = 1, $value = 'abc'
$key = 'test', $value = 'hi there!'

It's great for those times when you need to know the array key.

Find all storage devices attached to a Linux machine

Using HAL (kernel 2.6.17 and up):

#! /bin/bash
hal-find-by-property --key volume.fsusage --string filesystem |
while read udi ; do
    # ignore optical discs
    if [[ "$(hal-get-property --udi $udi --key volume.is_disc)" == "false" ]]; then
        dev=$(hal-get-property --udi $udi --key block.device)   
        fs=$(hal-get-property --udi $udi --key volume.fstype) 
        echo $dev": "$fs

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)

enter image description here

Bash function to find newest file matching pattern

Dark magic function incantation for those who want the find ... xargs ... head ... solution above, but in easy to use function form so you don't have to think:

#define the function
    echo $(find $1 -name $2 -print0 | xargs -0 ls -1 -t | head -1)

#mkdir /tmp/files_to_move
#cd /tmp/files_to_move
#touch file1.txt
#touch file2.txt

#invoke the function:
newest_file=$( find_newest_file_matching_pattern_under_directory /tmp/files_to_move/ bc* )
echo $newest_file



Which is:

The filename with the oldest modified timestamp of the file under the given directory matching the given pattern.

Implementing autocomplete

I know you already have several answers, but I was on a similar situation where my team didn't want to depend on a heavy libraries or anything related to bootstrap since we are using material so I made our own autocomplete control, using material-like styles, you can use my autocomplete or at least you can give a look to give you some guiadance, there was not much documentation on simple examples on how to upload your components to be shared on NPM.

Regex for numbers only

Regex for integer and floating point numbers:


A number can start with a period (without leading digits(s)), and a number can end with a period (without trailing digits(s)). Above regex will recognize both as correct numbers.

A . (period) itself without any digits is not a correct number. That's why we need two regex parts there (separated with a "|").

Hope this helps.

Git's famous "ERROR: Permission to .git denied to user"

This problem is also caused by:

If you are on a mac/linux, and are using 'ControlMaster' in your ~/.ssh/config, there may be some ssh control master processes running.

To find them, run:

ps aux | grep '\[mux\]'

And kill the relevant ones.

Button text toggle in jquery

You could also use .toggle() like so:

$(".pushme").toggle(function() {
    $(this).text("DON'T PUSH ME");
}, function() {
    $(this).text("PUSH ME");

More info at

This way also makes it pretty easy to change the text or add more than just 2 differing states.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I had the same problem and I solved it. My problem was that I was using a listview, with an array adapter and with filter. On the method performFiltering I was messing with the array that have the data and it was the problem since this method is not running on the UI thread and EVENTUALLY it raises some problems.

Resize Google Maps marker icon image

As mentionned in comments, this is the updated solution in favor of Icon object with documentation.

Use Icon object

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor

 posicion = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: posicion,
  map: map,
  icon: icon

Commenting out code blocks in Atom

Atom does not have a specific comment-block function, but if you select more rows and then use the normal ctrl-/ (Windows or Linux) cmd-/ (Mac), it will comment all the lines.

How to change the value of ${user} variable used in Eclipse templates

dovescrywolf gave tip as a comment on article linked by Davide Inglima

It was was very useful for me on MacOS.

  • Close Eclipse if it's opened.
  • Open Termnal (bash console) and do below things:

    $ pwd /Users/You/YourEclipseInstalationDirectory  
    $ cd  
    $ echo " Name" >> eclipse.ini  
    $ cat eclipse.ini
  • Close Terminal and start/open Eclipse again.

How can I pass a parameter in Action?

Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.

this.Include(includes, () =>

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Count number of occurrences of a pattern in a file (even on same line)

A belated post:
Use the search regex pattern as a Record Separator (RS) in awk
This allows your regex to span \n-delimited lines (if you need it).

printf 'X \n moo X\n XX\n' | 
   awk -vRS='X[^X]*X' 'END{print (NR<2?0:NR-1)}'

Is there a jQuery unfocus method?

This works for me:

// Document click blurer
$(document).on('mousedown', '*:not(input,textarea)', function() {
    try {
        var $a = $(document.activeElement).prop("disabled", true);
        setTimeout(function() {
            $a.prop("disabled", false);
    } catch (ex) {}

Creating a new empty branch for a new project

Let's say you have a master branch with files/directories:

> git branch  
> ls -la # (files and dirs which you may keep in master)

Step by step how to make an empty branch:

  1. git checkout —orphan new_branch_name
  2. Make sure you are in the right directory before executing the following command:
    ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
  3. git rm -rf .
  4. touch new_file
  5. git add new_file
  6. git commit -m 'added first file in the new branch'
  7. git push origin new_branch_name

In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master branch. Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.

Once you're done, you can easily switch between your branches:

git checkout master 
git checkout new_branch

ASP.NET MVC ActionLink and post method

Use the following the Call the Action Link:

<%= Html.ActionLink("Click Here" , "ActionName","ContorllerName" )%>

For submitting the form values use:

 <% using (Html.BeginForm("CustomerSearchResults", "Customer"))
   { %>
      <input type="text" id="Name" />
      <input type="submit" class="dASButton" value="Submit" />
   <% } %>

It will submit the Data to Customer Controller and CustomerSearchResults Action.

How to activate JMX on my JVM for access with jconsole?

Step 1: Run the application using following parameters.

Above arguments bind the application to the port 9999.

Step 2: Launch jconsole by executing the command jconsole in command prompt or terminal.

Select ‘Remote Process:’ and enter the url as {IP_Address}:9999 and click on Connect button to connect to the remote application.

You can refer this link for complete application.

Python Prime number checker

def isprime(n):
    '''check if integer n is a prime'''

    # make sure n is a positive integer
    n = abs(int(n))

    # 0 and 1 are not primes
    if n < 2:
        return False

    # 2 is the only even prime number
    if n == 2: 
        return True    

    # all other even numbers are not primes
    if not n & 1: 
        return False

    # range starts with 3 and only needs to go up 
    # the square root of n for all odd numbers
    for x in range(3, int(n**0.5) + 1, 2):
        if n % x == 0:
            return False

    return True

Taken from:

UITapGestureRecognizer - single tap and double tap

Some view have there own double tap recognizers built in (MKMapView being an example). To get around this you will need to implement UIGestureRecognizerDelegate method shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES:

First implement your double and single recognizers:

// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;

UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
doubleTapRecognizer.delegate = self;    // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

And then implement:

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer {  return YES; }

$(document).ready equivalent without jQuery

Three options:

  1. If script is the last tag of the body, the DOM would be ready before script tag executes
  2. When the DOM is ready, "readyState" will change to "complete"
  3. Put everything under 'DOMContentLoaded' event listener


  document.onreadystatechange = function () {
     if (document.readyState == "complete") {
     // document is ready. Do your stuff here

Source: MDN


document.addEventListener('DOMContentLoaded', function() {
   console.log('document is ready. I can sleep now');

Concerned about stone age browsers: Go to the jQuery source code and use the ready function. In that case you are not parsing+executing the whole library you're are doing only a very small part of it.

Maximize a window programmatically and prevent the user from changing the windows state

When I do this, I get a very small square screen instead of a maxed screen. Yet, when I only use the FormWindowState.Maximized, it does give me a full screen. Why is that?

        public partial class Testscherm : Form
            public Testscherm()


                    this.WindowState = FormWindowState.Maximized;
                    this.MaximizeBox = false;
                    this.MinimizeBox = false;
                    this.MinimumSize = this.Size;
                    this.MaximumSize = this.Size;
                    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;


c++ bool question

false == 0 and true = !false

i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

Some examples to clarify:

if(0)          // false
if(1)          // true
if(2)          // true
if(0 == false) // true
if(0 == true)  // false
if(1 == false) // false
if(1 == true)  // true
if(2 == false) // false
if(2 == true)  // false
cout << false  // 0
cout << true   // 1

true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.


// It will be called downloaded.pdf

// The PDF source is in original.pdf

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

Animate text change in UILabel

Swift 4.2 version of SwiftArchitect's solution above (works great):

    // Usage: insert view.fadeTransition right before changing content    

extension UIView {

        func fadeTransition(_ duration:CFTimeInterval) {
            let animation = CATransition()
            animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            animation.type = CATransitionType.fade
            animation.duration = duration
            layer.add(animation, forKey: CATransitionType.fade.rawValue)


    // This will fade

aLabel.text = "text"

What's the difference between REST & RESTful

REST(REpresentation State Transfer) is an architecture using which WebServices are created.


RESTful is way of writing services using the REST architectures. RESTful services exposes the resources to identify the targets to interact with clients.

vertical-align: middle with Bootstrap 2

i use this

html, body{height:100%;margin:0;padding:0 0} 
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}   
.centering{float:none;margin:0 auto} 
<div class="container-fluid">
     <div class="row-fluid">
     <div class="offset3 span6 centering">
            content here

Differences between time complexity and space complexity?

Yes, this is definitely possible. For example, sorting n real numbers requires O(n) space, but O(n log n) time. It is true that space complexity is always a lowerbound on time complexity, as the time to initialize the space is included in the running time.

File input 'accept' attribute - is it useful?

It is supported by Chrome. It's not supposed to be used for validation, but for type hinting the OS. If you have an accept="image/jpeg" attribute in a file upload the OS can only show files of the suggested type.

How to get the difference between two arrays of objects in JavaScript

You could use Array.prototype.filter() in combination with Array.prototype.some().

Here is an example (assuming your arrays are stored in the variables result1 and result2):

//Find values that are in result1 but not in result2
var uniqueResultOne = result1.filter(function(obj) {
    return !result2.some(function(obj2) {
        return obj.value == obj2.value;

//Find values that are in result2 but not in result1
var uniqueResultTwo = result2.filter(function(obj) {
    return !result1.some(function(obj2) {
        return obj.value == obj2.value;

//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);

How to find path of active app.config file?

I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;

The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.

git pull keeping local changes

If you have a file in your repo that it is supposed to be customized by most pullers, then rename the file to something like config.php.template and add config.php to your .gitignore.

foreach with index

You can do the following

foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
   if (it.Index > SomeNumber) //      

This will create an anonymous type value for every entry in the collection. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

how to get files from <input type='file' .../> (Indirect) with javascript

If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  

See this MDN article for more info on the FileList type.

Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files property in non-File API browsers.

When should we use intern method of String on String literals

On a recent project, some huge data structures were set up with data that was read in from a database (and hence not String constants/literals) but with a huge amount of duplication. It was a banking application, and things like the names of a modest set (maybe 100 or 200) corporations appeared all over the place. The data structures were already large, and if all those corp names had been unique objects they would have overflowed memory. Instead, all the data structures had references to the same 100 or 200 String objects, thus saving lots of space.

Another small advantage of interned Strings is that == can be used (successfully!) to compare Strings if all involved strings are guaranteed to be interned. Apart from the leaner syntax, this is also a performance enhancement. But as others have pointed out, doing this harbors a great risk of introducing programming errors, so this should be done only as a desparate measure of last resort.

The downside is that interning a String takes more time than simply throwing it on the heap, and that the space for interned Strings may be limited, depending on the Java implementation. It's best done when you're dealing with a known reasonable number of Strings with many duplications.

Copy the entire contents of a directory in C#

One variant with only one loop for copying of all folders and files:

foreach (var f in Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories))
    var output = Regex.Replace(f, @"^" + path, newPath);
    if (File.Exists(f)) File.Copy(f, output, true);
    else Directory.CreateDirectory(output);

How to read line by line of a text area HTML tag

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(;
String data = input.nextLine();

Please read the tutorial on how to use it as it will explain all.

Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

Replace transparency in PNG images with white background

The Alpha Remove section of the ImageMagick Usage Guide suggests using the -alpha remove option, e.g.:

convert in.png  -background white  -alpha remove  out.png

...using the -background color of your choosing.

The guide states:

This operation is simple and fast, and does the job without needing any extra memory use, or other side effects that may be associated with alternative transparency removal techniques. It is thus the prefered way of removing image transparency.

It additionally adds the note:

Note that while transparency is 'removed' the alpha channel will remain turned on, but will now be fully-opaque. If you no longer need the alpha channel you can then use Alpha Off to disable it.

Thus, if you do not need the alpha channel you can make your output image size smaller by adding the -alpha off option, e.g:

convert in.png  -background white  -alpha remove  -alpha off  out.png

There are more details on other, often-used techniques for removing transparency described in the Removing Transparency from Images section.

Included in that section is mention of an important caveat to the usage of -flatten as a technique for removing transparency:

However this will not work with "mogrify" or with a sequence of multiple images, basically because the "-flatten" operator is really designed to merge multiple images into a single image.

So, if you are converting several images at once, e.g. generating thumbnails from a PDF file, -flatten will not do what you want (it will flatten all images for all pages into one image). On the other hand, using the -alpha remove technique will still produce multiple images, each one having transparency removed.

Creating Unicode character from its number

Here is a block to print out unicode chars between \u00c0 to \u00ff:

char[] ca = {'\u00c0'};
for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 16; j++) {
        String sc = new String(ca);
        System.out.print(sc + " ");

How to implement reCaptcha for ASP.NET MVC?

I have added reCaptcha to a project I'm currently working on. I needed it to use the AJAX API as the reCaptcha element was loaded into the page dynamically. I couldn't find any existing controls and the API is simple so I created my own.

I'll post my code here in case anyone finds it useful.

1: Add the script tag to the master page headers

<script type="text/javascript" src=""></script>

2: Add your keys to the web.config

    <add key="ReCaptcha.PrivateKey" value="[key here]" />
    <add key="ReCaptcha.PublicKey" value="[key here]" />

3: Create the Action Attribute and Html Helper extensions

namespace [Your chosen namespace].ReCaptcha
    public enum Theme { Red, White, BlackGlass, Clean }

    public class InvalidKeyException : ApplicationException
        public InvalidKeyException() { }
        public InvalidKeyException(string message) : base(message) { }
        public InvalidKeyException(string message, Exception inner) : base(message, inner) { }

    public class ReCaptchaAttribute : ActionFilterAttribute
        public override void OnActionExecuting(ActionExecutingContext filterContext)
            var userIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;

            var privateKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PrivateKey", "");

            if (string.IsNullOrWhiteSpace(privateKey))
                throw new InvalidKeyException("ReCaptcha.PrivateKey missing from appSettings");

            var postData = string.Format("&privatekey={0}&remoteip={1}&challenge={2}&response={3}",

            var postDataAsBytes = Encoding.UTF8.GetBytes(postData);

            // Create web request
            var request = WebRequest.Create("");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataAsBytes.Length;
            var dataStream = request.GetRequestStream();
            dataStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);

            // Get the response.
            var response = request.GetResponse();

            using (dataStream = response.GetResponseStream())
                using (var reader = new StreamReader(dataStream))
                    var responseFromServer = reader.ReadToEnd();

                    if (!responseFromServer.StartsWith("true"))
                        ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha words typed incorrectly");

    public static class HtmlHelperExtensions
        public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, Theme theme, string callBack = null)
            const string htmlInjectString = @"<div id=""recaptcha_div""></div>
<script type=""text/javascript"">
    Recaptcha.create(""{0}"", ""recaptcha_div"", {{ theme: ""{1}"" {2}}});

            var publicKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PublicKey", "");

            if (string.IsNullOrWhiteSpace(publicKey))
                throw new InvalidKeyException("ReCaptcha.PublicKey missing from appSettings");

            if (!string.IsNullOrWhiteSpace(callBack))
                callBack = string.Concat(", callback: ", callBack);

            var html = string.Format(htmlInjectString, publicKey, theme.ToString().ToLower(), callBack);
            return MvcHtmlString.Create(html);

4: Add the captcha to your view

@using (Html.BeginForm("MyAction", "MyController"))
   @Html.TextBox("EmailAddress", Model.EmailAddress)
   <input type="submit" value="Submit" />

5: Add the attribute to your action

public ActionResult MyAction(MyModel model)
   if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
      return Json(new { capthcaInvalid = true });

   ... other stuff ...

6: Note you will need to reload the captcha after each post even if it was valid and another part of the form was invalid. Use Recaptcha.reload();

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

You can go here to download the Java JRE.

You can go here to download the Java JDK.

After that you need to set up your environmental variables in Windows:

  1. Right-click My Computer
  2. Click Properties
  3. Go to Advanced System Settings
  4. Click on the Advanced tab
  5. Click on Environment Variables

EDIT: See screenshot for environmental variables

enter image description here

Express-js can't GET my static files, why?

Try http://localhost:3001/default.css.

To have /styles in your request URL, use:

app.use("/styles", express.static(__dirname + '/styles'));

Look at the examples on this page:

//Serve static content for the app from the "public" directory in the application directory.

    // GET /style.css etc
    app.use(express.static(__dirname + '/public'));

// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static".

    // GET /static/style.css etc.
    app.use('/static', express.static(__dirname + '/public'));

Dark Theme for Visual Studio 2010 With Productivity Power Tools

You can also try this handy online tool, which generates .vssettings file for you.

Visual Studio Color Theme Generator

Headers and client library minor version mismatch

I am using MariaDB and have the similar problem.

From MariaDB site, it is recommended to fix it by

  1. Switch to using the mysqlnd driver in PHP (Recommended solution).
  2. Run with a lower error reporting level:

    $err_level = error_reporting(0);  
    $conn = mysql_connect('params');  
  3. Recompile PHP with the MariaDB client libraries.
  4. Use your original MySQL client library with the MariaDB.

My problem fixed by using the mysqlnd driver in Ubuntu:

sudo apt-get install php5-mysqlnd


[update: extra information] Installing this driver also resolve PDO problem that returns integer value as a string. To keep the type as integer, after installing mysqlInd, do this

$db = new PDO('mysql:host='.$host.';dbname='.$db_name, $user, $pass, 
          array( PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);

Postgres password authentication fails

As shown in the latest edit, the password is valid until 1970, which means it's currently invalid. This explains the error message which is the same as if the password was incorrect.

Reset the validity with:

ALTER USER postgres VALID UNTIL 'infinity';

In a recent question, another user had the same problem with user accounts and PG-9.2:

PostgreSQL - Password authentication fail after adding group roles

So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime type). Possibly, there's a bug in PG itself or in some client tool that would create this situation.

EDIT: it turns out to be a pgadmin bug. See

How to open a new HTML page using jQuery?

If you want to use jQuery, the .load() function is the correct function you are after;

But you are missing the # from the div1 id selector in the example 2)

This should work:


PHP Curl UTF-8 Charset

You Can use this header

   header('Content-type: text/html; charset=UTF-8');

and after decoding the string

 $page = utf8_decode(curl_exec($ch));

It worked for me