Programs & Examples On #Shlex

running multiple bash commands with subprocess

import subprocess
cmd = "vsish -e ls /vmkModules/lsom/disks/  | cut -d '/' -f 1  | while read diskID  ; do echo $diskID; vsish -e cat /vmkModules/lsom/disks/$diskID/virstoStats | grep -iE 'Delete pending |trims currently queued' ;  echo '====================' ;done ;"

def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    for line in proc_stdout.decode().split('\n'):
        print (line)


Escape a string in SQL Server so that it is safe to use in LIKE expression

Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become

WHERE ... LIKE '%aa[%]bb%'

If you need proof:

create table test (field nvarchar(100))
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
select * from test where field like 'abcdef[%]hijklm'

Array definition in XML?

In XML values in text() nodes.

If we write this


in element "numbers" will be one text() node with value "1,2,3".

Native way to get many text() nodes in element is insert nodes of other types in text.

Other available types is element or comment() node.

Split with element node:


Split with comment() node:


We can select this values by this XPath


Select value by index


Will return text() node with value "1"

any tool for java object to object mapping?

I'm happy to add Moo as an option, although clearly I'm biased towards it:

It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.

Using std::max_element on a vector<double>

min_element and max_element return iterators, not values. So you need *min_element... and *max_element....

How to view UTF-8 Characters in VIM or Gvim

this work for me and do not need change any config file

vim --cmd "set encoding=utf8" --cmd "set fileencoding=utf8" fileToOpen

var self = this?

