Programs & Examples On #Database independent

Windows 7, 64 bit, DLL problems

This solved the issue for me:

Uninstall the Visual Studio 2010 redistributable package if you have it installed already, and then install Microsoft Windows 7 SDK.

Xcode 6 Storyboard the wrong size?

I had this issue in xcode 6 and there is a way to resolve the resize conflicts. If you select your view, at the bottom you will see an icon that looks like |-Δ-|. If you click on it, you're project will resize for different devices.

Display the current date and time using HTML and Javascript with scrollable effects in hta application

Method 1:

With marquee tag.


<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
      <font color="blue">
        Today's date is : 
         <span id="time"></span>


var today = new Date();

Fiddle demo here

Method 2:

Without marquee tag and with CSS.


<p class="marquee">
    <span id="dtText"></span>


.marquee {
   width: 350px;
   margin: 0 auto;
   white-space: nowrap;
   overflow: hidden;
   box-sizing: border-box;

.marquee span {
   display: inline-block;
   padding-left: 100%;
   text-indent: 0;
   animation: marquee 15s linear infinite;

.marquee span:hover {
    animation-play-state: paused

@keyframes marquee {
    0%   { transform: translate(0, 0); }
    100% { transform: translate(-100%, 0); }


var today = new Date();

Fiddle demo here

How do I implement basic "Long Polling"?

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

Passing an Object from an Activity to a Fragment

To pass an object to a fragment, do the following:

First store the objects in Bundle, don't forget to put implements serializable in class.

            CategoryRowFragment fragment = new CategoryRowFragment();

            // pass arguments to fragment
            Bundle bundle = new Bundle();

            // event list we want to populate
            bundle.putSerializable("eventsList", eventsList);

            // the description of the row
            bundle.putSerializable("categoryRow", categoryRow);


Then retrieve bundles in Fragment

       // events that will be populated in this row_x000D_
        mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");_x000D_
        // description of events to be populated in this row_x000D_
        mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)

Check if a Bash array contains a value

A combination of answers by Beorn Harris and loentar gives one more interesting one-liner test:

delim=$'\x1F' # define a control code to be used as more or less reliable delimiter
if [[ "${delim}${array[@]}${delim}" =~ "${delim}a string to test${delim}" ]]; then
    echo "contains 'a string to test'"

This one does not use extra functions, does not make replacements for testing and adds extra protection against occasional false matches using a control code as a delimiter.

UPD: Thanks to @ChrisCogdon note, this incorrect code was re-written and published as .

Referencing a string in a string array resource with xml

The better option would be to just use the resource returned array as an array, meaning :


This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.

How to avoid precompiled headers

try to add #include "stdafx.h" before #include "iostream"

show distinct column values in pyspark dataframe: python

Run this first


Then run

    SELECT distinct
        column name

How to increase the distance between table columns in HTML?

You can just use padding. Like so:




 td {padding:10px 25px 10px 25px;}


 tr td:first-child {padding-left:0px;}
 td {padding:10px 0px 10px 50px;}

Easiest way to copy a table from one database to another?

Use MySql Workbench's Export and Import functionality. Steps:
1. Select the values you want

E.g. select * from table1; 
  1. Click on the Export button and save it as CSV.
  2. create a new table using similar columns as the first one

    E.g. create table table2 like table1; 
  3. select all from the new table

    E.g. select * from table2;  
  4. Click on Import and select the CSV file you exported in step 2

Sample of the Export and Import buttons in MySql Workbench

How to change working directory in Jupyter Notebook?

Running os.chdir(NEW_PATH) will change the working directory.

import os
In [3]:

In [4]:

In [ ]:

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

$result2 is resource link not a string to echo it or to replace some of its parts with str_replace().

Global variables in Javascript across multiple files

You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.

<script type='text/javascript' > 
  var myFunctionTag = false; 
<script type='text/javascript' src='js/helpers.js'></script>     
<script type='text/javascript' > 
  // rest of your code, which may depend on helpers.js

Using NULL in C++?

I never use NULL in my C or C++ code. 0 works just fine, as does if (ptrname). Any competent C or C++ programmer should know what those do.

Manually Set Value for FormBuilder Control

Tip: If you're using setValue but not providing every property on the form you'll get an error:

Must supply a value for form control with name: 'stateOrProvince'.

So you may be tempted to use patchValue, but this can be dangerous if you're trying to update a whole form. I have an address that may not have stateOrProvince or stateCd depending upon whether it is US or worldwide.

Instead you can update like this - which will use the nulls as defaults:

this.form.setValue( { stateOrProvince: null, stateCd: null, ...address } );

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");


In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

Custom Python list sorting

I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.

l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
l.sort(key = lambda x: (x[0], -x[1]) )

Output will be

[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]

The output will be sorted based on the order of the parameters we provided in the tuple format

How different is Objective-C from C++?

They're completely different. Objective C has more in common with Smalltalk than with C++ (well, except for the syntax, really).

How to launch another aspx web page upon button click?

This button post to the current page while at the same time opens OtherPage.aspx in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.

<asp:Button ID="myBtn" runat="server" Text="Click me" 
     onclick="myBtn_Click" OnClientClick="'OtherPage.aspx', 'OtherPage');" />

Html table tr inside td

Full Example:

<table border="1" style="width:100%;">
    <td>Item 1</td>
    <td>Item 1</td>
      <table border="1" style="width: 100%;">
          <td>Name 1</td>
          <td>Price 1</td>
          <td>Name 2</td>
          <td>Price 2</td>
          <td>Name 3</td>
          <td>Price 3</td>
    <td>Item 1</td>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>

How to fully delete a git repository created with init?

I tried:

rm -rf .git and also

Git keeps all of its files in the .git directory. Just remove that one and init again.

Neither worked for me. Here's what did:

  • Delete all files except for .git
  • git add . -A
  • git commit -m "deleted entire project"
  • git push

Then create / restore the project from backup:

  • Create new project files (or copy paste a backup)
  • git add . -A
  • git commit -m "recreated project"
  • git push

How to create a table from select query result in SQL Server 2008

Please try:

SELECT * INTO NewTable FROM OldTable

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap.

Since you're not informing Jackson of the element type of your ArrayList, it doesn't know that you want to deserialize into an ArrayList of Accounts. So it falls back to the default.

Instead, you could probably use as(JsonNode.class), and then deal with the ObjectMapper in a richer manner than rest-assured allows. Something like this:

ObjectMapper mapper = new ObjectMapper();

JsonNode accounts = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newClub.getOwner().getCustId() + "/clubs")

//Jackson's use of generics here are completely unsafe, but that's another issue
List<Account> accountList = mapper.convertValue(
    new TypeReference<List<Account>>(){}


Remove Unnamed columns in pandas dataframe

The pandas.DataFrame.dropna function removes missing values (e.g. NaN, NaT).

For example the following code would remove any columns from your dataframe, where all of the elements of that column are missing.

df.dropna(how='all', axis='columns')

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

This will help :

 function getTwentyFourHourTime(amPmString) { 
        var d = new Date("1/1/2013 " + amPmString); 
        return d.getHours() + ':' + d.getMinutes(); 

Example :

getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"

Update : Note : There should be a space for timestring between "Time" and "am/pm".

How to remove a variable from a PHP session array

Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:


unset ($ar[2])

Two ways of unsetting values within an array:

# remove by key:
function array_remove_key ()
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
# remove by value:
function array_remove_value ()
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,

echo "<pre>Original Array:\n",

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
echo "<pre>Array after key removal:\n",

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",

So, unset has no effect to internal array counter!!!

How to increase scrollback buffer size in tmux?

The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit session option (the default value is 2000).

To create a pane with a different value you will need to set the appropriate history-limit option before creating the pane.

To establish a different default, you can put a line like the following in your .tmux.conf file:

set-option -g history-limit 3000

Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.

For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit. You might use a command like this (from a shell):

tmux set-option history-limit 5000 \; new-window

For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit before creating the session:

tmux set-option -g history-limit 5000 \; new-session

Note: If you do not re-set the history-limit value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit (though show-option (especially in 1.7 and later) can help with retrieving the current value so that you restore it later).

Validate email address textbox using JavaScript

Assuming your regular expression is correct:

inside your script tags

function validateEmail(emailField){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if (reg.test(emailField.value) == false) 
            alert('Invalid Email Address');
            return false;

        return true;


in your textfield:

<input type="text" onblur="validateEmail(this);" />

HTTP GET Request in Node.js Express

Request and Superagent are pretty good libraries to use.

note: request is deprecated, use at your risk!

Using request:

var request=require('request');

  if(err) //TODO: handle err
  if(res.statusCode === 200 ) //etc
  //TODO Do something with response

How to redirect siteA to siteB with A or CNAME records

You can do this a number of non-DNS ways. The landing page at can have an HTTP redirect. The webserver at can be configured to redirect (easy in Apache, not sure about IIS), etc.

Android: Color To Int conversion

All the methods and variables in Color are static. You can not instantiate a Color object.

Official Color Docs

The Color class defines methods for creating and converting color ints.

Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue.

The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.

Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF

Numpy - Replace a number with NaN


A==NDV will produce a boolean array that can be used as an index for A

Want to show/hide div based on dropdown box selection

you have error in your code unexpected token.use:

  $('#purpose').on('change', function () {
   if (this.value == '1') {
    } else {



Update: You can narrow down the code using .toggle()

 $('#purpose').on('change', function () {
   $("#business").toggle(this.value == '1');

How to annotate MYSQL autoincrement field with JPA annotations

I tried every thing, but still I was unable to do that, I am using mysql, jpa with hibernate, I resolved my issue by assigning value of id 0 in constructor Following is my id declaration code

@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

TypeError: 'int' object is not subscriptable

Just to be clear, all the answers so far are correct, but the reasoning behind them is not explained very well.

The sumall variable is not yet a string. Parentheticals will not convert to a string (e.g. summ = (int(birthday[0])+int(birthday[1])) still returns an integer. It looks like you most likely intended to type str((int(sumall[0])+int(sumall[1]))), but forgot to. The reason the str() function fixes everything is because it converts anything in it compatible to a string.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

The hosting environment comes from the ASPNET_ENV environment variable, which is available during Startup using the IHostingEnvironment.IsEnvironment extension method, or one of the corresponding convenience methods of IsDevelopment or IsProduction. Either save what you need in Startup(), or in ConfigureServices call:

var foo = Environment.GetEnvironmentVariable("ASPNET_ENV");

Best timing method in C?

gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

How can I INSERT data into two tables simultaneously in SQL Server?

Create table #temp1
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)

Create table #temp2
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)

-----main query ------

insert into #temp1(name,profession)

output,inserted.profession into #temp2

select 'Shekhar','IT'

Remove all padding and margin table HTML and CSS

Remove padding between cells inside the table. Just use cellpadding=0 and cellspacing=0 attributes in table tag.

How to run docker-compose up -d at system start up?

I tried restart: always, it works at some containers(like php-fpm), but i faced the problem that some containers(like nginx) is still not restarting after reboot.

Solved the problem.

crontab -e

@reboot (sleep 30s ; cd directory_has_dockercomposeyml ; /usr/local/bin/docker-compose up -d )&

CSS3 animate border color

You can try this also...

button {
  background: none;
  border: 0;
  box-sizing: border-box;
  margin: 1em;
  padding: 1em 2em;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  vertical-align: middle;
  position: relative;
button::before, button::after {
  box-sizing: inherit;
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;

.draw {
  -webkit-transition: color 0.25s;
  transition: color 0.25s;
.draw::before, .draw::after {
  border: 2px solid transparent;
  width: 0;
  height: 0;
.draw::before {
  top: 0;
  left: 0;
.draw::after {
  bottom: 0;
  right: 0;
.draw:hover {
  color: #60daaa;
.draw:hover::before, .draw:hover::after {
  width: 100%;
  height: 100%;
.draw:hover::before {
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  -webkit-transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
  transition: width 0.25s ease-out, height 0.25s ease-out 0.25s;
.draw:hover::after {
  border-bottom-color: #60daaa;
  border-left-color: #60daaa;
  -webkit-transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
  transition: border-color 0s ease-out 0.5s, width 0.25s ease-out 0.5s, height 0.25s ease-out 0.75s;
<section class="buttons">
  <button class="draw">Draw</button>

Execute jQuery function after another function completes

You could also use custom events:

function Typer() {
    // Some stuff


$(anyDomElement).on("myCustomEvent", function() {
    // Some other stuff

How to randomize Excel rows

I usually do as you describe:
Add a separate column with a random value (=RAND()) and then perform a sort on that column.

Might be more complex and prettyer ways (using macros etc), but this is fast enough and simple enough for me.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.

In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also:

Best /Fastest way to read an Excel Sheet into a DataTable?

''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
                                incomingFileName As String) As Boolean
    Dim returnValue As Boolean = False

        Dim sheetName As String = ""
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
        Dim tablesInFile As DataTable
        Dim oleExcelCommand As OleDbCommand
        Dim oleExcelReader As OleDbDataReader
        Dim oleExcelConnection As OleDbConnection

        oleExcelConnection = New OleDbConnection(connectionString)

        tablesInFile = oleExcelConnection.GetSchema("Tables")

        If tablesInFile.Rows.Count > 0 Then
            sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
        End If

        If sheetName <> "" Then

            oleExcelCommand = oleExcelConnection.CreateCommand()
            oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
            oleExcelCommand.CommandType = CommandType.Text

            oleExcelReader = oleExcelCommand.ExecuteReader

            'Determine what row of the Excel file we are on
            Dim currentRowIndex As Integer = 0

            While oleExcelReader.Read
                'If we are on the First Row, then add the item as Columns in the DataTable
                If currentRowIndex = 0 Then
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
                        table.Columns.Add(currentColumnName, GetType(String))
                End If
                'If we are on a Row with Data, add the data to the SheetTable
                If currentRowIndex > 0 Then
                    Dim newRow As DataRow = table.NewRow
                    For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
                        Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
                        newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
                        If IsDBNull(newRow(currentFieldIndex)) Then
                            newRow(currentFieldIndex) = ""
                        End If
                End If

                'Increment the CurrentRowIndex
                currentRowIndex += 1
            End While


        End If

        returnValue = True
    Catch ex As Exception
        'LastError = ex.ToString
        Return False
    End Try

    Return returnValue
End Function

Add row to query result using select

In SQL Server, you would say:

Select name from users

In Oracle, you would say

Select name from user
Select 'JASON' from DUAL

Regex select all text between tags

For multiple lines:


AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.

How do I convert a IPython Notebook into a Python file via commandline?

I had this problem and tried to find the solution online. Though I found some solutions, they still have some problems, e.g., the annoying Untitled.txt auto-creation when you start a new notebook from the dashboard.

So eventually I wrote my own solution:

import io
import os
import re
from nbconvert.exporters.script import ScriptExporter
from notebook.utils import to_api_path

def script_post_save(model, os_path, contents_manager, **kwargs):
    """Save a copy of notebook to the corresponding language source script.

    For example, when you save a `foo.ipynb` file, a corresponding ``
    python script will also be saved in the same directory.

    However, existing config files I found online (including the one written in
    the official documentation), will also create an `Untitile.txt` file when
    you create a new notebook, even if you have not pressed the "save" button.
    This is annoying because we usually will rename the notebook with a more
    meaningful name later, and now we have to rename the generated script file,

    Therefore we make a change here to filter out the newly created notebooks
    by checking their names. For a notebook which has not been given a name,
    i.e., its name is `Untitled.*`, the corresponding source script will not be
    saved. Note that the behavior also applies even if you manually save an
    "Untitled" notebook. The rationale is that we usually do not want to save
    scripts with the useless "Untitled" names.
    # only process for notebooks
    if model["type"] != "notebook":

    script_exporter = ScriptExporter(parent=contents_manager)
    base, __ = os.path.splitext(os_path)

    # do nothing if the notebook name ends with `Untitled[0-9]*`
    regex = re.compile(r"Untitled[0-9]*$")

    script, resources = script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')

    log = contents_manager.log"Saving script at /%s",
             to_api_path(script_fname, contents_manager.root_dir))

    with, "w", encoding="utf-8") as f:

c.FileContentsManager.post_save_hook = script_post_save

To use this script, you can add it to ~/.jupyter/ :)

Note that you may need to restart the jupyter notebook / lab for it to work.

Python conversion from binary string to hexadecimal

>>> import string
>>> s="0000 0100 1000 1101"
>>> ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ]  )


>>> s="0000 0100 1000 1101"
>>> hex(string.atoi(s.replace(" ",""),2))

How to dump a dict to a json file?

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...

"Char cannot be dereferenced" error

A char doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.

The usage would be:

if(Character.isLetter(ch)) { //... }

Run a script in Dockerfile

In addition to the answers above:

If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.


  • If you use Notepad++, you need to click "Edit/EOL Conversion/UNIX (LF)"
  • If you use Visual Studio, I would suggest installing "End Of Line" plugin. Then you can make line endings visible by pressing Ctrl-R, Ctrl-W. And to set Linux style endings you can press Ctrl-R, Ctrl-L. For Windows style, press Ctrl-R, Ctrl-C.

Remove lines that contain certain string

Use python-textops package :

from textops import *

'oldfile.txt' | cat() | grepv('bad') | tofile('newfile.txt')

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Is Secure.ANDROID_ID unique for each device?

So if you want something unique to the device itself, TM.getDeviceId() should be sufficient.

Here is the code which shows how to get Telephony manager ID. The android Device ID that you are using can change on factory settings and also some manufacturers have issue in giving unique id.

TelephonyManager tm = 
        (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String androidId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
Log.d("ID", "Android ID: " + androidId);
Log.d("ID", "Device ID : " + tm.getDeviceId());

Be sure to take permissions for TelephonyManager by using

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

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

  "your message",
  "window title", 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 

private final static attribute vs private final attribute

Final: Once a final variable has been assigned, it always contains the same value. wherever the variable is static or not static: it will be only one variable for all instances initialized one time in Memory

Plot smooth line with PyPlot

See the scipy.interpolate documentation for some examples.

The following example demonstrates its use, for linear and cubic spline interpolation:

>>> from scipy.interpolate import interp1d

>>> x = np.linspace(0, 10, num=11, endpoint=True)
>>> y = np.cos(-x**2/9.0)
>>> f = interp1d(x, y)
>>> f2 = interp1d(x, y, kind='cubic')

>>> xnew = np.linspace(0, 10, num=41, endpoint=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
>>> plt.legend(['data', 'linear', 'cubic'], loc='best')

enter image description here

How do I prevent people from doing XSS in Spring MVC?

**To avoid XSS security threat in spring application**

solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.

    It needs XML entry in the web.xml file & two simple classes.

        java code :-
        The code for the  first class named is :

        package com.filter;

        import javax.servlet.Filter;
        import javax.servlet.FilterChain;
        import javax.servlet.FilterConfig;
        import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.http.HttpServletRequest;
        import org.apache.log4j.Logger;

        public class CrossScriptingFilter implements Filter {
            private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
            private FilterConfig filterConfig;

            public void init(FilterConfig filterConfig) throws ServletException {
                this.filterConfig = filterConfig;

            public void destroy() {
                this.filterConfig = null;

            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
      "Inlter CrossScriptingFilter  ...............");
                chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
      "Outlter CrossScriptingFilter ...............");


The code second class named is :

package com.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;

public final class RequestWrapper extends HttpServletRequestWrapper {
    private static Logger logger = Logger.getLogger(RequestWrapper.class);
    public RequestWrapper(HttpServletRequest servletRequest) {

    public String[] getParameterValues(String parameter) {"InarameterValues .. parameter .......");
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        return encodedValues;

    public String getParameter(String parameter) {"Inarameter .. parameter .......");
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }"Inarameter RequestWrapper ........ value .......");
        return cleanXSS(value);

    public String getHeader(String name) {"Ineader .. parameter .......");
        String value = super.getHeader(name);
        if (value == null)
            return null;"Ineader RequestWrapper ........... value ....");
        return cleanXSS(value);

    private String cleanXSS(String value) {
        // You'll need to remove the spaces from the html entities below"InnXSS RequestWrapper ..............." + value);
        //value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        //value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        //value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
        value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
        value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
        value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
        //value = value.replaceAll("<script>", "");
        //value = value.replaceAll("</script>", "");"OutnXSS RequestWrapper ........ value ......." + value);
        return value;

The only thing remained is the XML entry in the web.xml file:



The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e

Can the Android layout folder contain subfolders?

Now we can easily do with JetBrains plugin called "Android File Grouping"

check out this link

Android File Grouping

enter image description here

What is Scala's yield?

Unless you get a better answer from a Scala user (which I'm not), here's my understanding.

It only appears as part of an expression beginning with for, which states how to generate a new list from an existing list.

Something like:

var doubled = for (n <- original) yield n * 2

So there's one output item for each input (although I believe there's a way of dropping duplicates).

This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.

(If you're familiar with C#, it's closer to LINQ's select operator than it is to yield return).

C++ Get name of type in template

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;

#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X

// etc...

And then use it like

throw ParseError(TypeParseTraits<T>::name);


You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

How to set "value" to input web element using selenium?

driver.findElement("invoice_supplier_id")).setAttribute("value", "your value");

get and set in TypeScript

If you are working with TypeScript modules and are trying to add a getter that is exported, you can do something like this:

// dataStore.ts
export const myData: string = undefined;  // just for typing support
let _myData: string;  // for memoizing the getter results

Object.defineProperty(this, "myData", {
    get: (): string => {
        if (_myData === undefined) {
            _myData = "my data";  // pretend this took a long time

        return _myData;

Then, in another file you have:

import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"

Clearing _POST array fully

It may appear to be overly awkward, but you're probably better off unsetting one element at a time rather than the entire $_POST array. Here's why: If you're using object-oriented programming, you may have one class use $_POST['alpha'] and another class use $_POST['beta'], and if you unset the array after first use, it will void its use in other classes. To be safe and not shoot yourself in the foot, just drop in a little method that will unset the elements that you've just used: For example:

private function doUnset()

Just call the method and unset just those superglobal elements that have been passed to a variable or argument. Then, the other classes that may need a superglobal element can still use them.

However, you are wise to unset the superglobals as soon as they have been passed to an encapsulated object.

Content Security Policy: The page's settings blocked the loading of a resource

I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}


git stash pop stash@{1}

Taking pictures with camera on Android programmatically

Look at following demo code.

Here is your XML file for UI,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Camera" />


And here is your Java class file,

public class CameraDemoActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    public static int count = 0;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)

        // Here, we are making a folder named picFolder to store
        // pics taken by the camera using this application.
        final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        File newdir = new File(dir);

        Button capture = (Button) findViewById(;
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Here, the counter will be incremented each time, and the
                // picture taken by camera will be stored as 1.jpg,2.jpg
                // and likewise.
                String file = dir+count+".jpg";
                File newfile = new File(file);
                try {
                catch (IOException e)

                Uri outputFileUri = Uri.fromFile(newfile);

                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");


Specify the following permissions in your manifest file,

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

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

PowerShell The term is not recognized as cmdlet function script file or operable program

Yet another way this error message can occur...

If PowerShell is open in a directory other than the target file, e.g.:

If someScript.ps1 is located here: C:\SlowLearner\some_missing_path\someScript.ps1, then C:\SlowLearner>. ./someScript.ps1 wont work.

In that case, navigate to the path: cd some_missing_path then this would work:

C:\SlowLearner\some_missing_path>. ./someScript.ps1

How to check if an option is selected?

If you only want to check if an option is selected, then you do not need to iterate through all options. Just do

    // do something
} else {
    // do something else

Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null

How to check undefined in Typescript


Just to add to all the above answers, we can also use the shorthand syntax

var result = uemail || '';

This will give you the email if uemail variable has some value and it will simply return an empty string if uemail variable is undefined.

This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.

Maven Out of Memory Build Failure

Add option



maven-compiler-plugin options


nvarchar(max) still being truncated

Problem seems to be associated with the SET statement. I think the expression can't be more than 4,000 bytes in size. There is no need to make any changes to any settings if all you are trying to do is to assign a dynamically generated statement that is more than 4,000 characters. What you need to do is to split your assignment. If your statement is 6,000 characters long, find a logical break point and then concatenate second half to the same variable. For example:

SET @Query = 'SELECT ....' [Up To 4,000 characters, then rest of statement as below]

SET @Query = @Query + [rest of statement]

Now run your query as normal i.e. EXEC ( @Query )

How to change menu item text dynamically in Android

You better use the override onPrepareOptionsMenu

menu.Clear ();
   if (TabActual == TabSelec.Anuncio)
       menu.Add(10, 11, 0, "Crear anuncio");
       menu.Add(10, 12, 1, "Modificar anuncio");
       menu.Add(10, 13, 2, "Eliminar anuncio");
       menu.Add(10, 14, 3, "Actualizar");
   if (TabActual == TabSelec.Fotos)
       menu.Add(20, 21, 0, "Subir foto");
       menu.Add(20, 22, 1, "Actualizar");
   if (TabActual == TabSelec.Comentarios)
       menu.Add(30, 31, 0, "Actualizar");

Here an example

Using switch statement with a range of value in each case?

It's possible to group several conditions in the same case statement using the mechanism of fall through allowed by switch statements, it's mentioned in the Java tutorial and fully specified in section §14.11. The switch Statement of the Java Language Specification.

The following snippet of code was taken from an example in the tutorial, it calculates the number of days in each month (numbered from month 1 to month 12):

switch (month) {
    case 1: case 3: case 5:
    case 7: case 8: case 10:
    case 12:
        numDays = 31;
    case 4: case 6:
    case 9: case 11:
        numDays = 30;
    case 2:
        if (((year % 4 == 0) && 
             !(year % 100 == 0))
             || (year % 400 == 0))
            numDays = 29;
            numDays = 28;
        System.out.println("Invalid month.");

As you can see, for covering a range of values in a single case statement the only alternative is to list each of the possible values individually, one after the other. As an additional example, here's how to implement the pseudocode in the question:

switch(num) {
    case 1: case 2: case 3: case 4: case 5:
        System.out.println("testing case 1 to 5");
    case 6: case 7: case 8: case 9: case 10:
        System.out.println("testing case 6 to 10");

How do I center an anchor element in CSS?

css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.

XPath query to get nth instance of an element

This is a FAQ:


means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:


Remember: The [] operator has higher precedence (priority) than the // abbreviation.

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)


@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Characters allowed in GET parameter

Alphanumeric characters and all of

~ - _ . ! * ' ( ) ,

are valid within an URL.

All other characters must be encoded.

How do I change a TCP socket to be non-blocking?

On Linux and BSD you can directly create the socket in non-blocking mode (

int fd = socket(res->ai_family, res->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, res->ai_protocol);
if (fd == -1) {
    return -1;

When accepting connections you can use the accept4 function to directly accept new connections in non-blocking mode (

int fd = accept4(lfd, NULL, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
if (fd == -1) {
    return -1;

I don't know why the accepted answer doesn't mention this.

jQuery textbox change event

I have found that this works:

    $('textarea').bind('input propertychange', function() {
        //do your update here


Format a datetime into a string with milliseconds

python -c "from datetime import datetime; print str([:-3]"
2017-02-09 10:06:37.006

How to get selenium to wait for ajax response?

In my case the issue seemed due to ajax delays but was related to internal iframes inside the main page. In seleminum it is possible to switch to internal frames with:


I use java. After that I was able to locate the element


Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

IT happens with me when I rename my project/solution. Go to the folder of project in windows explorer (get out of VS). Find and open the file Global (maybe you'll find 2 files, open that dont have ".asax.cs" extension), and edit the line of error with correct path. Good luck!

What is "Connect Timeout" in sql server connection string?

How a connection works in a nutshell

A connection between a program and a database server relies on a handshake.

What this means is that when a connection is opened then the thread establishing the connection will send network packets to the database server. This thread will then pause until either network packets about this connection are received from the database server or when the connection timeout expires.

The connection timeout

The connection timeout is measured in seconds from the point the connection is opened.

When the timeout expires then the thread will continue, but it will do so having reported a connection failure.

  • If there is no value specified for connection timeout in the connection string then the default value is 30.

  • A value greater than zero means how many seconds before it gives up e.g. a value of 10 means to wait 10 seconds.

  • A value of 0 means to never give up waiting for the connection

Note: A value of 0 is not advised since it is possible for either the connection request packets or the server response packets to get lost. Will you seriously be prepared to wait even a day for a response that may never come?

What should I set my Connection Timeout value to?

This setting should depend on the speed of your network and how long you are prepared to allow a thread to wait for a response.

As an example, on a task that repeats hourly during the day, I know my network has always responded within one second so I set the connection timeout to a value of 2 just to be safe. I will then try again three times before giving up and either raising a support ticket or escalating a similar existing support ticket.

Test your own network speed and consider what to do when a connection fails as a one off, and also when it fails repeatedly and sporadically.

A weighted version of random.choice

A very basic and easy approach for a weighted choice is the following:

np.random.choice(['A', 'B', 'C'], p=[0.3, 0.4, 0.3])

How to order events bound with jQuery

If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.

$('#mydiv').click(function(e) {
    // maniplate #mydiv ...

$('#mydiv').bind('mydiv-manipulated', function(e) {
    // do more stuff now that #mydiv has been manipulated

Something like that at least.

static linking only some libraries

From the manpage of ld (this does not work with gcc), referring to the --static option:

You may use this option multiple times on the command line: it affects library searching for -l options which follow it.

One solution is to put your dynamic dependencies before the --static option on the command line.

Another possibility is to not use --static, but instead provide the full filename/path of the static object file (i.e. not using -l option) for statically linking in of a specific library. Example:

# echo "int main() {}" > test.cpp
# c++ test.cpp /usr/lib/libX11.a
# ldd a.out =>  (0x00007fff385cc000) => /usr/lib/ (0x00007f9a5b233000) => /lib/ (0x00007f9a5afb0000) => /lib/ (0x00007f9a5ad99000) => /lib/ (0x00007f9a5aa46000)
/lib64/ (0x00007f9a5b53f000)

As you can see in the example, libX11 is not in the list of dynamically-linked libraries, as it was linked statically.

Beware: An .so file is always linked dynamically, even when specified with a full filename/path.

How to Implement Custom Table View Section Headers and Footers with Storyboard

  1. Add cell in StoryBoard, and set reuseidentified


  2. Code

    class TP_TaskViewTableViewSectionHeader: UITableViewCell{



  3. Use:

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableCell(withIdentifier: "header", for: IndexPath.init(row: 0, section: section))
        return header

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

go to c->users->[Your user account]-> remove android 1.2 and restart the android studio when it ask to import select first radio button which is import setting from previous config

there you go fixed

How to add,set and get Header in request of HttpClient?

On apache page:

You have something like this:

URIBuilder builder = new URIBuilder();
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri =;
HttpGet httpget = new HttpGet(uri);

How do I enable NuGet Package Restore in Visual Studio?

I had to remove packages folder close and re-open (VS2015) solution. I was not migrating and I did not have packages checked into source control. All I can say is something got messed up and this fixed it.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
Console.WriteLine(list[3]);  // Throws exception.

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

How to get the last day of the month?

In the code below 'get_last_day_of_month(dt)' will give you this, with date in string format like 'YYYY-MM-DD'.

import datetime

def DateTime( d ):
    return datetime.datetime.strptime( d, '%Y-%m-%d').date()

def RelativeDate( start, num_days ):
    d = DateTime( start )
    return str( d + datetime.timedelta( days = num_days ) )

def get_first_day_of_month( dt ):
    return dt[:-2] + '01'

def get_last_day_of_month( dt ):
    fd = get_first_day_of_month( dt )
    fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
    return RelativeDate( fd_next_month, -1 )

How to retrieve value from elements in array using jQuery?


var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)


How do I "commit" changes in a git submodule?

A submodule is its own repo/work-area, with its own .git directory.

So, first commit/push your submodule's changes:

$ cd path/to/submodule
$ git add <stuff>
$ git commit -m "comment"
$ git push

Then, update your main project to track the updated version of the submodule:

$ cd /main/project
$ git add path/to/submodule
$ git commit -m "updated my submodule"
$ git push

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db

How can I get the current user directory?

you can use the following code:

    m_CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
else if(Platform.Equals("Win32NT"))
    m_CurrentPath = Directory.GetCurrentDirectory();

more information see: Get Current Directory Path in both WinXP and WinCE with C#

Check if a string matches a regex in Bash script

In bash version 3 you can use the '=~' operator:

if [[ "$date" =~ ^[0-9]{8}$ ]]; then
    echo "Valid date"
    echo "Invalid date"


NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2

How to check a channel is closed or not without reading it?

Well, you can use default branch to detect it, for a closed channel will be selected, for example: the following code will select default, channel, channel, the first select is not blocked.

func main() {
    ch := make(chan int)

    go func() {
        select {
        case <-ch:
        select {
        case <-ch:
        select {
        case <-ch:
    ch <- 1


2018/05/24 08:00:00 1.default
2018/05/24 08:00:01
2018/05/24 08:00:01

What's the difference between an element and a node in XML?

Different W3C specifications define different sets of "Node" types.

Thus, the DOM spec defines the following types of nodes:

  • Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType
  • DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • DocumentType -- no children
  • EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
  • Attr -- Text, EntityReference
  • ProcessingInstruction -- no children
  • Comment -- no children
  • Text -- no children
  • CDATASection -- no children
  • Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Notation -- no children

The XML Infoset (used by XPath) has a smaller set of nodes:

  • The Document Information Item
  • Element Information Items
  • Attribute Information Items
  • Processing Instruction Information Items
  • Unexpanded Entity Reference Information Items
  • Character Information Items
  • Comment Information Items
  • The Document Type Declaration Information Item
  • Unparsed Entity Information Items
  • Notation Information Items
  • Namespace Information Items
  • XPath has the following Node types:

    • root nodes
    • element nodes
    • text nodes
    • attribute nodes
    • namespace nodes
    • processing instruction nodes
    • comment nodes

    The answer to your question "What is the difference between an element and a node" is:

    An element is a type of node. Many other types of nodes exist and serve different purposes.

    How to navigate back to the last cursor position in Visual Studio Code?

    This will be different for each OS, based on the information at

    Go Back: workbench.action.navigateBack Go Forward: workbench.action.navigateForward

    Linux Go Back: Ctrl+Alt+-
    Go Forward: Ctrl+Shift+-

    OSX ^- / ^?-

    Windows Alt+ ? / ?

    Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

    var regex =/^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,64}$/;
    function test() {
     alert("Min 6,Max 64,At Least One Uppercase Character,One Lowercase Character,One Numeric Value And One Special Character(!@#$%^&*) Required ");
    <input type="text" id="txtPassword" />
    <button id="testBtn" onclick=test()>CheckPassword</button>

    UTF-8 output from PowerShell

    Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

    fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

    I solved the problem by changing the line that generated the output file from:

    out-file -FilePath GITVersion.h -InputObject $result


    out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

    Get variable from PHP to JavaScript

    You can pass PHP Variables to your JavaScript by generating it with PHP:

    $someVar = 1;
    <script type="text/javascript">
        var javaScriptVar = "<?php echo $someVar; ?>";

    How to restart kubernetes nodes?

    If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

    In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

    For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

    Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.

    Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

    To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

    • Reserve some memory for the system.
    • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

    The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

    Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

    I think this problem occurs when you try to access your web driver object after

    1) a window has closed and you haven't yet switched to the parent

    2) you switched to a window that wasn't quite ready and has been updated since you switched

    waiting for the windowhandles.count to be what you're expecting doesn't take into account the page content nor does document.ready. I'm still searching for a solution to this problem

    How to call a JavaScript function within an HTML body

    Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

    WCF ServiceHost access rights

    I am working on Windows Vista. Even i faced the same problem but when i tried to run VS 2008 with administrative privileges, the issue resolved and my service was up and running. :)

    How to zip a whole folder using PHP

    Create a zip folder in PHP.

    Zip create method

       public function zip_creation($source, $destination){
        $dir = opendir($source);
        $result = ($dir === false ? false : true);
        if ($result !== false) {
            $rootPath = realpath($source);
            // Initialize archive object
            $zip = new ZipArchive();
            $zipfilename = $destination.".zip";
            $zip->open($zipfilename, ZipArchive::CREATE | ZipArchive::OVERWRITE );
            // Create recursive directory iterator
            /** @var SplFileInfo[] $files */
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
            foreach ($files as $name => $file)
                // Skip directories (they would be added automatically)
                if (!$file->isDir())
                    // Get real and relative path for current file
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($rootPath) + 1);
                    // Add current file to archive
                    $zip->addFile($filePath, $relativePath);
            // Zip archive will be created only after closing object
            return TRUE;
        } else {
            return FALSE;

    Call the zip method

    $source = $source_directory;
    $destination = $destination_directory;
    $zipcreation = $this->zip_creation($source, $destination);

    python list in sql query as parameter

    Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.

    Here's a variant using a parameterised query that would work for both:

    placeholder= '?' # For SQLite. See DBAPI paramstyle.
    placeholders= ', '.join(placeholder for unused in l)
    query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
    cursor.execute(query, l)

    How do I debug jquery AJAX calls?

    here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:

        $('#ChangePermission').click(function () {
            url: 'change_permission.php',
            type: 'POST',
            data: {
                'user': document.GetElementById("user").value,
                'perm': document.GetElementById("perm").value
            success: function (data) {
            error: function (data) {

    on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.

    require_once(functions . php);
    $result = "true";
    $DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");
    if (isset($_POST["user"]) && isset($_POST["perm"])) {
        $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
        $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
    try {
    } catch (PDOException $e) {
        $result .= $e->getMessage;
    echo json_encode($result);

    Sorting JSON by values

    jQuery isn't particularly helpful for sorting, but here's an elegant and efficient solution. Just write a plain JS function that takes the property name and the order (ascending or descending) and calls the native sort() method with a simple comparison function:

    var people = [
            "f_name": "john",
            "l_name": "doe",
            "sequence": "0",
            "title" : "president",
            "url" : "",
            "color" : "333333",
        // etc
    function sortResults(prop, asc) {
        people.sort(function(a, b) {
            if (asc) {
                return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
            } else {
                return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);


    sortResults('l_name', true);

    Play with a working example here.

    What is the use of the JavaScript 'bind' method?

    Consider the Simple Program listed below,

    //we create object user
    let User = { name: 'Justin' };
    //a Hello Function is created to Alert the object User 
    function Hello() {
    //since there the value of this is lost we need to bind user to use this keyword
    let user = Hello.bind(User);
    //we create an instance to refer the this keyword (;

    Vertical alignment of text and icon in button

    Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

    <button id="edit-listing-form-house_Continue" 
        class="btn btn-large btn-primary"
    <span class="align-middle">Continue</span>
    <i class="icon-ok align-middle" style="font-size:40px;"></i>

    How to convert a Base64 string into a Bitmap image to show it in a ImageView?

    You can just basically revert your code using some other built in methods.

    byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

    BeautifulSoup Grab Visible Webpage Text

    from bs4 import BeautifulSoup
    from bs4.element import Comment
    import urllib.request
    import re
    import ssl
    def tag_visible(element):
        if in ['style', 'script', 'head', 'title', 'meta', '[document]']:
            return False
        if isinstance(element, Comment):
            return False
        if re.match(r"[\n]+",str(element)): return False
        return True
    def text_from_html(url):
        body = urllib.request.urlopen(url,context=ssl._create_unverified_context()).read()
        soup = BeautifulSoup(body ,"lxml")
        texts = soup.findAll(text=True)
        visible_texts = filter(tag_visible, texts)  
        text = u",".join(t.strip() for t in visible_texts)
        text = text.lstrip().rstrip()
        text = text.split(',')
        clean_text = ''
        for sen in text:
            if sen:
                sen = sen.rstrip().lstrip()
                clean_text += sen+','
        return clean_text
    url = ''

    What is the difference between compileSdkVersion and targetSdkVersion?

    The Application settings of an Android project's properties in Visual Studio 2017 (15.8.5) has them combined:

    enter image description here

    What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

    (Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)

    How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.

    For instance, if you don't mind the value being a shallow clone:

    var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                                   entry => entry.Value);

    If you've already constrained T to implement ICloneable:

    var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, 
                                                   entry => (T) entry.Value.Clone());

    (Those are untested, but should work.)

    How can I switch views programmatically in a view controller? (Xcode, iPhone)

    #import "YourViewController.h"

    To push a view including the navigation bar and/or tab bar:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
    YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
    [self.navigationController pushViewController:viewController animated:YES];

    To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

    SQL Server error on update command - "A severe error occurred on the current command"

    I just had the same error, and it was down to a corrupted index. Re-indexing the table fixed the problem.

    How to send post request to the below post method using postman rest client

    I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.

    Setting timezone in Python

    Be aware that running

    import os
    os.system("tzutil /s \"Central Standard Time\"");

    will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

    >>> os.environ['TZ'] = 'Europe/London'
    >>> time.tzset()

    which will only set in the current environment time (in Unix only)

    How to access URL segment(s) in blade in Laravel 5?

    Here is code you can get url segment.

    {{ Request::segment(1) }}

    If you don't want the data to be escaped then use {!! !!} else use {{ }}.

    {!! Request::segment(1) !!}

    How to log PostgreSQL queries?

    FYI: The other solutions will only log statements from the default database—usually postgres—to log others; start with their solution; then:

    ALTER DATABASE your_database_name
    SET log_statement = 'all';

    Ref: / log_statement

    Create an array or List of all dates between two dates

    Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

    How to find a whole word in a String in java

    A much simpler way to do this is to use split():

    String match = "123woods";
    String text = "I will come and meet you at the 123woods";
    String[] sentence = text.split();
    for(String word: sentence)
            return true;
    return false;

    This is a simpler, less elegant way to do the same thing without using tokens, etc.

    maxReceivedMessageSize and maxBufferSize in app.config

    You can do that in your app.config. like that:


    (The max value is Int32.MaxValue )

    Or in Code:

    WSHttpBinding binding = new WSHttpBinding();
    binding.Name = "MyBinding";
    binding.MaxReceivedMessageSize = Int32.MaxValue;


    If your service is open to the Wide world, think about security when you increase this value.

    jquery variable syntax

    The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

    Change SQLite database mode to read-write

    (this error message is typically misleading, and is usually a general permissions error)

    On Windows

    • If you're issuing SQL directly against the database, make sure whatever application you're using to run the SQL is running as administrator
    • If an application is attempting the update, the account that it uses to access the database may need permissions on the folder containing your database file. For example, if IIS is accessing the database, the IUSR and IIS_IUSRS may both need appropriate permissions (you can try this by temporarily giving these accounts full control over the folder, checking if this works, then tying down the permissions as appropriate)

    QtCreator: No valid kits found

    For QT 5.* if you face error at Kits, like No Valid Kits Found, go to Options->Build&Run-> (Kits tab) then you see a Manual category which should list Desktop as the default.

    Just go to your OS Terminal and write sudo apt-get install qt5-default, go back to QT Creator and Start your New Project, and there you see the kit option Desktop included in the list.

    How do I efficiently iterate over each entry in a Java Map?

    It doesn't quite answer the OP's question, but might be useful to others who find this page:

    If you only need the values and not the keys, you can do this:

    Map<Ktype, Vtype> myMap = [...];
    for (Vtype v: myMap.values()) {
      System.out.println("value: " + v);

    Ktype, Vtype are pseudocode.

    C++ - how to find the length of an integer

    Code for finding Length of int and decimal number:

        using namespace std;
        int main()
            int len,num;
            cin >> num;
            len = log10(num) + 1;
            cout << len << endl;
            return 0;
        //sample input output
        Process returned 0 (0x0)   execution time : 3.292 s
        Press any key to continue.

    Running python script inside ipython

    How to run a script in Ipython

    import os

    That should do it

    multiple conditions for filter in spark data frames

    Another way is to use function expr with where clause

    import org.apache.spark.sql.functions.expr
    df2 = df1.where(expr("col1 = 'value1' and col2 = 'value2'"))

    It works the same.

    Initialize Array of Objects using NSArray

    This way you can Create NSArray, NSMutableArray.

    NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
    NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

    How to deal with "data of class uneval" error from ggplot2?

    Another cause is accidentally putting the data=... inside the aes(...) instead of outside:

    ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
    ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)

    In particular this can happen when you prototype your plot command with qplot(), which doesn't use an explicit aes(), then edit/copy-and-paste it into a ggplot()

    qplot(data=..., x=...,y=..., ...)
    ggplot(data=..., aes(x=...,y=...,...))

    It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.

    Serving static web resources in Spring Boot & Spring Security application

    Here is the ultimate solution, after 20+ hours of research.

    Step 1. Add '' to your project.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    public class MvcConfig extends WebMvcConfigurerAdapter {
        public void addResourceHandlers(ResourceHandlerRegistry registry) {

    Step 2. Add configure(WebSecurity web) override to your SecurityConfig class

        public void configure(WebSecurity web) throws Exception {

    Step 3. Place all static resources in webapp/resources/..

    Replace new line/return with space using regex


    L.replaceAll("(\\t|\\r?\\n)+", " ");

    Depending on the system a linefeed is either \r\n or just \n.

    Get input type="file" value when it has multiple files selected

    The files selected are stored in an array: [input].files

    For example, you can access the items

    // assuming there is a file input with the ID `my-input`...
    var files = document.getElementById("my-input").files;
    for (var i = 0; i < files.length; i++)

    For jQuery-comfortable people, it's similarly easy

    // assuming there is a file input with the ID `my-input`...
    var files = $("#my-input")[0].files;
    for (var i = 0; i < files.length; i++)

    When should I use "this" in a class?

    this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.

    edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus

    class POJO {
       protected int i;
       public void modify() {
          i = 9;
       public void thisModify() {
          this.i = 9;

    resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name

      public void m() {
          int i;
          i = 9;  // i refers to variable in method's scope
          this.i = 9; // i refers to class variable

    What's the difference between console.dir and console.log?

    None of the 7 prior answers mentioned that console.dir supports extra arguments: depth, showHidden, and whether to use colors.

    Of particular interest is depth, which (in theory) allows travering objects into more than the default 2 levels that console.log supports.

    I wrote "in theory" because in practice when I had a Mongoose object and ran console.log(mongoose) and console.dir(mongoose, { depth: null }), the output was the same. What actually recursed deeply into the mongoose object was using util.inspect:

    import * as util from 'util';
    console.log(util.inspect(myObject, {showHidden: false, depth: null}));

    Official reasons for "Software caused connection abort: socket write error"

    To prove which component fails I would monitor the TCP/IP communication using wireshark and look who is actaully closing the port, also timeouts could be relevant.

    Delete files older than 15 days using PowerShell

    Esperento57's script doesn't work in older PowerShell versions. This example does:

    Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt  (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue

    Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

    What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

    By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

    You should try changing the value of -Xmx and -Xms.

    How to create tar.gz archive file in Windows?

    tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

    If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

    How to get a substring between two strings in PHP?

    If the strings are different (ie: [foo] & [/foo]), take a look at this post from Justin Cook. I copy his code below:

    function get_string_between($string, $start, $end){
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    $fullstring = 'this is my [tag]dog[/tag]';
    $parsed = get_string_between($fullstring, '[tag]', '[/tag]');
    echo $parsed; // (result = dog)

    Material Design not styling alert dialogs

    You can consider this project:

    It can provide you material theme alert dialogs almost the same as lollipop's. Compatible with Android 2.1.

    Excel telling me my blank cells aren't blank

    Found another way. Set AutoFilter for all columns (important or you will misalign data) by selecting the header row > 'Data' tab > Sort and filter - 'Filter'. Use drop-down in first data column, untick 'Select all' and select only '(Blanks)' option > [OK]. Highlight rows (now all together) > right click > 'Delete row'. Head back to the drop-down > 'Select all'. Presto :)

    Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

    The API can't be loaded after the document has finished loading by default, you'll need to load it asynchronous.

    modify the page with the map:

    <div id="map_canvas" style="height: 354px; width:713px;"></div>
    <script src=""></script>
    <script src=""></script>
    var directionsDisplay,
    function initialize() {
      var directionsService = new google.maps.DirectionsService();
      directionsDisplay = new google.maps.DirectionsRenderer();
      var chicago = new google.maps.LatLng(41.850033, -87.6500523);
      var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
      map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    For more details take a look at:


    Resize HTML5 canvas to fit window

    Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.

    A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:

    #containingDiv { 
      overflow: hidden;
    #myCanvas {
      position: absolute; 
      top: 0px;
      left: 0px;

    The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.

    What do *args and **kwargs mean?

    Notice the cool thing in S.Lott's comment - you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:

    def foo(a, b, c, d):
      print a, b, c, d
    l = [0, 1]
    d = {"d":3, "c":2}
    foo(*l, **d)

    Will print: 0 1 2 3

    What is the most efficient way to create HTML elements using jQuery?

    I am using jquery.min v2.0.3 . It's for me better to use following:

    var select = jQuery("#selecter");
    jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);

    as following:

    var select = jQuery("#selecter");
    jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);

    Processing time of first code is much lower than second code.

    How to SUM two fields within an SQL query

    Try the following:

    SELECT *, (FieldA + FieldB) AS Sum
    FROM Table

    MySQL SELECT statement for the "length" of the field is greater than 1

    Just in case anybody want to find how in oracle and came here (like me), the syntax is

    select length(FIELD) from TABLE

    just in case ;)

    Jquery-How to grey out the background while showing the loading icon over it

    Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.

    If the gif is displayed but not animating, see reference links at very bottom of this answer.

    Displaying the gif + overlay, however, is easier than you might think.

    All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.

    So, when the button is pressed, just unhide those two divs. That's it!

    jsFiddle Demo

    $("#button").click(function() {_x000D_
       $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    /*  Or, remove overlay/image on click background... */_x000D_
     $('#myOverlay, #loadingGIF').fadeOut();_x000D_
    body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
    button{margin:5px 30px;padding:10px 20px;}
    <div id="myOverlay"></div>_x000D_
    <div id="loadingGIF"><img src="" /></div>_x000D_
    <div id="abunchoftext">_x000D_
    Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="" target="_blank">Apologies To Poe</a></div>_x000D_
    <button id="button">Submit</button>_x000D_
    <script src=""></script>


    You might enjoy playing with the new backdrop-filter:blur(_px) css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)


    Animated GIF while loading page does not animate

    Hex-encoded String to Byte Array

    Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.

    The method is DatatypeConverter.parseHexBinary

    In this case it can be used as follows:

    String str = "9B7D2C34A366BF890C730641E6CECF6F";
    byte[] bytes = DatatypeConverter.parseHexBinary(str);

    The class also provides type conversions for many other formats that are generally used in XML.

    Git Commit Messages: 50/72 Formatting

    Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

    For these reasons, the "summary" must be no more than 70-75
    characters, and it must describe both what the patch changes, as well
    as why the patch might be necessary.  It is challenging to be both
    succinct and descriptive, but that is what a well-written summary
    should do.

    That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

    Lengths of Git summary lines (view full-sized)

    There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

    If you want to see the raw lengths:

    cd /path/to/repo
    git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

    or a text-based histogram:

    cd /path/to/repo
    git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

    How to solve static declaration follows non-static declaration in GCC C code?

    I have had this issue in a case where the static function was called before it was declared. Moving the function declaration to anywhere above the call solved my problem.

    LIMIT 10..20 in SQL Server

    as you found, this is the preferred sql server method:

    SELECT * FROM ( 
      SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases 
     ) a WHERE a.row > 5 and a.row <= 10

    Defined Edges With CSS3 Filter Blur

    The simplest way is just adding a transparent border to the div that contains the image and setting its display property to inline-block just like this:


    margin: 2rem;
    height: 100vh;
    overflow: hidden;
    display: inline-block;
    border: 1px solid #00000000;
    img {
    -webkit-filter: blur(2rem);
    filter: blur(2rem);


    <div><img src='' /></div>

    Here's a codepen depicting the same:

    C++ variable has initializer but incomplete type?

    I got a similar error and hit this page while searching the solution.

    With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

    What does an exclamation mark before a cell reference mean?

    When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

    For example, create a named range MyName refering to =SUM(!B1:!K1)

    Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

    Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

    Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

    How to remove leading and trailing white spaces from a given html string?

    I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.

    I have come up with a solution based on your comment for the output you are looking for:

    Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 

    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";_x000D_
    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));

    .trim() removes leading and trailing whitespace

    .replace(/&nbsp;/g, '') removes &nbsp;

    .replace(/<[^\/>][^>]*><\/[^>]+>/g, "")); removes empty tags

    How to get a responsive button in bootstrap 3

    I know this already has a marked answer, but I feel I have an improvement to it.

    The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.

    One thing not mentioned here, is that the words may break in the middle of a word and look messed up.

    My solution, forces the break to happen between words, a nice word wrap.

    .btn-responsive {
        white-space: normal !important;
        word-wrap: break-word;
    <a href="#" class="btn btn-primary btn-responsive">Click Here</a>

    Objective-C ARC: strong vs retain and weak vs assign


    • Property will not Destroy but Only once you set the property to nil will the object get destroyed
    • By default all instance variables and local variables are strong pointers.
    • You use strong only if you need to retain the object.
    • We generally use strong for UIViewControllers (UI item's parents)
    • IOS 4 (non-ARC) We Can Use Retain KeyWord
    • IOS 5(ARC) We Can Use Strong Keyword

    Example: @property (strong, nonatomic) ViewController *viewController;

    @synthesize viewController;


    By Default automatically get and set to nil

    • We generally use weak for IBOutlets (UIViewController's Childs) and delegate
    • the same thing as assign, no retain or release

    Example : @property (weak, nonatomic) IBOutlet UIButton *myButton;

    @synthesize myButton;

    Node.js console.log() not logging anything

    This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

    UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

    How enable auto-format code for Intellij IDEA?

    None of the solutions in Intellij is as elegant (or useful) as in Eclipse. What we need is feature request to the intellij so that we can add a hook (what actions to perform) when the IDE autosaves.

    In Eclipse we can add "post-save" actions, such as organize imports and format the class. Yes you have to do a "save" or ctrl-s but the hook is very convenient.

    How to share my Docker-Image without using the Docker-Hub?


    More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.

    Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.

    Pricing is by amount of data stored, and data transfer costs.

    [Original answer]

    If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:

    which will then run on your own server(s).

    Other hosting suppliers are available, eg CoreOS:

    which bought

    Creating object with dynamic keys

    In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

    The syntax is:

    var obj = {
      [myKey]: value,

    If applied to the OP's scenario, it would turn into:

    stuff = function (thing, callback) {
      var inputs  = $('div.quantity > input').map(function(){
        return {
          [this.attr('name')]: this.attr('value'),
      callback(null, inputs);

    Note: A transpiler is still required for browser compatiblity.

    Using Babel or Google's traceur, it is possible to use this syntax today.

    In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

    To use a "dynamic" key, you have to use bracket notation:

    var obj = {};
    obj[myKey] = value;

    In your case:

    stuff = function (thing, callback) {
      var inputs  = $('div.quantity > input').map(function(){
        var key   = this.attr('name')
         ,  value = this.attr('value')
         ,  ret   = {};
         ret[key] = value;
         return ret;
      callback(null, inputs);

    How to create a String with carriage returns?

    Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.

    Preventing HTML and Script injections in Javascript

    From here

    var string="<script>...</script>";
    string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3

    Postgres DB Size Command

    Based on the answer here by @Hendy Irawan

    Show database sizes:



    => \l+
     berbatik_prd_commerce    | berbatik_prd     | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 19 MB   | pg_default | 
     berbatik_stg_commerce    | berbatik_stg     | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 8633 kB | pg_default | 
     bursasajadah_prd         | bursasajadah_prd | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 1122 MB | pg_default | 

    Show table sizes:



    => \d+
     public | tuneeca_prd | table | tomcat | 8192 bytes | 
     public | tuneeca_stg | table | tomcat | 1464 kB    | 

    Only works in psql.

    The split() method in Java does not work on a dot (.)

    It works fine. Did you read the documentation? The string is converted to a regular expression.

    . is the special character matching all input characters.

    As with any regular expression special character, you escape with a \. You need an additional \ for the Java string escape.

    How to print instances of a class using print()?

    A generic way that can be applied to any class without specific formatting could be done as follows:

    class Element:
        def __init__(self, name, symbol, number):
   = name
            self.symbol = symbol
            self.number = number
        def __str__(self):
            return str(self.__class__) + ": " + str(self.__dict__)

    And then,

    elem = Element('my_name', 'some_symbol', 3)


    __main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}

    How to mock static methods in c# using MOQ framework?

    Another option to transform the static method into a static Func or Action. For instance.

    Original code:

        class Math
            public static int Add(int x, int y)
                return x + y;

    You want to "mock" the Add method, but you can't. Change the above code to this:

            public static Func<int, int, int> Add = (x, y) =>
                return x + y;

    Existing client code doesn't have to change (maybe recompile), but source stays the same.

    Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

        public static void MyTest()
            Math.Add = (x, y) =>
                return 11;

    Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.

    This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

    [edit] I suggest that you add the following Cleanup code to your Unit Test class:

        public void Cleanup()
            typeof(Math).TypeInitializer.Invoke(null, null);

    Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.

    Getting file size in Python?


    Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

    UTF-8 encoding in JSP page

    I also had an issue displaying charectors like "? U".I added the following to my web.xml.


    This solved the issue in the pages except header. Tried many ways to solve this and nothing worked in my case. The issue with header was header jsp page is included from another jsp. So gave the encoding to the import and that solved my problem.

    <c:import url="/Header1.jsp" charEncoding="UTF-8"/>


    SELECT with LIMIT in Codeigniter

    Try this...

    function nationList($limit=null, $start=null) {
        if ($this->session->userdata('language') == "it") {
            $this->db->select(', nation.name_it as name');
        if ($this->session->userdata('language') == "en") {
            $this->db->select(', nation.name_en as name');
        $this->db->order_by("name", "asc");
        if ($limit != '' && $start != '') {
           $this->db->limit($limit, $start);
        $query  = $this->db->get();
        $nation = array();
        foreach ($query->result() as $row) {
            array_push($nation, $row);
        return $nation;     

    How to handle static content in Spring MVC?

    From Spring 3, all the resources needs to mapped in a different way. You need to use the tag to specify the location of the resources.

    Example :

    <mvc:resources mapping="/resources/**" location="/resources/" />

    By doing this way, you are directing the dispatcher servlet to look into the directory resources to look for the static content.

    Field 'browser' doesn't contain a valid alias configuration

    In my case, it is due to a case-sensitivity typo in import path. For example,

    Should be:

    import Dashboard from './Dashboard/dashboard';

    Instead of:

    import Dashboard from './Dashboard/Dashboard';

    WindowsError: [Error 126] The specified module could not be found

    On the off chance anyone else ever runs into this extremely specific issue.. Something inside PyTorch breaks DLL loading. Once you run import torch, any further DLL loads will fail. So if you're using PyTorch and loading your own DLLs you'll have to rearrange your code to import all DLLs first. Confirmed w/ PyTorch 1.5.0 on Python 3.7

    How to test if a file is a directory in a batch script?

    A variation of @batchman61's approach (checking the Directory attribute).

    This time I use an external 'find' command.

    (Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

    SETLOCAL EnableExtensions
    ECHO.%~a1 | find "d" >NUL 2>NUL && (
        ECHO %1 is a directory

    Outputs yes on:

    • Directories.
    • Directory symbolic links or junctions.
    • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
    • Directories which you have no read permission on (e.g. "C:\System Volume Information")

    Print time in a batch file (milliseconds)

    You have to be careful with what you want to do, because it is not just about to get the time.

    The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.


    • dd.MM.yyyy
    • dd.MM.yy
    • d.M.yy
    • dd/MM/yy
    • yyyy-MM-dd


    • H:mm:ss,msec
    • HH:mm:ss,msec

    Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.

    The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.

    I am using the wmic windows builtin utility to request such things (put it in a script file):

    for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE`) do if "%%i" == "LocalDateTime" echo.%%j

    or type it in the cmd.exe console:

    for /F "usebackq tokens=1,2 delims==" %i in (`wmic os get LocalDateTime /VALUE`) do @if "%i" == "LocalDateTime" echo.%j

    The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.

    If you want to continue use this then you can write something like this (get_datetime.bat):

    @echo off
    rem Description:
    rem   Independent to Windows locale date/time request.
    rem Drop last error level
    cd .
    rem drop return value
    set "RETURN_VALUE="
    for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if "%%i" == "LocalDateTime" set "RETURN_VALUE=%%j"
    if not "%RETURN_VALUE%" == "" (
      set "RETURN_VALUE=%RETURN_VALUE:~0,18%"
      exit /b 0
    exit /b 1

    Now, you can parse %RETURN_VALUE% somethere in your script:

    call get_datetime.bat
    set "FILE_SUFFIX=%FILE_SUFFIX:~8,2%_%FILE_SUFFIX:~10,2%_%FILE_SUFFIX:~12,6%"

    How to write a foreach in SQL Server?

    I would say everything probably works except that the column idx doesn't actually exist in the table you're selecting from. Maybe you meant to select from @Practitioner:

    WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

    because that's defined in the code above like that:

    DECLARE @Practitioner TABLE (
        idx smallint Primary Key IDENTITY(1,1)
        , PractitionerId int

    Finding square root without using sqrt function?

    As I found this question is old and have many answers but I have an answer which is simple and working great..

    #define EPSILON 0.0000001 // least minimum value for comparison
    double SquareRoot(double _val) {
        double low = 0; 
        double high = _val;
        double mid = 0; 
        while (high - low > EPSILON) {
                mid = low + (high - low) / 2; // finding mid value
                if (mid*mid > _val) {
                    high = mid;
                } else {
                    low = mid;
        return mid;

    I hope it will be helpful for future users.

    How do I cancel a build that is in progress in Visual Studio?

    Go to the Window menu and choose "Web Publish Activity" There will be a cancel button. Cancel button on "Web Publish Activity" tab

    How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

    This was in response to your other question, that looks like it's been deleted....the point still stands.

    Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.

    .NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).

    My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:

    using System.Text;
    string inputString = GetInput();
    var encoder = ASCIIEncoding.GetEncoder();
    encoder.Fallback = new EncoderReplacementFallback(string.Empty);
    byte[] bAsciiString = encoder.GetBytes(inputString);
    // Do something with bytes...
    // can write to a file as is
    File.WriteAllBytes(FILE_NAME, bAsciiString);
    // or turn back into a "clean" string
    string cleanString = ASCIIEncoding.GetString(bAsciiString); 
    // since the offending bytes have been removed, can use default encoding as well
    Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

    Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

    How do I query between two dates using MySQL?

    Your second date is before your first date (ie. you are querying between September 29 2010 and January 30 2010). Try reversing the order of the dates:

    SELECT *
    FROM `objects`
    WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

    JQuery html() vs. innerHTML

    Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)

    if (/(msie|trident)/i.test(navigator.userAgent)) {
     var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
     var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
     Object.defineProperty(HTMLElement.prototype, "innerHTML", {
      get: function () {return (this)},
      set: function(new_html) {
       var childNodes = this.childNodes
       for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
        this.removeChild (childNodes[0])
       } (this, new_html)
    var mydiv = document.createElement ('div')
    mydiv.innerHTML = "test"
    document.body.appendChild (mydiv)
    document.body.innerHTML = ""
    console.log (mydiv.innerHTML)

    Build tree array from flat array in javascript

    a more simple function list-to-tree-lite

    npm install list-to-tree-lite



    function listToTree(data, options) {
        options = options || {};
        var ID_KEY = options.idKey || 'id';
        var PARENT_KEY = options.parentKey || 'parent';
        var CHILDREN_KEY = options.childrenKey || 'children';
        var tree = [],
            childrenOf = {};
        var item, id, parentId;
        for (var i = 0, length = data.length; i < length; i++) {
            item = data[i];
            id = item[ID_KEY];
            parentId = item[PARENT_KEY] || 0;
            // every item may have children
            childrenOf[id] = childrenOf[id] || [];
            // init its children
            item[CHILDREN_KEY] = childrenOf[id];
            if (parentId != 0) {
                // init its parent's children object
                childrenOf[parentId] = childrenOf[parentId] || [];
                // push it into its parent's children object
            } else {
        return tree;


    convert epoch time to date

    Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date, DateFormat and SimpleDateFormat classes. It all goes more natural with the modern Java date and time API.

    To get a date-time object from your millis:

        ZonedDateTime dateTime = Instant.ofEpochMilli(millis)

    If millis equals 1318388699000L, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.

    If you want the date-time in your string format for presentation:

    String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));


    12/10/2011 14:04:59

    PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59.

    How to get the process ID to kill a nohup process?

    About losing your putty: often the ps ... | awk/grep/perl/... process gets matched, too! So the old school trick is like this

    ps -ef | grep -i [n]ohup 

    That way the regex search doesn't match the regex search process!