I think it actually depends on what are you going to do inside your doSomething function. If you are going to access MyObject properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){

$("#foobar").ready('click', function(){


POST an array from an HTML form without javascript

check this one out.

<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">

<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">

<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">

<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">

it should end up like this in the $_POST[] array (PHP format for easy visualization)

$_POST[] = array(
    'tree' => array(

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:

PHP call Class method / function

This way:

 $instance = new Functions(); // create an instance (object) of functions class
 $instance->filter($data); // now call it

How do I get the object if it exists, or None if it does not exist?

It's one of those annoying functions that you might not want to re-implement:

from annoying.functions import get_object_or_None
user = get_object_or_None(Content, name="baby")

Printing Python version in output


python --version 


python -V

This will return a current python version in terminal.

Setting the default Java character encoding

I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer String.getBytes("charsetName"). That way your application is not dependent on things beyond its control.

I personally feel that String.getBytes() should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.

Byte[] to InputStream or OutputStream

output = new ByteArrayOutputStream();
input = new ByteArrayInputStream( output.toByteArray() )

Go to first line in a file in vim?

Type "gg" in command mode. This brings the cursor to the first line.

trigger body click with jQuery

I've used the following code a few times and it works sweet:

    // Check what has been clicked:
    var target = $(; 
    // The target was clicked
    // Do something...

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

If you have control over your server, you can use PHP:

header('Access-Control-Allow-Origin: *');

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

Wasted 4+ hours on this.

I have Visual Studio 2017 Enterprise, one of the projects has below error:

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

To resolve above error, I tried to install all below:

However, none of the above worked.

Later, installed Visual Studio 2013 Ultimate, then all worked fine.

Looks like, the older Visual studio is a must to resolve this.

Hope it helps.

Given a filesystem path, is there a shorter way to extract the filename without its extension?

You can use Path API as follow:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

More info: Path.GetFileNameWithoutExtension

Android SharedPreferences in Fragment

Maybe this is helpfull to someone after few years. New way, on Androidx, of getting SharedPreferences() inside fragment is to implement into gradle dependencies

implementation "androidx.preference:preference:1.1.1"

and then, inside fragment call

SharedPreferences preferences;
preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());

using sql count in a case statement

    COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",
    COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted"
from tb_a

You can see the output for this request HERE

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

How to escape single quotes in MySQL

If you use prepared statements, the driver will handle any escaping. For example (Java):

Connection conn = DriverManager.getConnection(driverUrl);
PreparedStatement prepped = conn.prepareStatement("INSERT INTO tbl(fileinfo) VALUES(?)");
String line = null;
while ((line = br.readLine()) != null) {
    prepped.setString(1, line);

Getting only 1 decimal place

Are you trying to represent it with only one digit:

print("{:.1f}".format(number)) # Python3
print "%.1f" % number          # Python2

or actually round off the other decimal places?


or even round strictly down?


Bootstrap button - remove outline on Chrome OS X

That CSS goes from this file "tab-focus.less" in mixins folder (it could be difficult to find, because mixins are not shown at chrome dev-tools). So you should edit this:

// WebKit-style focus 

.tab-focus() {
      // Default
      outline: thin dotted;
      // WebKit
      outline: 5px auto -webkit-focus-ring-color;
      outline-offset: -2px;

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
           mse (integer)
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    return mse

Hope this helps :). for further explaination visit

Make an existing Git branch track a remote branch?

Make sure you run :

git config push.default tracking

to be able to push trouble free

Why are hexadecimal numbers prefixed with 0x?

Short story: The 0 tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x is an arbitrary choice.

Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).

The BCPL language used the syntax 8 1234 for octal numbers. When Ken Thompson created B from BCPL, he used the 0 prefix instead. This is great because

  1. an integer constant now always consists of a single token,
  2. the parser can still tell right away it's got a constant,
  3. the parser can immediately tell the base (0 is the same in both bases),
  4. it's mathematically sane (00005 == 05), and
  5. no precious special characters are needed (as in #123).

When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x was arbitrarily chosen (00 was probably ruled out as awkward).

C# is a descendant of C, so it inherits the syntax.

Set Icon Image in Java

Use Default toolkit for this


How do I use properly CASE..WHEN in MySQL

CASE course_enrollment_settings.base_price is wrong here, it should be just CASE

WHEN course_enrollment_settings.base_price = 0      THEN 1 
WHEN course_enrollment_settings.base_price<101      THEN 2 
WHEN course_enrollment_settings.base_price>100 AND    
                  course_enrollment_settings.base_price<201 THEN 3 
    ELSE 6 
END AS 'calc_base_price', 
WHERE course_enrollment_settings.base_price = 0 

Some explanations. Your original query will be executed as :

WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
ELSE 6, ...

it's why you always get 3

How to increase memory limit for PHP over 2GB?

For others who are experiencing with the same problem, here is the description of the bug in php + patch

Is Python faster and lighter than C++?

All the slowest (>100x) usages of Python on the shootout are scientific operations that require high GFlop/s count. You should NOT use python for those anyways. The correct way to use python is to import a module that does those calculations, and then go have a relaxing afternoon with your family. That is the pythonic way :)

Specifying maxlength for multiline textbox

This snippet worked in my case. I was searching for the solution and thought to write this so that it may help any future reader.


<asp:TextBox ID="tbName" runat="server" MaxLength="250" TextMode="MultiLine" onkeyUp="return CheckMaxCount(this,event,250);"></asp:TextBox>

Java Script

function CheckMaxCount(txtBox,e, maxLength)
        if(txtBox.value.length > maxLength)
            txtBox.value = txtBox.value.substring(0, maxLength);
            return ( txtBox.value.length <= maxLength)

function checkSpecialKeys(e)
    if(e.keyCode !=8 && e.keyCode!=46 && e.keyCode!=37 && e.keyCode!=38 && e.keyCode!=39 && e.keyCode!=40)
        return false;
        return true;

@Raúl Roa Answer did worked for me in case of copy/paste. while this does.

nodejs module.js:340 error: cannot find module

I also got this issue and this was due to wrong path that we mention while running. Check your file path and also make sure that there is no space between the name of your directory name.

How to list physical disks?

I just ran across this in my RSS Reader today. I've got a cleaner solution for you. This example is in Delphi, but can very easily be converted to C/C++ (It's all Win32).

Query all value names from the following registry location: HKLM\SYSTEM\MountedDevices

One by one, pass them into the following function and you will be returned the device name. Pretty clean and simple! I found this code on a blog here.

function VolumeNameToDeviceName(const VolName: String): String;
  s: String;
  TargetPath: Array[0..MAX_PATH] of WideChar;
  bSucceeded: Boolean;
  Result := ”;
  // VolumeName has a format like this: \\?\Volume{c4ee0265-bada-11dd-9cd5-806e6f6e6963}\
  // We need to strip this to Volume{c4ee0265-bada-11dd-9cd5-806e6f6e6963}
  s :=  Copy(VolName, 5, Length(VolName) - 5);

  bSucceeded := QueryDosDeviceW(PWideChar(WideString(s)), TargetPath, MAX_PATH) <> 0;
  if bSucceeded then
    Result := TargetPath;
  else begin
    // raise exception


C# if/then directives for debug vs release

Slightly modified (bastardized?) version of the answer by Tod Thomson as a static function rather than a separate class (I wanted to be able to call it in a WebForm viewbinding from a viewutils class I already had included).

public static bool isDebugging() {
    bool debugging = false;

    WellAreWe(ref debugging);

    return debugging;

private static void WellAreWe(ref bool debugging)
    debugging = true;

Jenkins pipeline if else not working

It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

stage ('Test 3: Master') {
    when { branch 'master' }
    steps { 
        echo 'I only execute on the master branch.' 

stage ('Test 3: Dev') {
    when { not { branch 'master' } }
    steps {
        echo 'I execute on non-master branches.'

How to parseInt in Angular.js

This are to way to bind add too numbers

<!DOCTYPE html>_x000D_
<script src=""></script>_x000D_
var app = angular.module("myApp", []);_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$ = function() { _x000D_
  return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total: {{total() }}_x000D_

How to find longest string in the table column data

You can:

FROM table1 
WHERE len(CR) = (SELECT max(len(CR)) FROM table1)

Having just recieved an upvote more than a year after posting this, I'd like to add some information.

  • This query gives all values with the maximum length. With a TOP 1 query you get only one of these, which is usually not desired.
  • This query must probably read the table twice: a full table scan to get the maximum length and another full table scan to get all values of that length. These operations, however, are very simple operations and hence rather fast. With a TOP 1 query a DBMS reads all records from the table and then sorts them. So the table is read only once, but a sort operation on a whole table is quite some task and can be very slow on large tables.
  • One would usually add DISTINCT to my query (SELECT DISTINCT CR FROM ...), so as to get every value just once. That would be a sort operation, but only on the few records already found. Again, no big deal.
  • If the string lengths have to be dealt with quite often, one might think of creating a computed column (calculated field) for it. This is available as of Ms Access 2010. But reading up on this shows that you cannot index calculated fields in MS Access. As long as this holds true, there is hardly any benefit from them. Applying LEN on the strings is usually not what makes such queries slow.

Simple bubble sort c#

Bubble sort with sort direction -

using System;

public class Program
    public static void Main(string[] args)
        var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };


        Array.ForEach(input, Console.WriteLine);


    public enum Direction
        Ascending = 0,

    public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
        bool swapped;
        var length = input.Length;

            swapped = false;
            for (var index = 0; index < length - 1; index++)
                var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];

                if (needSwap)
                    var temp = input[index];
                    input[index] = input[index + 1];
                    input[index + 1] = temp;
                    swapped = true;
        } while (swapped);

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        0 as total,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
        sum(orders.quantity*orders.product_price) as total, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

rejected master -> master (non-fast-forward)

I had same as issue. I use Git Totoise. Just Right Click ->TotoiseGit -> Clean Up . Now you can push to Github It worked fine with me :D

How to merge two sorted arrays into a sorted array?

It can be done in 4 statements as below

 int a[] = {10, 20, 30};
 int b[]= {9, 14, 11};
 int res[]=new int[a.legth+b.length]; 
 System.arraycopy(a,0, res, 0, a.length); 
 System.arraycopy(b,0,res,a.length, b.length);

Hibernate Criteria Query to get specific columns

Use Projections to specify which columns you would like to return.


SQL Query


Hibernate Alternative

Criteria cr = session.createCriteria(User.class)
      .add("id"), "id")
      .add("Name"), "Name"))

  List<User> list = cr.list();

How can I align two divs horizontally?

<style type="text/css">

<div id="floatingDivs">
    <span>source list</span>
    <select size="10">
        <option />
        <option />
        <option />

<div id="floatingDivs">
    <span>destination list</span>
    <select size="10">
        <option />
        <option />
        <option />


Extract the last substring from a cell

Simpler would be: =TRIM(RIGHT(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),99))

You can use A2 in place of TRIM(A2) if you are sure that your data doesn't contain any unwanted spaces.

Based on concept explained by Rick Rothstein:

Sorry for being necroposter!

What's the maximum value for an int in PHP?

Ah I found it: 232 - 1 (2147483647)

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

$large_number =  2147483647;
// output: int(2147483647)

$large_number =  2147483648;
// output: float(2147483648)

javac not working in windows command prompt

";C:\Program Files\Java\jdk1.6.0\bin" sometime you may forget to put semicolon on last existing path.

Removing pip's cache?

pip can install a package ignoring the cache, like this

pip --no-cache-dir install scipy

Maven: Failed to read artifact descriptor

I had the same issue with eclipse where the maven build command line worked just fine BUT try this

  • go into .m2/repository and wipe the directory associated
  • run update maven dependencies in eclipse

The error goes away....why my mvn command line worked with those directories and eclipse .m2eclipse could not, I have no idea and it kinda sucks. My project is now working in eclipse again.

How do you use a variable in a regular expression?

To satisfy my need to insert a variable/alias/function into a Regular Expression, this is what I came up with:

oldre = /xx\(""\)/;
function newre(e){
    return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")

String.prototype.replaceAll = this.replace(newre(oldre), "withThis");

where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.

Round integers to the nearest 10

About the round(..) function returning a float

That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

See the discussion here for details.

c# search string in txt file

I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:

                foreach (var line in File.ReadLines(pathToFile))
                    if (line.Contains("CustomerEN") && current == null)
                        current = new List<string>();
                    else if (line.Contains("CustomerEN") && current != null)
                string s = String.Join(",", current);

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

I get this every time I want to create an application in VC++.

Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.

Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

a {_x000D_
    background-color: #FF0;_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
<a>Navigation Link</a>

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

List comprehension on a nested list?

If you don't like nested list comprehensions, you can make use of the map function as well,

>>> from pprint import pprint

>>> l = l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] 

>>> pprint(l)
[['40', '20', '10', '30'],
['20', '20', '20', '20', '20', '30', '20'],
['30', '20', '30', '50', '10', '30', '20', '20', '20'],
['100', '100'],
['100', '100', '100', '100', '100'],
['100', '100', '100', '100']]

>>> float_l = [map(float, nested_list) for nested_list in l]

>>> pprint(float_l)
[[40.0, 20.0, 10.0, 30.0],
[20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0],
[30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0],
[100.0, 100.0],
[100.0, 100.0, 100.0, 100.0, 100.0],
[100.0, 100.0, 100.0, 100.0]]

Is there any way to install Composer globally on Windows?

Install Composer

On Windows, you can use the Composer Windows Installer.

How can I style even and odd elements?

li:nth-child(1n) { color:green; }_x000D_
li:nth-child(2n) { color:red; }
  <li>list element 1</li>_x000D_
  <li>list element 2</li>_x000D_
  <li>list element 3</li>_x000D_
  <li>list element 4</li>_x000D_

See browser support here : CSS3 :nth-child() Selector

Batch files: How to read a file?

Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: findstr /v "randomtextthatnoonewilluse" filename.txt

How do I return an int from EditText? (Android)

First of all get a string from an EDITTEXT and then convert this string into integer like

      String no=myTxt.getText().toString();       //this will get a string                               
      int no2=Integer.parseInt(no);              //this will get a no from the string

Get current domain

I know this might not be entirely on the subject, but in my experience, I find storing WWW-ness of current URL in a variable useful.

Edit: In addition, please see my comment below, to see what this is getting at.

This is important when determining whether to dispatch Ajax calls with "www", or without:

$.ajax("url" : "", ...

$.ajax("url" : "", ...

When dispatching an Ajax call the domain name must match that of in the browser's address bar, otherwise you will have Uncaught SecurityError in console.

So I came up with this solution to address the issue:

    substr($_SERVER['SERVER_NAME'], 0, 3) == "www" ? $WWW = true : $WWW = false;

    if ($WWW) {
        /* We have */
    } else {
        /* We have */

Then, based on whether $WWW is true, or false run the proper Ajax call.

I know this might sound trivial, but this is such a common problem that is easy to trip over.

Simple URL GET/POST function in Python

I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

#!/usr/bin/env python3
import http.client
import json

print("\n GET example")
conn = http.client.HTTPSConnection("")
conn.request("GET", "/get")
response = conn.getresponse()
data ='utf-8')
print(response.status, response.reason)

print("\n POST example")
conn = http.client.HTTPSConnection('')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.status, response.reason)

print("\n PUT example ")
conn = http.client.HTTPSConnection('')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(, response.reason)
print(response.status, response.reason)

print("\n delete example")
conn = http.client.HTTPSConnection('')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(, response.reason)
print(response.status, response.reason)

How to remove indentation from an unordered list item?

My preferred solution to remove <ul> indentation is a simple CSS one-liner:

ul { padding-left: 1.2em; }
<p>A leading line of paragraph text</p>_x000D_
    <li>Bullet points align with paragraph text above.</li>_x000D_
    <li>Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. </li>_x000D_
    <li>List item 3</li>_x000D_
<p>A trailing line of paragraph text</p>

This solution is not only lightweight, but has multiple advantages:

  • It nicely left-aligns <ul>'s bullet points to surrounding normal paragraph text (= indenting of <ul> removed).
  • The text blocks within the <li> elements remain correctly indented if they wrap around into multiple lines.

Legacy info:
For IE versions 8 and below you must use margin-left instead:

    ul { margin-left: 1.2em; }

How to do logging in React Native?

There is normally two scenarios where we need debugging.

  1. When we facing issues related to data and we want to check our data and debugging related to data in that case console.log('data::',data)

    and debug js remotely is the best option.

  2. Other case is the UI and styles related issues where we need to check styling of the component in that case react-dev-tools is the best option.

    both of the methods mention here.

How to detect if JavaScript is disabled?

Adding a refresh in meta inside noscript is not a good idea.

  1. Because noscript tag is not XHTML compliant

  2. The attribute value "Refresh" is nonstandard, and should not be used. "Refresh" takes the control of a page away from the user. Using "Refresh" will cause a failure in W3C's Web Content Accessibility Guidelines --- Reference

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx

To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help."tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

Cannot lower case button text in android studio

in XML Code
add this line android:textAllCaps="false" like bellow code

       ** android:textAllCaps="false" ** />


in Java code (programmatically)
add this line to your button setAllCaps(false)

Button btn = (Button) findViewById(;

Convert PDF to clean SVG?

I am currently using PDFBox which has good support for graphic output. There is good support for extracting the vector strokes and also for managing fonts. There are some good tools for trying it out (e.g. PDFReader will display as Java Graphics2D). You can intercept the graphics tool with an SVG tool like Batik (I do this and it gives good capture).

There is no simple way to convert all PDF to SVG - it depends on the strategy and tools used to create the PDFs. Some text is converted to vectors and cannot be easily reconstructed - you have to install vector fonts and look them up.

UPDATE: I have now developed this into a package PDF2SVG which does not use Batik any more:

which has been tested on a range of PDFs. It produces SVG output consisting of

  • characters as one <svg:text> per character
  • paths as <svg:path>
  • images as <svg:image>

Later packages will (hopefully) convert the characters to running text and the paths to higher-level graphics objects

UPDATE: We can now re-create running text from the SVG characters. We've also converted diagrams to domain-specific XML (e.g. chemical spectra). See It's still in Alpha, but is moving at a useful speed. Anyone can join in!

UPDATE. (@Tim Kelty) We are continuing to work on PDF2SVG and also downstream tools that do (limited) Java OCR and creation of higher-level graphics primitives (arrows, boxes, etc.) See and . This is a funded project to capture 100 million facts from the scientific literature ( much of which is PDF.

how to sort pandas dataframe from one column

Just adding some more operations on data. Suppose we have a dataframe df, we can do several operations to get desired outputs

ID         cost      tax    label
1       216590      1600    test      
2       523213      1800    test 
3          250      1500    experiment

(df['label'].value_counts().to_frame().reset_index()).sort_values('label', ascending=False)

will give sorted output of labels as a dataframe

    index   label
0   test        2
1   experiment  1

What is the difference between decodeURIComponent and decodeURI?

As I had the same question, but didn't find the answer here, I made some tests in order to figure out what the difference actually is. I did this, since I need the encoding for something, which is not URL/URI related.

  • encodeURIComponent("A") returns "A", it does not encode "A" to "%41"
  • decodeURIComponent("%41") returns "A".
  • encodeURI("A") returns "A", it does not encode "A" to "%41"
  • decodeURI("%41") returns "A".

-That means both can decode alphanumeric characters, even though they did not encode them. However...

  • encodeURIComponent("&") returns "%26".
  • decodeURIComponent("%26") returns "&".
  • encodeURI("&") returns "&".
  • decodeURI("%26") returns "%26".

Even though encodeURIComponent does not encode all characters, decodeURIComponent can decode any value between %00 and %7F.

Note: It appears that if you try to decode a value above %7F (unless it's a unicode value), then your script will fail with an "URI error".

Changing three.js background to transparent or other color

In 2020 using r115 it works very good with this:

const renderer = new THREE.WebGLRenderer({ alpha: true }); const scene = new THREE.Scene(); scene.background = null;

Angular bootstrap datepicker date format does not format ng-model value

After checking the above answers, I came up with this and it worked perfectly without having to add an extra attribute to your markup

angular.module('app').directive('datepickerPopup', function(dateFilter) {
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
            ngModel.$parsers.push(function(viewValue) {
                return dateFilter(viewValue, 'yyyy-MM-dd');

no such file to load -- rubygems (LoadError)

I have a hunch that you have two ruby versions. Please paste the output of following command:

$ which -a ruby

updated regarding to the comment:

Nuke one version and leave only one. I had same problem with two versions looking at different locations for gems. Had me going crazy for few weeks. Put up a bounty here at SO got me same answer I'm giving to you.

All I did was nuke one installation of ruby and left the one managable via ports. I'd suggest doing this:

  1. Remove ruby version installed via ports (yum or whatever package manager).
  2. Remove ruby version that came with OS (hardcore rm by hand).
  3. Install ruby version from ports with different prefix (/usr instead of /usr/local)
  4. Reinstall rubygems

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

How can I count the occurrences of a list item?

I had this problem today and rolled my own solution before I thought to check SO. This:

dict((i,a.count(i)) for i in a)

is really, really slow for large lists. My solution

def occurDict(items):
    d = {}
    for i in items:
        if i in d:
            d[i] = d[i]+1
            d[i] = 1
return d

is actually a bit faster than the Counter solution, at least for Python 2.7.

How to switch text case in visual studio code

To have in Visual Studio Code what you can do in Sublime Text ( CTRL+K CTRL+U and CTRL+K CTRL+L ) you could do this:

  • Open "Keyboard Shortcuts" with click on "File -> Preferences -> Keyboard Shortcuts"
  • Click on "keybindings.json" link which appears under "Search keybindings" field
  • Between the [] brackets add:

        "key": "ctrl+k ctrl+u",
        "command": "editor.action.transformToUppercase",
        "when": "editorTextFocus"
        "key": "ctrl+k ctrl+l",
        "command": "editor.action.transformToLowercase",
        "when": "editorTextFocus"
  • Save and close "keybindings.json"

Another way:
Microsoft released "Sublime Text Keymap and Settings Importer", an extension which imports keybindings and settings from Sublime Text to VS Code. -

How to convert an address into a Google Maps Link (NOT MAP)

Also, anyone wanting to manually URLENCODE the address:

You can use that to create specific rules that meet GM standards.

How to change the button text of <input type="file" />?

for me it does not work the custom text with bootstrap-filestyle. It help with button decoration but text its weird to be changed, before get into wrestling with css i try the following :

$( document ).ready(function() {
   $('.buttonText').html('Seleccione ficheros');

bootstrap-filestyle render the component as span with a class named butonText, so when document load just change the text. easy right and it must work on all browsers.


How to get a string between two characters?

Use Pattern and Matcher

public class Chk {

    public static void main(String[] args) {

        String s = "test string (67)";
        ArrayList<String> arL = new ArrayList<String>();
        ArrayList<String> inL = new ArrayList<String>();

        Pattern pat = Pattern.compile("\\(\\w+\\)");
        Matcher mat = pat.matcher(s);

        while (mat.find()) {



        for (String sx : arL) {

            Pattern p = Pattern.compile("(\\w+)");
            Matcher m = p.matcher(sx);

            while (m.find()) {





Alternate table with new not null Column in existing table in SQL

There are two ways to add the NOT NULL Columns to the table :

  1. ALTER the table by adding the column with NULL constraint. Fill the column with some data. Ex: column can be updated with ''

  2. ALTER the table by adding the column with NOT NULL constraint by giving DEFAULT values. ALTER table TableName ADD NewColumn DataType NOT NULL DEFAULT ''

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:


Loop through a date range with JavaScript

If you want an efficient way with milliseconds:

var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
    daysOfYear.push(new Date(d));

How to change checkbox's border style in CSS?

You can use box shadows to fake a border:

-webkit-box-shadow: 0px 0px 0px 1px rgba(255,0,0,1);
-moz-box-shadow: 0px 0px 0px 1px rgba(255,0,0,1);
box-shadow: 0px 0px 0px 1px rgba(255,0,0,1);

View the change history of a file using Git versioning


  1. In the menu enable to display unchanged files: View / Show unchanged files
  2. Right click the file and select 'Log' or press 'Ctrl-L'

Android: Background Image Size (in Pixel) which Support All Devices

The following are the best dimensions for the app to run in all devices. For understanding multiple supporting screens you have to read

xxxhdpi: 1280x1920 px
xxhdpi: 960x1600 px
xhdpi: 640x960 px
hdpi: 480x800 px
mdpi: 320x480 px
ldpi: 240x320 px

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    public void write(int b) throws IOException {
        this.string.append((char) b );

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

How to convert a number to string and vice versa in C++

I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

// make_string
class make_string {
  template <typename T>
  make_string& operator<<( T const & val ) {
    buffer_ << val;
    return *this;
  operator std::string() const {
    return buffer_.str();
  std::ostringstream buffer_;

And then you use it as;

string str = make_string() << 6 << 8 << "hello";

Quite nifty!

Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
  std::stringstream buf;
  buf << str;
  buf >> val;
  return val;

Use as:

int x = parse_string<int>("78");

You might also want versions for wstrings.

How to do case insensitive search in Vim

You can use in your vimrc those commands:

  • set ignorecase - All your searches will be case insensitive
  • set smartcase - Your search will be case sensitive if it contains an uppercase letter

You need to set ignorecase if you want to use what smartcase provides.

I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')

enter image description here

Update elements in a JSONObject

public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
            JSONObject json = new JSONObject();
            // get the keys of json object
            Iterator iterator = obj.keys();
            String key = null;
            while (iterator.hasNext()) {
                key = (String);
                // if the key is a string, then update the value
                if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
                    if ((key.equals(keyString))) {
                        // put new value
                        obj.put(key, newValue);
                        return obj;

                // if it's jsonobject
                if (obj.optJSONObject(key) != null) {
                    updateJson(obj.getJSONObject(key), keyString, newValue);

                // if it's jsonarray
                if (obj.optJSONArray(key) != null) {
                    JSONArray jArray = obj.getJSONArray(key);
                    for (int i = 0; i < jArray.length(); i++) {
                        updateJson(jArray.getJSONObject(i), keyString, newValue);
            return obj;

Downloading a file from spring controllers

Below code worked for me to generate and download a text file.

@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {

    String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
    byte[] output = regData.getBytes();

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set("charset", "utf-8");
    responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");

    return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them

REST API error return good practices

I know this is extremely late to the party, but now, in year 2013, we have a few media types to cover error handling in a common distributed (RESTful) fashion. See "vnd.error", application/vnd.error+json ( and "Problem Details for HTTP APIs", application/problem+json (

How do I install PyCrypto on Windows?

After years and years, python finally agreed for a binary disribution called wheel which allows to install even binary extensions on Windows without having a compiler with simple pip install packagename. There is a list of popular packages with their status. Pycrypto is not there yet, but lxml, PySide and Scrapy for example.

Edited Nov 2015: pip uninstall pycrypto & pip install pycryptodome. It is a pycrypto fork with new features and it supports wheel. It replaces pycrypto, so existing code will continue to work (see

How to export a Vagrant virtual machine to transfer it

None of the above answers worked for me. I have been 2 days working out the way to migrate a Vagrant + VirtualBox Machine from a computer to another... It's possible!

First, you need to understand that the virtual machine is separated from your sync / shared folder. So when you pack your machine you're packing it without your files, but with the databases.

What you need to do:

1- Open the CMD of your computer 1 host machine (Command line. Open it as Adminitrator with the right button -> "Run as administrator") and go to your vagrant installed files. On my case: C:/VVV You will see your Vagrantfile an also these folders:


The /www/ folder is where I have my Sync Folder with my development domains. You may have your sync folder in other place, just be sure to understand what you are doing. Also /config and /database are sync folders.

2- run this command: vagrant package --vagrantfile Vagrantfile

(This command does a package of your virtual machine using you Vagrantfile configuration.)

Here's what you can read on the Vagrant documentation about the command:

A common misconception is that the --vagrantfile option will package a Vagrantfile that is used when vagrant init is used with this box. This is not the case. Instead, a Vagrantfile is loaded and read as part of the Vagrant load process when the box is used. For more information, read about the Vagrantfile load order.

When finnished, you will have a file.

3- Copy all these files (/config, /database, Vagrantfile,, etc.) and paste them on your Computer 2 just where you want to install your virtual machine (on my case D:/VVV).

Now you have a copy of everything you need on your computer 2 host.

4- run this: vagrant box add --name VVV

(The --name is used to name your virtual machine. On my case it's named VVV) (You can use --force if you already have a virtual machine with this name and want to overwrite it. (Use carefully !))

This will unpack your new vagrant Virtual machine.

5- When finnished, run: vagrant up

The machine will install and you should see it on the "Oracle virtual machine box manager". If you cannot see the virtual machine, try running the Oracle VM box as administrator (right click -> Run as administrator)

You now may have everything ok but remember to see if your hosts are as you expected:


6- Maybe it's a good idea to copy your host file from your Computer 1 to your Computer 2. Or copy the lines you need. In my case these are the hosts I need:

Where the is the IP of my Virtual machine and and are developing hosts.

I hope this can help you :) I'll be happy if you feedback your go.

Some particularities of my case that you may find:

When I ran vagrant up, there was a problem with mysql, it wasn't working. I had to run on the Virtual server (right click on the oracle virtual machine -> Show console): apt-get install mysql-server

After this, I ran again vagrant up and everything was working but without data on the databases. So I did a mysqldump all-tables from the Computer 1 and upload them to Computer 2.

OTHER NOTES: My virtual machine is not exactly on Computer 1 and Computer 2. For example, I made some time ago internal configuration to use NFS (to speed up the server sync folders) and I needed to run again this command on the Computer 2 host: vagrant plugin install vagrant-winnfsd

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

        find <Path> <Conditions> | xargs cp -t <copy file path>
        find -mtime -1 -type f | xargs cp -t inner/
  2. But our production data files might contain spaces, so most of time this command is effective:

       find <path> <condition> -exec cp '{}' <copy path> \;
       find -mtime -1 -type f -exec cp '{}' inner/ \;

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

PHP Warning: PHP Startup: Unable to load dynamic library

phpStom with XAMPP

TL;DR Except from verifying that the files exist, you might need to add the drive letter to some records in your php.ini file

I suddenly started having a problem using phpStorm 7 for debugging php with xampp and xdebug. When trying to set intellij interperter to be xampps php I got a lot of the warnings like the one in the question, for example:

Unable to load dynamic library '/xampp/php/ext/php_bz2.dll'

For some reason I had to add my drive letter to the records of extension_dir and browscap in the php.ini file:

extension_dir = "\xampp\php\ext"
browscap = "\xampp\php\extras\browscap.ini"


extension_dir = "e:\xampp\php\ext"
browscap = "e:\xampp\php\extras\browscap.ini"

Select first empty cell in column F starting from row 1. (without using offset )

Code of Sam is good but I think it need some correction,

Public Sub SelectFirstBlankCell()
    Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
    Dim currentRowValue As String

    sourceCol = 6   'column F has a value of 6
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    'for every row, find the first blank cell and select it
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, sourceCol).Value
        If IsEmpty(currentRowValue) Or currentRowValue = "" Then
            Cells(currentRow, sourceCol).Select
            Exit For 'This is missing...
        End If
End Sub


text box input height

You can define a class or id for input fields.


input {
    line-height: 20px;

Hope this helps you.

How to change indentation mode in Atom?

You could try going to "Atom > Preferences > Editor" and set Tab length to 4.

enter image description here

This is for mac. For windows you will have to find the appropriate menu.

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

Adding a Scrollable JTextArea (Java)

You don't need two JScrollPanes.


JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);  

// Add the scroll pane into the content pane
JFrame f = new JFrame();

Removing Data From ElasticSearch

#list all index:       curl -XGET http://localhost:9200/_cat/indices?v 

enter image description here

#delete index:         curl -XDELETE 'localhost:9200/index_name'
#delete all indices:   curl -XDELETE 'localhost:9200/_all'
#delete document   :   curl -XDELETE 'localhost:9200/index_name/type_name/document_id'

Install kibana. Kibana has a smarter dev tool which helps to build query easily.

enter image description here

Select a row from html table and send values onclick of a button

This below code will give selected row, you can parse the values from it and send to the AJAX call.

$(".selected").click(function () {
var row = $(this).parent().parent().parent().html();            

Access POST values in Symfony2 request object

The form post values are stored under the name of the form in the request. For example, if you've overridden the getName() method of ContactType() to return "contact", you would do this:

$postData = $request->request->get('contact');
$name_value = $postData['name'];

If you're still having trouble, try doing a var_dump() on $request->request->all() to see all the post values.

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

Convert a date format in PHP

Use date_create and date_format

Try this.

function formatDate($input, $output){
  $inputdate = date_create($input);
  $output = date_format($inputdate, $output);
  return $output;

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    ' Assumes that the filter was previously applied
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

How to prevent page scrolling when scrolling a DIV element?

You can do this without JavaScript. You can set the style on both divs to position: fixed and overflow-y: auto. You may need to make one of them higher than the other by setting its z-index (if they overlap).

Here's a basic example on CodePen.

python JSON only get keys in first level

for key in data.keys():
    print key

How do I use DateTime.TryParse with a Nullable<DateTime>?

DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;

(There might be more elegant solutions, but why don't you simply do something as above?)

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

The meaning of NoInitialContextException error

I solved the same problem by adding the following Jar libraries to my project:

  • appserv-rt.jar
  • javaee.jar

from the folder : C:\Program Files\glassfish-4.0\glassfish\lib

The links to these libraries were broken and Netbeans didn't found the right classes to use.

How can I divide one column of a data frame through another?

Hadley Wickham


packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Can VS Code run on Android?

The accepted answer is correct as asked, below answers the opposite question of developing Android on VS Code.


Ultimately you can automate building and running your app on a device emulator by adding the function below to your $PATH and running runDebugApp <module> <start activity> from the integrated terminal:

# run android app
# usage runDebugApp [module] [fully qualified start activity com.package/com.package.MainActivity]
function runDebugApp(){
  ./gradlew -offline :"$1":installDebug && adb shell am start "$2" && adb logcat -d > logcat.log

glob exclude pattern

As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:


Recursive is the default for non-fast-forward merges. We're all familiar with that one.


I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge


Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)


Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

When I used --allow-unrelated-histories, this command generated too many conflicts. There were conflicts in files which I didn't even work on. To get over the error " Refusing to merge unrelated histories", I used following rebase command:

git pull --rebase=preserve --allow-unrelated-histories

After this commit the uncommitted changes with a commit message. Finally, run the following command:

git rebase --continue

After this, my working copy was up-to-date with the remote copy and I was able to push my changes as before. No more unrelated histories error while pulling.

How to convert Java String to JSON Object

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

Open URL in Java to get the content

If you just want to open up the webpage, I think less is more in this case:

import java.awt.Desktop;
import; //Note this is URI, not URL

class BrowseURL{
    public static void main(String args[]) throws Exception{
        // Create Desktop object
        Desktop d=Desktop.getDesktop();

        // Browse a URL, say
        d.browse(new URI(""));


I want to load another HTML page after a specific amount of time

<meta http-equiv="refresh" content="5;URL='form2.html'">

Char array declaration and initialization in C

I think these are two really different cases. In the first case memory is allocated and initialized in compile-time. In the second - in runtime.

Disable ScrollView Programmatically?

public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {     
    case MotionEvent.ACTION_DOWN:         
        // if we can scroll pass the event to the superclass      
        if (mScrollable) return super.onInterceptTouchEvent(ev);      
        // only continue to handle the touch event if scrolling enabled    
        return mScrollable; // mScrollable is always false at this point     
            return super.onInterceptTouchEvent(ev);      

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
```{r, echo=FALSE}
```{r, echo=FALSE}

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

jQuery - setting the selected value of a select control via its text description

Select by description for jQuery v1.6+

var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).prop('selected', true);
<script src=""></script>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_

jQuery versions below 1.6 and greater than or equal to 1.4

var text1 = 'Two';_x000D_
$("select option").filter(function() {_x000D_
  //may want to use $.trim in here_x000D_
  return $(this).text() == text1;_x000D_
}).attr('selected', true);
<script src=""></script>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_

Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.

Previous versions

val() should handle both cases.

$('select').val('1'); // selects "Two"_x000D_
$('select').val('Two'); // also selects "Two"
<script src=""></script>_x000D_
  <option value="0">One</option>_x000D_
  <option value="1">Two</option>_x000D_

Remove Blank option from Select Option with AngularJS

There are multiple ways like -

<select ng-init="feed.config = options[0]" ng-model="feed.config"
        ng-options="template.value as for template in feed.configs">


$scope.feed.config = $scope.configs[0].name;

Is a Java hashmap search really O(1)?

This basically goes for most hash table implementations in most programming languages, as the algorithm itself doesn't really change.

If there are no collisions present in the table, you only have to do a single look-up, therefore the running time is O(1). If there are collisions present, you have to do more than one look-up, which drives down the performance towards O(n).

Turn a number into star rating display using jQuery and CSS

Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?

For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.

Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).

What are some ways of accessing Microsoft SQL Server from Linux?

FreeTDS + unixODBC or iODBC

Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.

unixODBC has isql, iODBC has iodbctest

You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)

I'm personally using FreeTDS + iODBC:

$more /etc/freetds/freetds.conf
    host =
    port = 1433
    tds version = 8.0

$ more /etc/odbc.ini
Driver = /usr/local/freetds/lib/
Description = ODBC to SQLServer via FreeTDS
Trace = No
Servername =
Database = accounts_ver8

How do I get the collection of Model State Errors in ASP.NET MVC?

<% ViewData.ModelState.IsValid %>


<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

and for a specific property...

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection

How do I return clean JSON from a WCF Service?

I faced the same problem, and resolved it by changing the BodyStyle attribut value to "WebMessageBodyStyle.Bare" :

[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetProjectWithGeocodings/{projectId}")]
GeoCod_Project GetProjectWithGeocodings(string projectId);

The returned object will no longer be wrapped.

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

Count number of times a date occurs and make a graph out of it

If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1) next to it and copy the formula down. This assumes you have your values in range A1:A100 and the de-duplicated values are in column B.

how to dynamically add options to an existing select in vanilla javascript

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript


 daySelect = document.getElementById('daySelect');
 daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');

CSS / HTML Navigation and Logo on same line

1) you can float the image to the left:

<img style="float:left" src="">

2)You can use an HTML table to place elements on one line.

Code below

  <div class="navigation-bar">
    <div id="navigation-container">
          <td><img src=""></td>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Get in Touch</a></li>

C# : 'is' keyword and checking for Not

The is operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the ! operator. Why would you want to have a different operator just for this?

How to flush output of print function?

I first struggled to understand how the flush option was working. I wanted to do a 'loading display' and here is the solution I found:

for i in range(100000):
    print('{:s}\r'.format(''), end='', flush=True)
    print('Loading index: {:d}/100000'.format(i+1), end='')

The first line flushes the previous print and the second line prints a new updated message. I don't know if an one-line syntax exists here.

'printf' vs. 'cout' in C++

cout<< "Hello";
printf("%s", "Hello"); 

Both are used to print values. They have completely different syntax. C++ has both, C only has printf.

How to concat a string to xsl:value-of select="...?

Not the most readable solution, but you can mix the result from a value-of with plain text:

  <xsl:attribute name="href"> 
    Text<xsl:value-of select="/*/properties/property[@name='report']/@value"/>Text

Split string in JavaScript and detect line break

Here's the final code I [OP] used. Probably not best practice, but it worked.

function wrapText(context, text, x, y, maxWidth, lineHeight) {

    var breaks = text.split('\n');
    var newLines = "";
    for(var i = 0; i < breaks.length; i ++){
      newLines = newLines + breaks[i] + ' breakLine ';

    var words = newLines.split(' ');
    var line = '';
    for(var n = 0; n < words.length; n++) {
      if(words[n] != 'breakLine'){
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        else {
          line = testLine;
          context.fillText(line, x, y);
          line = '';
          y += lineHeight;
    context.fillText(line, x, y);

What's the difference between %s and %d in Python string formatting?

from python 3 doc

%d is for decimal integer

%s is for generic string or object and in case of object, it will be converted to string

Consider the following code

name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))

the out put will be

giacomo 4.3 4 4.300000 4.3

as you can see %d will truncate to integer, %s will maintain formatting, %f will print as float and %g is used for generic number


print('%d' % (name))

will generate an exception; you cannot convert string to number

"rm -rf" equivalent for Windows?

You can install cygwin, which has rm as well as ls etc.

XSL xsl:template match="/"

The value of the match attribute of the <xsl:template> instruction must be a match pattern.

Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.

/ in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node().

A match pattern can contain the // abbreviation.

Examples of match patterns:

<xsl:template match="table">

can be applied on any element named table.

<xsl:template match="x/y">

can be applied on any element named y whose parent is an element named x.

<xsl:template match="*">

can be applied to any element.

<xsl:template match="/*">

can be applied only to the top element of an XML document.

<xsl:template match="@*">

can be applied to any attribute.

<xsl:template match="text()">

can be applied to any text node.

<xsl:template match="comment()">

can be applied to any comment node.

<xsl:template match="processing-instruction()">

can be applied to any processing instruction node.

<xsl:template match="node()">

can be applied to any node: element, text, comment or processing instructon.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference


 mAdapter = new RecordingsListAdapter(this, recordings);


 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

For me this error appeared immediatey after I changed the user's home directory by

sudo usermod -d var/www/html username

It can also happen because of lack of proper permission to authorized_key file in ~/.ssh. Make sure the permission of this file is 0600 and permission of ~/.ssh is 700.

How to get the size of a file in MB (Megabytes)?

Easiest is by using FileUtils from Apache commons-io.( )

Returns human readable file size from Bytes to Exabytes , rounding down to the boundary.

File fileObj = new File(filePathString);
String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());

// output will be like 56 MB 

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

I handle the ajax request by using Selenium and the Firefox web driver. It is not that fast if you need the crawler as a daemon, but much better than any manual solution. I wrote a short tutorial here for reference

Differences between strong and weak in Objective-C

Strong: Basically Used With Properties we used to get or send data from/into another classes. Weak: Usually all outlets, connections are of Weak type from Interface.

Nonatomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Nonatomic instance make our properties to deal with one thread at a time. Hopefully it helpful for you.

Updating Python on Mac

On a mac use the following in the terminal to update python if you have anaconda:

conda update python

Apache Name Virtual Host with SSL

First you need NameVirtualHost ip:443 in you config file! You probably have one with 80 at the end, but you will also need one with 443.

Second you need a *.domain certificate (wildcard) (it is possible to make one)

Third you can make only something.domain webs in one ip (because of the certificate)

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

Here's a demo:

Client on Node.js: Uncaught ReferenceError: require is not defined

ES6: In HTML, include the main JavaScript file using attribute type="module" (browser support):

<script type="module" src="script.js"></script>

And in the script.js file, include another file like this:

import { hello } from './module.js';
// alert(hello());

Inside the included file (module.js), you must export the function/class that you will import:

export function hello() {
    return "Hello World";

A working example is here. More information is here.

How do I connect to a MySQL Database in Python?

MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.

The openssl extension is required for SSL/TLS protection

I had the exact same problem and couldn't find a solution, so after thinking and looking for a while I figured that my PHP.INI apparently didn't look in the correct directory for my PHP Extensions, so I went under:

"Directory in which the loadable extensions (modules) reside." And found the following:

; extension_dir = "./"
; On windows:
;extension_dir = "ext"

And simply removed the ; infront of "extension_dir = "ext", note this is only for Windows, remove the semicolon in front of the first extension_dir if you are running a different operating system.

I have no idea why mine wasn't already unmarked, but it's just something to look for if you are having problems.

How to get size of mysql database?

To get a result in MB:


To get a result in GB:

SUM(ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024 / 1024), 2)) AS "SIZE IN GB"

typedef fixed length array

You want

typedef char type24[3];

C type declarations are strange that way. You put the type exactly where the variable name would go if you were declaring a variable of that type.

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

Combining paste() and expression() functions in plot labels

If x^2 and y^2 were expressions already given in the variable squared, this solves the problem:

labNames <- c('xLab','yLab')
squared <- c(expression('x'^2), expression('y'^2))

xlab <- eval(bquote(expression(.(labNames[1]) ~ .(squared[1][[1]]))))
ylab <- eval(bquote(expression(.(labNames[2]) ~ .(squared[2][[1]]))))

plot(c(1:10), xlab = xlab, ylab = ylab)

Please note the [[1]] behind squared[1]. It gives you the content of "expression(...)" between the brackets without any escape characters.

Loop and get key/value pair for JSON array using jQuery

Parse the JSON string and you can loop through the keys.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';_x000D_
var data = JSON.parse(resultJSON);_x000D_
for (var key in data)_x000D_
    //console.log(key + ' : ' + data[key]);_x000D_
    alert(key + ' --> ' + data[key]);_x000D_

How to open select file dialog via js?


 * Select file(s).
 * @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
 * @param {Boolean} multiple Indicates if the user can select multiples file.
 * @returns {Promise<File|File[]>} A promise of a file or array of files in case the multiple parameter is true.
function (contentType, multiple){
    return new Promise(resolve => {
        let input = document.createElement('input');
        input.type = 'file';
        input.multiple = multiple;
        input.accept = contentType;

        input.onchange = _ => {
            let files = Array.from(input.files);
            if (multiple)


// Content wrapper element_x000D_
let contentElement = document.getElementById("content");_x000D_
// Button callback_x000D_
async function onButtonClicked(){_x000D_
    let files = await selectFile("image/*", true);_x000D_
    contentElement.innerHTML = => `<img src="${URL.createObjectURL(file)}" style="width: 100px; height: 100px;">`).join('');_x000D_
// ---- function definition ----_x000D_
function selectFile (contentType, multiple){_x000D_
    return new Promise(resolve => {_x000D_
        let input = document.createElement('input');_x000D_
        input.type = 'file';_x000D_
        input.multiple = multiple;_x000D_
        input.accept = contentType;_x000D_
        input.onchange = _ => {_x000D_
            let files = Array.from(input.files);_x000D_
            if (multiple)_x000D_
<button onclick="onButtonClicked()">Select images</button>_x000D_
<div id="content"></div>

Array String Declaration

I think the beginning to the resolution to this issue is the fact that the use of the for loop or any other function or action can not be done in the class definition but needs to be included in a method/constructor/block definition inside of a class.

CodeIgniter Select Query

When use codeIgniter Framework then refer this active records link. how the data interact with structure and more.

The following functions allow you to build SQL SELECT statements.

Selecting Data


Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:

$query = $this->db->get('mytable');

With access to each row

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
    echo $row->title;

Where clues



 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Select field

$this->db->select('title, content, date');

$query = $this->db->get('mytable');

// Produces: SELECT title, content, date FROM mytable


$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); 
$query = $this->db->get('mytable');

How to return JSON with ASP.NET & jQuery

Try to use this , it works perfectly for me


   varb = new List<object>();

 // Example 

   varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});

 // JSON  + Serializ

public string Json()
            return (new JavaScriptSerializer()).Serialize(varb);

//  Jquery SIDE 

  var datasets = {
            "Products": {
                label: "Products",
                data: <%= getJson() %> 

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Its as simple as this:

    @p1 sql_variant,
    @p2 sql_variant
)  RETURNS sql_variant
        WHEN @p1 IS NULL AND @p2 IS NOT NULL THEN @p2 
        WHEN @p2 IS NULL AND @p1 IS NOT NULL THEN @p1
        WHEN @p1 > @p2 THEN @p1
        ELSE @p2 END

Updating state on props change in React Form

The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:

componentWillReceiveProps(nextProps) {
  // You don't have to do this check first, but it can help prevent an unneeded render
  if (nextProps.startTime !== this.state.startTime) {
    this.setState({ startTime: nextProps.startTime });

becomes the following in a functional hooks driven component:

// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
useEffect(() => {
  if (props.startTime !== startTime) {
}, [props.startTime]);

we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.

ALTER TABLE, set null in not null column, PostgreSQL 9.1


More details in the manual:

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
        return xhr;
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
    success: function(data) {
        console.log(data); // Here is "blob" type


If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,

How may I reference the script tag that loaded the currently-executing script?

Since scripts are executed sequentially, the currently executed script tag is always the last script tag on the page until then. So, to get the script tag, you can do:

var scripts = document.getElementsByTagName( 'script' );
var thisScriptTag = scripts[ scripts.length - 1 ];

How to establish ssh key pair when "Host key verification failed"

This issue arises when the host key is expired or changed. you can remove the keys that host is using and try to ssh again, so that you are adding new key that is known to both client and server.

You can check the keys associated with your hosts with cat /.ssh/known_hosts . Now, You can remove the hosts keys manually or using the ssh-keygen option. You can do either of the following option.

  1. Manual removal of keys

    vim /.ssh/known_hosts

delete the key that is associated with your host.

  1. Remove key using ssh-keygen

    ssh-keygen -R your_host_or_host_ip

This will remove your key associated with the host.

Now, you can ssh to your host as usual and you will be asked if you want to continue to this host. Once your enter yes, this host will be added to your/.ssh/known_hosts with updated key. By now, you should be your host.

Calculating the difference between two Java date instances

int daysDiff = (date1.getTime() - date2.getTime()) / MILLIS_PER_DAY;

How to test if a double is an integer

if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
    // integer type

This checks if the rounded-down value of the double is the same as the double.

Your variable could have an int or double value and Math.floor(variable) always has an int value, so if your variable is equal to Math.floor(variable) then it must have an int value.

This also doesn't work if the value of the variable is infinite or negative infinite hence adding 'as long as the variable isn't inifinite' to the condition.

How to downgrade php from 5.5 to 5.3

Long answer: it is possible!

  1. Temporarily rename existing xampp folder
  2. Install xampp 1.7.7 into xampp folder name
  3. Folder containing just installed 1.7.7 distribution rename to different name and previously existing xampp folder rename back just to xampp.
  4. In xampp folder rename php and apache folders to different names (I propose php_prev and apache_prev) so you can after switch back to them by renaming them back.
  5. Copy apache and php folders from folder with xampp 1.7.7 into xampp directory
  6. In xampp directory comment line apache/conf/httpd.conf:458

    #Include "conf/extra/httpd-perl.conf"

  7. In xampp directory do next replaces in files:



"C:\xampp\php\.\php.exe" -f "\xampp\php\pci" -- %*


set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\php.exe" -f "%XAMPPPHPDIR%\pci" -- %*



"C:\xampp\php\.\php.exe" -f "\xampp\php\pciconf" -- %*


set XAMPPPHPDIR=C:\xampp\php "%XAMPPPHPDIR%\.\php.exe" -f "%XAMPPPHPDIR%\pciconf" -- %*



IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"


IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"



IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"


IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"



IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\.\php.exe"


IF "%PHP_PEAR_BIN_DIR%"=="" SET "PHP_PEAR_BIN_DIR=C:\xampp\php\" IF "%PHP_PEAR_PHP_BIN%"=="" SET "PHP_PEAR_PHP_BIN=C:\xampp\php\php.exe"



%~dp0php.exe %~dp0pharcommand.phar %*


"%~dp0php.exe" "%~dp0pharcommand.phar" %*

Enjoy new XAMPP with PHP 5.3

Checked by myself in XAMPP 5.6.31, 7.0.15 & 7.1.1 with XAMPP Control Panel v3.2.2

How to clear variables in ipython?

In iPython you can remove a single variable like this:

del x

How to change font size in html?

If you want to do this without adding classes...

p:first-child {
    font-size: 16px;

p:last-child {
    font-size: 12px;


p:nth-child(1) {
    font-size: 16px;

p:nth-child(2) {
    font-size: 12px;

How to install a specific version of Node on Ubuntu?

The Node.js project recently pushed out a new stable version with the 0.10.0 release Use the following command on Ubuntu 13x sudo apt-get install nodejs=0.10.18-1chl1~raring1

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz

$ env | grep zzz

$ export yyy=5

$ set | grep yyy

$ env | grep yyy


other useful threads

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.


.container > :not(marquee){

<div class="container">

intellij idea - Error: java: invalid source release 1.9

I also had the same problem in IntellijIdea, after selecting the project, then File > ProjectStructure > ProjectSettings > Modules -> sources the option was showing - the Language Level set at 9:

So, I Just change it to 8. Still my issue didn't got resolve.

The main issue was with pom.xml. I reimported the pom.xml file and my issue got resolved.

So, whenever you changed the pom.xml file, IDEA needs to update the project structure. For example if you've added there some more dependencies, IDEA needs to add them as project libraries.

In "Settings > Build, Execution, Deployment > Build Tools > Maven > Importing" you can choose "Import Maven projects automatically". This will automatically invoke "Reimport" action when the pom.xml is changed.

enter image description here

Select columns based on string match - dplyr::select

Based on Piotr Migdals response I want to give an alternate solution enabling the possibility for a vector of strings:

myVectorOfStrings <- c("foo", "bar")
matchExpression <- paste(myVectorOfStrings, collapse = "|")
# [1] "foo|bar"
df %>% select(matches(matchExpression))

Making use of the regex OR operator (|)

ATTENTION: If you really have a plain vector of column names (and do not need the power of RegExpression), please see the comment below this answer (since it's the cleaner solution).

ValidateAntiForgeryToken purpose, explanation and example

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.

A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit

It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:

public ActionResult CreateProduct(Product product)  
  if (ModelState.IsValid)  
    //your logic 
  return View(ModelName);

It is derived from System.Web.Mvc namespace.

And in your view, add this code to add the token so it is used to validate the form upon submission.


Programmatically find the number of cores on a machine

hwloc ( is worth looking at. Though requires another library integration into your code but it can provide all the information about your processor (number of cores, the topology, etc.)

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

I think what's missing here is that when you do:

>pip install .

to install a local package with a, it installs a package that is visible to all the conda envs that use the same version of python. Note I am using the conda version of pip!

e.g., if I'm using python2.7 it puts the local package here:


If I then later create a new conda env with python=2.7 (= the default):

>conda create --name new

>source activate new

And then do:

(new)>conda list    // empty - conda is not aware of any packages yet

However, if I do:

(new)>pip list      // the local package installed above is present

So in this case, conda does not know about the pip package, but the package is available to python.

However, If I instead install the local package (again using pip) after I've created (and activated) the new conda env, now conda sees it:

(new)>conda list   // sees that the package is there and was installed by pip

So I think the interaction between conda and pip has some issues - ie, using pip to install a local package from within one conda env makes that package available (but not seen via conda list) to all other conda envs of the same python version.

How to close an iframe within iframe itself

"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.

In IFrame:


In parent:

function closeIFrame(){

Better way to find control in ASP.NET

Action Management On Controls

Create below class in base class. Class To get all controls:

public static class ControlExtensions
    public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
        var result = new List<T>();
        foreach (Control control in parent.Controls)
            if (control is T)
            if (control.HasControls())
        return result;

From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.

In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like

<div id="divAction1" visible="false" runat="server" clientidmode="Static">   
                <a id="anchorAction" runat="server">Submit

IN CS: Use this function on your page:

private void ShowHideActions()

        var controls = Page.GetAllControlsOfType<HtmlGenericControl>();

        foreach (DataRow dr in DTActions.Rows)

            foreach (Control cont in controls)

                if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
                    cont.Visible = true;


How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

Replace words in the body text

To replace a string in your HTML with another use the replace method on innerHTML:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

Note that this will replace the first instance of hello throughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution - for better results, try restricting the scope of your replacement by targeting your code using document.getElementById or similar.

To replace all instances of the target string, use a simple regular expression with the global flag:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

How to customize an end time for a YouTube video?

Today I found, that the old ways are not working very well.

So I used: "Customize YouTube Start and End Time -" from

They provide a link into e.g. Link contain forward to format like this

Fatal error: Namespace declaration statement has to be the very first statement in the script in

You must change the file encoding to ANSI. I was using Notepad++ with encoding UTF-8 and had the same problem. The problem disappeared after I change the file encoding to ANSI!

Get a timestamp in C in microseconds?

You have two choices for getting a microsecond timestamp. The first (and best) choice, is to use the timeval type directly:

struct timeval GetTimeStamp() {
    struct timeval tv;
    return tv;

The second, and for me less desirable, choice is to build a uint64_t out of a timeval:

uint64_t GetTimeStamp() {
    struct timeval tv;
    return tv.tv_sec*(uint64_t)1000000+tv.tv_usec;

How do I load an url in iframe with Jquery

Try $(this).load("/file_name.html");. This method targets a local file.

You can also target remote files (on another domain) take a look at:

Including jars in classpath on commandline (javac or apt)

In windows:

java -cp C:/.../jardir1/*;C:/.../jardir2/* class_with_main_method

make sure that the class with the main function is in one of the included jars