Programs & Examples On #Html manipulation

Address already in use: JVM_Bind

My answer does 100% fit to this problem, but I want to document my solution and the trap behind it, since the Exception is the same.

My port was always in use testing a Jetty in a Junit testcase. Problem was Google's code pro on Eclipse, which, I guess, was testing in the background and thus starting jetty before me all the time. Workaround: let Eclipse open *.java files always w/ the Java editor instead of Google's Junit editor. That seems to help.

OrderBy descending in Lambda expression?

Try this another way:

var qry = Employees
          .OrderByDescending (s => s.EmpFName)
          .ThenBy (s => s.Address)
          .Select (s => s.EmpCode);


Round a double to 2 decimal places

For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.

x = Math.floor(x * 100) / 100;

Building and running app via Gradle and Android Studio is slower than via Eclipse

Update After Android Studio 2.3

All answers are great, and I encourage to use those methods with this one to improve build speed.

After release of android 2.2 on September 2016, Android released experimental build cache feature to speed up gradle build performance, which is now official from Android Studio 2.3 Canary. (Official Release note)

It introduces a new build cache feature, which is enable by default, can speed up build times (including full builds, incremental builds, and instant run) by storing and reusing files/directories that were created in previous builds of the same or different Android project.

How to use:

Add following line in your file

android.enableBuildCache = true
# Set to true or false to enable or disable the build cache. If this parameter is not set, the build cache is enable by default.

Clean the cache:

  • There is a new Gradle task called cleanBuildCache for you to more easily clean the build cache. You can use it by typing the following in your terminal:

    ./gradlew cleanBuildCache

  • OR You can clean the cache for Android studio 2.2 by deleting all the files store at location


Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer:

How to run Rake tasks from within Rake tasks?

I would suggest not to create general debug and release tasks if the project is really something that gets compiled and so results in files. You should go with file-tasks which is quite doable in your example, as you state, that your output goes into different directories. Say your project just compiles a test.c file to out/debug/test.out and out/release/test.out with gcc you could setup your project like this:

WAYS = ['debug', 'release']
FLAGS = {}
FLAGS['debug'] = '-g'
FLAGS['release'] = '-O'
def out_dir(way)
  File.join('out', way)
def out_file(way)
  File.join(out_dir(way), 'test.out')
WAYS.each do |way|
  desc "create output directory for #{way}"
  directory out_dir(way)

  desc "build in the #{way}-way"
  file out_file(way) => [out_dir(way), 'test.c'] do |t|
    sh "gcc #{FLAGS[way]} -c test.c -o #{}"
desc 'build all ways'
task :all =>{|way|out_file(way)}

task :default => [:all]

This setup can be used like:

rake all # (builds debug and release)
rake debug # (builds only debug)
rake release # (builds only release)

This does a little more as asked for, but shows my points:

  1. output directories are created, as necessary.
  2. the files are only recompiled if needed (this example is only correct for the simplest of test.c files).
  3. you have all tasks readily at hand if you want to trigger the release build or the debug build.
  4. this example includes a way to also define small differences between debug and release-builds.
  5. no need to reenable a build-task that is parametrized with a global variable, because now the different builds have different tasks. the codereuse of the build-task is done by reusing the code to define the build-tasks. see how the loop does not execute the same task twice, but instead created tasks, that can later be triggered (either by the all-task or be choosing one of them on the rake commandline).

UnsatisfiedDependencyException: Error creating bean with name

If you are using Spring Boot, your main app should be like this (just to make and understand things in simple way) -

package aaa.bbb.ccc;
@ComponentScan({ "aaa.bbb.ccc.*" })
public class Application {

Make sure you have @Repository and @Service appropriately annotated.

Make sure all your packages fall under - aaa.bbb.ccc.*

In most cases this setup resolves these kind of trivial issues. Here is a full blown example. Hope it helps.

How to get local server host and port in Spring Boot?

I used to declare the configuration in like this (you can use you own property file) = localhost
server.port = 8081

and in application you can get it easily by @Value("${}") and @Value("${server.port}") as field level annotation.

or if in your case it is dynamic than you can get from system properties

Here is the example


For a better understanding of this annotation , see this example Multiple uses of @Value annotation

Finding the max/min value in an array of primitives using Java

Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):

public static double getMax(double[] vals){
    final double[] max = {Double.NEGATIVE_INFINITY};

    IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
            .forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);

    return max[0];

(Not completely serious)

Git push/clone to new server

You can push a branch to a remote server, say github. You would first have to do the initial project setup, then clone your project and:

git push <remote repo> <your branch>

How do you set the EditText keyboard to only consist of numbers on Android?

        android:inputType="number" />

I have tried every thing now try this one it shows other characters but you cant enter in the editText


enter image description here

Interpreting "condition has length > 1" warning from `if` function

maybe you want ifelse:

a <- c(1,1,1,1,0,0,0,0,2,2)

 [1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000
 [9] 0.250 0.250

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

Angular2 - Radio Button Binding

Note - radio button binding is now a supported feature in RC4 onwards - see this answer

Radio button example using custom RadioControlValueAccessor similar to CheckboxControlValueAccessor (Updated with Angular 2 rc-1)


import {Component} from "@angular/core";
import {FORM_DIRECTIVES} from "@angular/common";
import {RadioControlValueAccessor} from "./radio_value_accessor";
import {bootstrap} from '@angular/platform-browser-dynamic';

    selector: "my-app",
    templateUrl: "template.html",
    directives: [FORM_DIRECTIVES, RadioControlValueAccessor]
export class App {


    constructor() {
        this.model = {
            sex: "female"


    <form action="">
        <input type="radio" [(ngModel)]=""  name="sex" value="male">Male<br>
        <input type="radio" [(ngModel)]=""  name="sex" value="female">Female

    <input type="button" value="select male" (click)="'male'">
    <input type="button" value="select female" (click)="'female'">
    <div>Selected Radio: {{}}</div>


import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/common';

export const RADIO_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioControlValueAccessor),
    multi: true

   host: {'(change)': 'onChange($', '(blur)': 'onTouched()'},
export class RadioControlValueAccessor implements ControlValueAccessor {
   onChange = (_) => {};
   onTouched = () => {};

   constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}

   writeValue(value: any): void {
       this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value == this._elementRef.nativeElement.value);
   registerOnChange(fn: (_: any) => {}): void { this.onChange = fn; }
   registerOnTouched(fn: () => {}): void { this.onTouched = fn; }

Source :

Plunker live demo :

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I had the same problem, today 2016 - october - 06 I solved with this:

I changed all dependencies that began with 9.?.? to 9.6.1 I compiled with sdk version 24 and target version 17.

There is another packages in my solution because I used more things then only authentication.

After changed your build.gradle (Module:app) with the code below do it:

  1. Put your package NAME in the line with the words applicationId "com.YOUR_PACKAGE_HERE"

  2. Synchronize your project (Ctrl+alt+v) and Build Again.

This is the code of the file buid.gradle (Module:app) that worked for me:

apply plugin: ''

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.YOUR_PACKAGE_HERE"
        minSdkVersion 24
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('', {
        exclude group: '', module: 'support-annotations'

    compile ''
    compile ''

    compile ''
    compile ''

    compile ''
    testCompile 'junit:junit:4.12'

    compile ''

    compile ''

    compile ''

    compile ''

apply plugin: ''

How to set root password to null

If you want an empty password, you should set the password to null and not use the Password hash function, as such:

On the command line:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-networking &
mysql -uroot


use mysql;
update user set password=null where User='root';
flush privileges;

Circle button css

you could always do

html: <div class = "btn"> <a> <button> idk whatever you want to put in the button </button> </a> </div>

and then do

css: .btn a button { border-radius: 50% }

works perfect in my opinion

Importing class/java files in Eclipse

First, you don't need the .class files if they are compiled from your .java classes.

To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.

How do I change the data type for a column in MySQL?

ALTER TABLE tablename MODIFY columnname INTEGER;

This will change the datatype of given column

Depending on how many columns you wish to modify it might be best to generate a script, or use some kind of mysql client GUI

How to convert current date to epoch timestamp?

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

So, you need to do below

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch

Git - deleted some files locally, how do I get them from a remote repository

If you have deleted multiple files locally but not committed, you can force checkout

$ git checkout -f HEAD

How to install latest version of git on CentOS 7.x/6.x

It can be very confusing, and dangerous, to replace the upstream base repositories with add-on repositories without considerable testing and thought. RPMforge, in particularly, is effectively moribund and is not getting updates.

I personally publish tools for building git 2.4, wrapped as an alternatively named "git24" package, at Feel free to access and fork those if you want packages distinguished from the standard system packages, much as "samba" and "samba4" packages are differentiated.

Smooth scroll without the use of jQuery

Try this smooth scrolling demo, or an algorithm like:

  1. Get the current top location using self.pageYOffset
  2. Get the position of element till where you want to scroll to: element.offsetTop
  3. Do a for loop to reach there, which will be quite fast or use a timer to do smooth scroll till that position using window.scrollTo

See also the other popular answer to this question.

Andrew Johnson's original code:

function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;

function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;

function smoothScroll(eID) {
    var startY = currentYPosition();
    var stopY = elmYPosition(eID);
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        scrollTo(0, stopY); return;
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
        for ( var i=startY; i<stopY; i+=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        } return;
    for ( var i=startY; i>stopY; i-=step ) {
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
        leapY -= step; if (leapY < stopY) leapY = stopY; timer++;

Related links:

PHP Warning: PHP Startup: Unable to load dynamic library

If you're on Linux, you can find all loaded configuration files by typing this in shell:

php -r "print phpinfo();" | grep ".ini"

UPDATE: As mentioned in comments, this can be even more accurate:

php -i | grep ini

The right way of setting <a href=""> when it's a local file

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

        <base href="~/" />

Execute PHP scripts within Node.js web server

A simple, fast approach in my opinion would be to use dnode-php for that.

You can see a brief introduction here. Simple, quick and easy!

Instagram API - How can I retrieve the list of people a user is following on Instagram

I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.

You need to use browser console from tab to make it works.

let username = 'USERNAME'
let followers = [], followings = []
try {
  let res = await fetch(`${username}/?__a=1`)

  res = await res.json()
  let userId =

  let after = null, has_next = true
  while (has_next) {
    await fetch(`` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next =
      after =
      followers = followers.concat({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
  console.log('Followers', followers)

  has_next = true
  after = null
  while (has_next) {
    await fetch(`` + encodeURIComponent(JSON.stringify({
      id: userId,
      include_reel: true,
      fetch_mutual: true,
      first: 50,
      after: after
    }))).then(res => res.json()).then(res => {
      has_next =
      after =
      followings = followings.concat({node}) => {
        return {
          username: node.username,
          full_name: node.full_name
  console.log('Followings', followings)
} catch (err) {
  console.log('Invalid username')

A html space is showing as %2520 instead of %20

When you are trying to visit a local filename through firefox browser, you have to force the file:\\\ protocol ( or else firefox will encode your space TWICE. Change the html snippet from this:

<img src="C:\Documents and Settings\screenshots\Image01.png"/>

to this:

<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>

or this:

<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>

Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.

Helpful link:

How can I make a link from a <td> table cell

I would recommend using an actual anchor element, and set it as block.

<div class="divBox">
    <a href="#">Link</a>

    width: 300px;
    height: 100px;
.divBox a
    width: 100%;
    height: 100%;
    display: block;

This will set the anchor to the same dimensions of the parent div.

How to describe table in SQL Server 2008?

Just enter the below line.

exec sp_help [table_name]

Disable Drag and Drop on HTML elements?

try this

$('#id').on('mousedown', function(event){

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] )

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);

  /* close */

  return 0;

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

To get the version of JVM currently running the program


Invisible characters - ASCII

How a character is represented is up to the renderer, but the server may also strip out certain characters before sending the document.

You can also have untitled YouTube videos like by using the Unicode character ZERO WIDTH NON-JOINER (U+200C), or &zwnj; in HTML. The code block below should contain that character:


Razor/CSHTML - Any Benefit over what we have?

  1. Everything is encoded by default!!! This is pretty huge.

  2. Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.

  3. You can make a section required which is nice.

Javascript/Jquery Convert string to array


var trainindIdArray = traingIds.split(',');


var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

how to check confirm password field in form without reloading page

WITHOUT clicking the button you will have to listen to the change event of the input fields

var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");

function checkPasswordMatch(){
    var status = document.getElementById("password_status");
    var submit = document.getElementById("submit");

    status.innerHTML = "";

    if(confirmField.value === "")

    if(passwordField.value === confirmField.value)

    status.innerHTML = "Passwords don't match";
    submit.setAttribute("disabled", "disabled");

passWordField.addEventListener("change", function(event){
confirmField.addEventListener("change", function(event){

then add the status element to your html:

<p id="password_status"></p>

and set the submit button id to submit

... id="submit" />

hope this helps you

How to use KeyListener

Here is an SSCCE,

package experiment;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class KeyListenerTester extends JFrame implements KeyListener {

    JLabel label;

    public KeyListenerTester(String s) {
        JPanel p = new JPanel();
        label = new JLabel("Key Listener!");
        setSize(200, 100);


    public void keyTyped(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key typed");
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key typed");


    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key pressed");
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key pressed");


    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            System.out.println("Right key Released");
        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left key Released");

    public static void main(String[] args) {
        new KeyListenerTester("Key Listener Tester");

Additionally read upon these links : How to Write a Key Listener and How to Use Key Bindings

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

You should be able to fake this by using a custom cell to do your header rows. These will then scroll like any other cell in the table view.

You just need to add some logic in your cellForRowAtIndexPath to return the right cell type when it is a header row.

You'll probably have to manage your sections yourself though, i.e. have everything in one section and fake the headers. (You could also try returning a hidden view for the header view, but I don't know if that will work)

How to set background color of an Activity to white programmatically?

To get the root view defined in your xml file, without action bar, you can use this:

View root = ((ViewGroup) findViewById(;

So, to change color to white:


How to change a css class style through Javascript?

<!DOCTYPE html>
<script src=""></script>
            return "par" ;
.par {
    color: blue;
<div class="test">This is a paragraph.</div>

Appending to an existing string

Yet an other way:

s.insert(-1, ' world')

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da

Maintain image aspect ratio when changing height

I just had the same issue. Use the flex align to center your elements. You need to use align-items: center instead of align-content: center. This will maintain the aspect ratio, while align-content will not keep the aspect ratio.

Android Eclipse - Could not find *.apk

i'm no expert, but eclipse on Windows, doing android apps, refuses to create the file (in the app root directory). I've just copied one from another app and it works fine. Simple contents, for Android 2.2 project it just says (ignoring comments):



Eclipse - Unable to install breakpoint due to missing line number attributes

This fixed my issue:

  1. Window -> preferences -> server -> runtime environments
  2. Apache Tomcat -> edit
  3. Select a JDK instead of JRE

How do I change data-type of pandas data frame to string with a defined format?

I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])

SQL QUERY replace NULL value in a row with a value from the previous known value

Here is the Oracle solution (10g or higher). It uses the analytic function last_value() with the ignore nulls option, which substitutes the last non-null value for the column.

SQL> select *
  2  from mytable
  3  order by id
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         3          5
         6          2

6 rows selected.

SQL> select id
  2         , last_value(somecol ignore nulls) over (order by id) somecol
  3  from mytable
  4  /

        ID    SOMECOL
---------- ----------
         1          3
         2          3
         3          5
         4          5
         5          5
         6          2

6 rows selected.


Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

If using MVC 5 read this solution!

I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace SydHeller.Filters
    public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
        public void OnAuthorization(AuthorizationContext filterContext)
            string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
            if (clientToken == null)
                throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));

            string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
            if (serverToken == null)
                throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));

            System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);

        private const string KEY_NAME = "__RequestVerificationToken";

-- Make note of the using System.Web.Mvc and using System.Web.Mvc.Filters, not the http libraries (I think that is one of the things that changed with MVC v5. --

Then just apply the filter [ValidateJSONAntiForgeryHeader] to your action (or controller) and it should get called correctly.

In my layout page right above </body> I have @AntiForgery.GetHtml();

Finally, in my Razor page, I do the ajax call as follows:

var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();

  type: "POST",
  url: serviceURL,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: requestData,
  headers: {
     "__RequestVerificationToken": formForgeryToken
     success: crimeDataSuccessFunc,
     error: crimeDataErrorFunc

RSA: Get exponent and modulus given a public key

If you need to parse ASN.1 objects in script, there's a library for that:

For doing the math, I found jsbn convenient:

Walking the ASN.1 structure and extracting the exp/mod/subject/etc. is up to you -- I never got that far!

How to create a drop shadow only on one side of an element?

I think this is what you're after?

.shadow {_x000D_
  -webkit-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  -moz-box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
  box-shadow: 0 0 0 4px white, 0 6px 4px black;_x000D_
<div class="shadow">wefwefwef</div>

Pycharm and sys.argv arguments

It works in the edu version for me. It was not necessary for me to specify a -s option in the interpreter options.

Pycharm parameters for running with command line

Nesting optgroups in a dropdownlist/select

I really like the Broken Arrow's solution above in this post. I have just improved/changed it a bit so that what was called labels can be toggled and are not considered options. I have used a small piece of jQuery, but this could be done without jQuery.

I have replaced intermediate labels (no leaf labels) with links, which call a function on click. This function is in charge of toggling the next div of the clicked link, so that it expands/collapses the options. This avoids the possibility of selecting an intermediate element in the hierarchy, which usually is something desired. Making a variant that allows to select intermediate elements should be easy.

This is the modified html:

<div class="NestedSelect">
    <a onclick="toggleDiv(this)">Fruit</a>
            <input type="radio" name="MySelectInputName"><span>Apple</span></label>
            <input type="radio" name="MySelectInputName"><span>Banana</span></label>
            <input type="radio" name="MySelectInputName"><span>Orange</span></label>

    <a onclick="toggleDiv(this)">Drink</a>
            <input type="radio" name="MySelectInputName"><span>Water</span></label>

        <a onclick="toggleDiv(this)">Soft</a>
                <input type="radio" name="MySelectInputName"><span>Cola</span></label>
                <input type="radio" name="MySelectInputName"><span>Soda</span></label>
                <input type="radio" name="MySelectInputName"><span>Lemonade</span></label>

        <a onclick="toggleDiv(this)">Hard</a>
                <input type="radio" name="MySelectInputName"><span>Bear</span></label>
                <input type="radio" name="MySelectInputName"><span>Whisky</span></label>
                <input type="radio" name="MySelectInputName"><span>Vodka</span></label>
                <input type="radio" name="MySelectInputName"><span>Gin</span></label>

A small javascript/jQuery function:

function toggleDiv(element) {

And the css:

.NestedSelect {
    display: inline-block;
    height: 100%;
    border: 1px Black solid;
    overflow-y: scroll;

.NestedSelect a:hover, .NestedSelect span:hover  {
    background-color: #0092ff;
    color: White;
    cursor: pointer;

.NestedSelect input[type="radio"] {
    display: none;

.NestedSelect input[type="radio"] + span {
    display: block;
    padding-left: 0px;
    padding-right: 5px;

.NestedSelect input[type="radio"]:checked + span {
    background-color: Black;
    color: White;

.NestedSelect div {
    display: none;
    margin-left: 15px;
    border-left: 1px black

.NestedSelect label > span:before, .NestedSelect a:before{
    content: '- ';

.NestedSelect a {
    display: block;

Running sample in JSFiddle

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).

In MySQL, a user is identified by both a username ("test2") and a host ("localhost").

The error message identifies the user ("test2") and the host ("localhost") values...


We can check to see if the user exists, using this query from a client we can connect from:

 SELECT user, host FROM mysql.user

We're looking for a row that has "test2" for user, and "localhost" for host.

 user     host       
 -------  -----------
 test2  cleanup
 test2     ::1        
 test2     localhost  

If that row doesn't exist, then the host may be set to wildcard value of %, to match any other host that isn't a match.

If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root

 SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')

We can also verify that the user has privileges on objects in the database.

 GRANT SELECT ON jobs.* TO 'test2'@'localhost' 


If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES statement, executed by a privileged user.

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.

Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with user IDs plus entities for the term "blue angels":


jQuery or JavaScript auto click


Suppose this would work too.

Delete element in a slice

Where a is the slice, and i is the index of the element you want to delete:

a = append(a[:i], a[i+1:]...)

... is syntax for variadic arguments in Go.

Basically, when defining a function it puts all the arguments that you pass into one slice of that type. By doing that, you can pass as many arguments as you want (for example, fmt.Println can take as many arguments as you want).

Now, when calling a function, ... does the opposite: it unpacks a slice and passes them as separate arguments to a variadic function.

So what this line does:

a = append(a[:0], a[1:]...)

is essentially:

a = append(a[:0], a[1], a[2])

Now, you may be wondering, why not just do

a = append(a[1:]...)

Well, the function definition of append is

func append(slice []Type, elems ...Type) []Type

So the first argument has to be a slice of the correct type, the second argument is the variadic, so we pass in an empty slice, and then unpack the rest of the slice to fill in the arguments.

How to change the integrated terminal in visual studio code or VSCode

For OP's terminal Cmder there is an integration guide, also hinted in the VS Code docs.

If you want to use VS Code tasks and encounter problems after switch to Cmder, there is an update to @khernand's answer. Copy this into your settings.json file:

"": "cmd.exe",

"": {
  "CMDER_ROOT": "[cmder_root]" // replace [cmder_root] with your cmder path
"": [
  "%CMDER_ROOT%\\vendor\\bin\\vscode_init.cmd" // <-- this is the relevant change
  // OLD: "%CMDER_ROOT%\\vendor\\init.bat"

The invoked file will open Cmder as integrated terminal and switch to cmd for tasks - have a look at the source here. So you can omit configuring a separate terminal in tasks.json to make tasks work.

Starting with VS Code 1.38, there is also "" setting, which lets you set your terminal for tasks globally and avoids issues with Cmder.

"": "cmd.exe"

Changing SqlConnection timeout

A cleaner way is to set connectionString in xml file, for example Web.Confing(WepApplication) or App.Config(StandAloneApplication).

    <remove name="myConn"/>
    <add name="myConn" connectionString="User ID=sa;Password=XXXXX;Initial Catalog=qualitaBorri;Data Source=PC_NAME\SQLEXPRESS;Connection Timeout=60"/>

By code you can get connection in this way:

public static SqlConnection getConnection()
        string conn = string.Empty;
        conn = System.Configuration.ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
        SqlConnection aConnection = new SqlConnection(conn);
        return aConnection;

You can set ConnectionTimeout only you create a instance. When instance is create you don't change this value.

Pipe to/from the clipboard in Bash script

I have found a good reference:

In my case I would like to paste content on the clipboard and also to see what is been pasted there, so I used also the tee command with a file descriptor:

echo "just a test" | tee >(xclip -i -selection clipboard)

>() is a form of process substitution. bash replaces each with the path to a file descriptor which is connected to the standard input of the program within the parentheses.

The teecommand forks your command allowing you to "pipe its content" and see the result on standard output "stdout"

you can also create aliases to get and write on the clipboard, allowing you to use "pbcopy" and "pbpaste" as if you where on MAC. In my case, as I use zsh I have this on my aliases file:

(( $+commands[xclip] )) && {
    alias pbpaste='xclip -i -selection clipboard -o'
    alias pbcopy='xclip -selection clipboard'

the (( $+command[name] )) in zsh tests if the command "name" is installed on your system, then both aliases are grouped with {}. the && is a binary AND, if a then b, hence if you have xclip then the aliases will be set.

echo "another test" | tee >(pbcopy)

To get your clipboard content just type:

pbpaste | "any-command-you-need-here"

Database development mistakes made by application developers

Not paying enough attention towards managing database connections in your application. Then you find out the application, the computer, the server, and the network is clogged.

Program to find prime numbers

It may just be my opinion, but there's another serious error in your program (setting aside the given 'prime number' question, which has been thoroughly answered).

Like the rest of the responders, I'm assuming this is homework, which indicates you want to become a developer (presumably).

You need to learn to compartmentalize your code. It's not something you'll always need to do in a project, but it's good to know how to do it.

Your method prime_num(long num) could stand a better, more descriptive name. And if it is supposed to find all prime numbers less than a given number, it should return them as a list. This makes it easier to seperate your display and your functionality.

If it simply returned an IList containing prime numbers you could then display them in your main function (perhaps calling another outside function to pretty print them) or use them in further calculations down the line.

So my best recommendation to you is to do something like this:

public void main(string args[])
    //Get the number you want to use as input
    long x = number;//'number' can be hard coded or retrieved from ReadLine() or from the given arguments

    IList<long> primes = FindSmallerPrimes(number);


public IList<long> FindSmallerPrimes(long largestNumber)
    List<long> returnList = new List<long>();
    //Find the primes, using a method as described by another answer, add them to returnList
    return returnList;

public void DisplayPrimes(IList<long> primes)
    foreach(long l in primes)
        Console.WriteLine ( "Prime:" + l.ToString() );

Even if you end up working somewhere where speration like this isn't needed, it's good to know how to do it.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)


You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality


is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  

How to make a stable two column layout in HTML/CSS

Here you go:

    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    .clear {_x000D_
      clear: both;_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    <div class="clear"></div>_x000D_

See it in action here:

HTML5 live streaming

Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want. All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config. Example with nginx-rtmp-module:

rtmp {
    server {
        listen 1935; # Listen on standard RTMP port
        chunk_size 4000;

        application show {
            live on;
            # Turn on HLS
            hls on;
            hls_path /mnt/hls/;
            hls_fragment 3;
            hls_playlist_length 60;
            # disable consuming the stream from nginx as rtmp
            deny play all;

server {
    listen 8080;

    location /hls {
        # Disable cache
        add_header Cache-Control no-cache;

        # CORS setup
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        add_header 'Access-Control-Allow-Headers' 'Range';

        # allow CORS preflight requests
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Headers' 'Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;

        types {
            application/ m3u8;
            video/mp2t ts;

        root /mnt/;

After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.

In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Live Streaming</title>
    <link href="//" rel="stylesheet">
    <script src="//"></script>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
    <source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
    var player = videojs('#player');

You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.

Return multiple fields as a record in PostgreSQL with PL/pgSQL

You need to define a new type and define your function to return that type.

CREATE TYPE my_type AS (f1 varchar(10), f2 varchar(10) /* , ... */ );

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
RETURNS my_type 

  result_record my_type;

  SELECT f1, f2, f3
  INTO result_record.f1, result_record.f2, result_record.f3
  FROM table1
  WHERE pk_col = 42;

  SELECT f3 
  INTO result_record.f3
  FROM table2
  WHERE pk_col = 24;

  RETURN result_record;

$$ LANGUAGE plpgsql; 

If you want to return more than one record you need to define the function as returns setof my_type


Another option is to use RETURNS TABLE() instead of creating a TYPE which was introduced in Postgres 8.4

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
  RETURNS TABLE (f1 varchar(10), f2 varchar(10) /* , ... */ )

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  return bytes;
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  link.href = data; = `${fileName}.pdf`;;

Set NOW() as Default Value for datetime datatype?

CREATE TABLE `users` (
  `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mobile_UNIQUE` (`mobile`)

How do you count the lines of code in a Visual Studio solution?

For future readers I'd like to advise the DPack extension for Visual Studio 2010.

It's got a load of utilities built in including a line counter which says how many lines are blank, code, and etc.

escaping question mark in regex javascript

You should use double slash:

var regex = new RegExp("\\?", "g");

Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"

And "\\?", becomes "\?"

Regex date format validation on Java

If you want a simple regex then it won't be accurate. offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.

ISO date format (yyyy-mm-dd):


ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.

^[0-9]{4}([- /.])(((0[13578]|(10|12))\1(0[1-9]|[1-2][0-9]|3[0-1]))|(02\1(0[1-9]|[1-2][0-9]))|((0[469]|11)\1(0[1-9]|[1-2][0-9]|30)))$

United States date format (mm/dd/yyyy)


Hours and minutes, 24 hours format (HH:MM):


Good luck

How to make a JFrame Modal in Swing java

As far as I know, JFrame cannot do Modal mode. Use JDialog instead and call setModalityType(Dialog.ModalityType type) to set it to be modal (or not modal).

Why doesn't JUnit provide assertNotEquals methods?

I'd argue that the absence of assertNotEqual is indeed an asymmetry and makes JUnit a bit less learnable. Mind that this is a neat case when adding a method would diminish the complexity of the API, at least for me: Symmetry helps ruling the bigger space. My guess is that the reason for the omission may be that there are too few people calling for the method. Yet, I remember a time when even assertFalse did not exist; hence, I have a positive expectation that the method might eventually be added, given that it is not a difficult one; even though I acknowledge that there are numerous workarounds, even elegant ones.

Is Secure.ANDROID_ID unique for each device?

Check into this thread,. However you should be careful as it's documented as "can change upon factory reset". Use at your own risk, and it can be easily changed on a rooted phone. Also it appears as if some manufacturers have had issues with their phones having duplicate numbers thread. Depending on what your trying to do, I probably wouldnt use this as a UID.

Extract the first word of a string in a SQL Server query

I wanted to do something like this without making a separate function, and came up with this simple one-line approach:

SET @test = 'First Second'

SELECT SUBSTRING(@test,1,(CHARINDEX(' ',@test + ' ')-1))

This would return the result "First"

It's short, just not as robust, as it assumes your string doesn't start with a space. It will handle one-word inputs, multi-word inputs, and empty string or NULL inputs.

How can I tell when a MySQL table was last updated?

For a list of recent table changes use this:

FROM information_schema.tables

Sending GET request with Authentication headers using restTemplate

These days something like the following will suffice:

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken); URI(url)).headers(headers).build(), returnType);

How to draw an overlay on a SurfaceView used by Camera on Android?

Try calling setWillNotDraw(false) from surfaceCreated:

public void surfaceCreated(SurfaceHolder holder) {
    try {
    } catch (Exception e) {
        Log.d(TAG,"Surface not created");

protected void onDraw(Canvas canvas) {

    canvas.drawRect(area, rectanglePaint);
    Log.w(this.getClass().getName(), "On Draw Called");

and calling invalidate from onTouchEvent:

public boolean onTouch(View v, MotionEvent event) {

    return true;

How to remove trailing whitespaces with sed?

It is best to also quote $1:

sed -i.bak 's/[[:blank:]]*$//' "$1"

Current time in microseconds in java

Use Instant to compute microseconds since Epoch:

val instant =;
val currentTimeMicros = instant.getEpochSecond() * 1000_000 + instant.getNano() / 1000;

How to list npm user-installed packages?

As a shorthand, you can run:

npm ls -g --depth=0

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

except (KeyboardInterrupt, EOFError): # the parens are necessary

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here:

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

except (KeyboardInterrupt, EOFError) as err: 

Note that in Python 3, the err object falls out of scope when the except block is concluded.


You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

except (IDontLikeYouException, YouAreBeingMeanException) as e:

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):

So when you want to pass on certain exceptions, use suppress.

How to center a checkbox in a table cell?

Pull out ALL of your in-line CSS, and move it to the head. Then use classes on the cells so you can adjust everything as you like (don't use a name like "center" - you may change it to left 6 months from now...). The alignment answer is still the same - apply it to the <td> NOT the checkbox (that would just center your check :-) )

Using you code...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Alignment test</title>
table { margin:10px auto; border-collapse:collapse; border:1px solid gray; }
td,th { border:1px solid gray; text-align:left; padding:20px; }
td.opt1 { text-align:center; vertical-align:middle; }
td.opt2 { text-align:right; }


        <th>Search?</th><th>Field</th><th colspan="2">Search criteria</th><th>Include in report?<br></th>
        <td class="opt1"><input type="checkbox" name="query_myTextEditBox"></td>
           <select size ="1" name="myTextEditBox_compare_operator">
            <option value="=">equals</option>
            <option value="<>">does not equal</option>
        <td><input type="text" name="myTextEditBox_compare_value"></td>
        <td class="opt2">
          <input type="checkbox" name="report_myTextEditBox" value="checked">

Importing a csv into mysql via command line

You can simply import by

mysqlimport --ignore-lines=1 --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local -uroot -proot db_name csv_import.csv

Note: Csv File name and Table name should be same

Where is HttpContent.ReadAsAsync?

Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

Get specific line from text file using just shell script

I didn't particularly like any of the answers.

Here is how I did it.

# Convert the file into an array of strings
lines=(`cat "foo.txt"`)

# Print out the lines via array index
echo "${lines[0]}"
echo "${lines[1]}"
echo "${lines[5]}"

How to get the full path of running process?

By combining Sanjeevakumar Hiremath's and Jeff Mercado's answers you can actually in a way get around the problem when retrieving the icon from a 64-bit process in a 32-bit process.

using System;
using System.Management;
using System.Diagnostics;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            int processID = 6680;   // Change for the process you would like to use
            Process process = Process.GetProcessById(processID);
            string path = ProcessExecutablePath(process);

        static private string ProcessExecutablePath(Process process)
                return process.MainModule.FileName;
                string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

                foreach (ManagementObject item in searcher.Get())
                    object id = item["ProcessID"];
                    object path = item["ExecutablePath"];

                    if (path != null && id.ToString() == process.Id.ToString())
                        return path.ToString();

            return "";

This may be a bit slow and doesn't work on every process which lacks a "valid" icon.

What happens if you don't commit a transaction to a database (say, SQL Server)?

The behaviour is not defined, so you must explicit set a commit or a rollback:

"If auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is executed."

Hsqldb makes a rollback

stmt.executeUpdate("insert into USER values ('" +  insertedUserId + "','Anton','Alaf')");

result is

2011-11-14 14:20:22,519 main INFO [SqlAutoCommitExample:55] [AutoCommit enabled = false] 2011-11-14 14:20:22,546 main INFO [SqlAutoCommitExample:65] [Found 0# users in database]

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

How to generate different random numbers in a loop in C++?

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

    srand (time(NULL));
    (int t=0;t<10;t++)
    cout << rand() % 100 << endl;

How do I replicate a \t tab space in HTML?

This simple formula should work. Give the element whose text will contain a tab the following CSS property: white-space:pre. Otherwise your html may not render tabs at all. Then, wherever you want to have a tab in your text, type &#9;.

Since you didn't mention CSS, if you want to do this without a CSS file, just use

<tag-name style="white-space:pre">text in element&#9;more text</tag-name>

in your HTML.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Commenting here as this seems to be the most popular answer on the subject for searching for files whilst excluding certain directories in powershell.

To avoid issues with post filtering of results (i.e. avoiding permission issues etc), I only needed to filter out top level directories and that is all this example is based on, so whilst this example doesn't filter child directory names, it could very easily be made recursive to support this, if you were so inclined.

Quick breakdown of how the snippet works

$folders << Uses Get-Childitem to query the file system and perform folder exclusion

$file << The pattern of the file I am looking for

foreach << Iterates the $folders variable performing a recursive search using the Get-Childitem command

$folders = Get-ChildItem -Path C:\ -Directory -Name -Exclude Folder1,"Folder 2"
$file = "*filenametosearchfor*.extension"

foreach ($folder in $folders) {
   Get-Childitem -Path "C:/$folder" -Recurse -Filter $file | ForEach-Object { Write-Output $_.FullName }

How do I convert a Python 3 byte-string variable into a regular string?

Call decode() on a bytes instance to get the text which it encodes.

str = bytes.decode()

javac option to compile all java files under a given directory recursively

I'm just using make with a simple makefile that looks like this:

JAVAC = javac -Xlint:unchecked
sources = $(shell find . -type f -name '*.java')
classes = $(

all : $(classes)

clean :
        rm -f $(classes)

%.class :
        $(JAVAC) $<

It compiles the sources one at a time and only recompiles if necessary.

How to use placeholder as default value in select2 framework

   placeholder: "Select a State",
   allowClear: true
   placeholder: "Select a State"

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

React onClick function fires on render

Instead of calling the function, bind the value to the function:

this.props.removeTaskFunction.bind(this, todo)

MDN ref:

How to Apply Mask to Image in OpenCV?

You can use the mask to copy only the region of interest of an original image to a destination one:


where mask should be an 8-bit single channel array.

See more at the OpenCV docs

How to convert hex strings to byte values in Java

Here, if you are converting string into byte[].There is a utility code :

    String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
    byte[] dataCopy = new byte[str.length] ;
    int i=0;
    for(String s:str ) {
    return dataCopy;

Clearing _POST array fully

Yes, that is fine. $_POST is just another variable, except it has (super)global scope.

$_POST = array();

...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.

how to write javascript code inside php

Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.

$script = <<< JS

$(function() {
   // js code goes here


After closing the heredoc construction the $script variable contains your JS code that can be used like this:

<script><?= $script ?></script>

The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.

How to display the first few characters of a string in Python?

Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum


>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
>>> sha1sum
>>> sha5sum

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.


Read XML file using javascript

You can do something like this to read your nodes.

Also you can find some explanation in this page

<script type="text/javascript">
        var markers = null;
        $(document).ready(function () {
            $.get("File.xml", {}, function (xml){
                 markers = $(this);

RE error: illegal byte sequence on Mac OS X

My workaround had been using gnu sed. Worked fine for my purposes.

How to manually set an authenticated user in Spring Security / SpringMVC

I couldn't find any other full solutions so I thought I would post mine. This may be a bit of a hack, but it resolved the issue to the above problem:

public void login(HttpServletRequest request, String userName, String password)

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);

    // Authenticate the user
    Authentication authentication = authenticationManager.authenticate(authRequest);
    SecurityContext securityContext = SecurityContextHolder.getContext();

    // Create a new session and add the security context.
    HttpSession session = request.getSession(true);
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

How does the Python's range function work?

range(x) returns a list of numbers from 0 to x - 1.

>>> range(1)
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range(). i is used inside the body to refer to the “current” item of the list. In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.

Java/Groovy - simple date reformatting

With Groovy, you don't need the includes, and can just do:

String oldDate = '04-DEC-2012'
Date date = Date.parse( 'dd-MMM-yyyy', oldDate )
String newDate = date.format( 'M-d-yyyy' )

println newDate

To print:


Query to get all rows from previous month

SELECT *  FROM table  

Java ArrayList of Doubles

Try this,

ArrayList<Double> numb= new ArrayList<Double>(Arrays.asList(1.38, 2.56, 4.3));

Access XAMPP Localhost from Internet

First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here

For example, let's say you picked the IP address After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and, since your computer will now always have that IP address on your network.

If you look up your IP address (such as, the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.

Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).

For the Linksys router I have, I enter, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.

Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering (the same one you see when you go here ).

As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as and your friend can then always access your website by simply going to in his browser. Here is their site again: DynDns

I hope this helps.

Algorithm to detect overlapping periods

You can create a reusable Range pattern class :

public class Range<T> where T : IComparable
    readonly T min;
    readonly T max;

    public Range(T min, T max)
        this.min = min;
        this.max = max;

    public bool IsOverlapped(Range<T> other)
        return Min.CompareTo(other.Max) < 0 && other.Min.CompareTo(Max) < 0;

    public T Min { get { return min; } }
    public T Max { get { return max; } }

You can add all methods you need to merge ranges, get intersections and so on...

Mobile Redirect using htaccess

Similarly, if you wanted to redirect to a sub-folder instead of a sub-domain, do the following:

Working off of Kevin's great solution you can add this to the .htaccess file in your site's root directory:

    <IfModule mod_rewrite.c>
        RewriteBase /
        RewriteEngine On

        # Check if mobile=1 is set and set cookie 'mobile' equal to 1
        RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
        RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

        # Check if mobile=0 is set and set cookie 'mobile' equal to 0
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

        # cookie can't be set and read in the same request so check
        RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
        RewriteRule ^ - [S=1]

        # Check if this looks like a mobile device
        RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
        RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
        RewriteCond %{HTTP:Profile}       !^$

        # Check if we're not already on the mobile site
        RewriteCond %{HTTP_HOST}          !^m\.
        # Check to make sure we haven't set the cookie before
        RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
        # Now redirect to the mobile site
        RewriteRule ^ [R]

Then, in the /m/ folder, add or create an .htaccess with the following:

    #Begin user agent loop fix

         RewriteEngine Off
         RewriteBase /

    #End user agent loop fix 

I know it's not a direct answer to the question, but somebody (like me) might stumble upon this question and wonder how that method would be accomplished as well.

How to do a less than or equal to filter in Django queryset?

Less than or equal:


Greater than or equal:


Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Python method for reading keypress?

It's really late now but I made a quick script which works for Windows, Mac and Linux, simply by using each command line:

import os, platform

def close():
    if platform.system() == "Windows":
        print("Press any key to exit . . .")
    elif platform.system() == "Linux":
        os.system("read -n1 -r -p \"Press any key to exit . . .\" key")
    elif platform.system() == "Darwin":
        print("Press any key to exit . . .")
        os.system("read -n 1 -s -p \"\"")

It uses only inbuilt functions, and should work for all three (although I've only tested Windows and Linux...).

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

Most efficient T-SQL way to pad a varchar on the left to a certain length?

In SQL Server 2005 and later you could create a CLR function to do this.

Adding new line of data to TextBox

I find this method saves a lot of typing, and prevents a lot of typos.

string nl = "\r\n";

txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";

How to fix Git error: object file is empty?

I had a similar problem. My laptop ran out of battery during a git operation. Boo.

I didn't have any backups. (N.B. Ubuntu One is not a backup solution for git; it will helpfully overwrite your sane repository with your corrupted one.)

To the git wizards, if this was a bad way to fix it, please leave a comment. It did, however, work for me... at least temporarily.

Step 1: Make a backup of .git (in fact I do this in between every step that changes something, but with a new copy-to name, e.g. .git-old-1, .git-old-2, etc.):

cp -a .git .git-old

Step 2: Run git fsck --full

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
error: object file .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e is empty
fatal: loose object 8b61d0135d3195966b443f6c73fb68466264c68e (stored in .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e) is corrupt

Step 3: Remove the empty file. I figured what the heck; its blank anyway.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e 
rm: remove write-protected regular empty file `.git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e'? y

Step 3: Run git fsck again. Continue deleting the empty files. You can also cd into the .git directory and run find . -type f -empty -delete -print to remove all empty files. Eventually git started telling me it was actually doing something with the object directories:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: object file .git/objects/e0/cbccee33aea970f4887194047141f79a363636 is empty
fatal: loose object e0cbccee33aea970f4887194047141f79a363636 (stored in .git/objects/e0/cbccee33aea970f4887194047141f79a363636) is corrupt

Step 4: After deleting all of the empty files, I eventually came to git fsck actually running:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: HEAD: invalid sha1 pointer af9fc0c5939eee40f6be2ed66381d74ec2be895f
error: refs/heads/master does not point to a valid object!
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 5: Try git reflog. Fail because my HEAD is broken.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reflog
fatal: bad object HEAD

Step 6: Google. Find this. Manually get the last two lines of the reflog:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ tail -n 2 .git/logs/refs/heads/master
f2d4c4868ec7719317a8fce9dc18c4f2e00ede04 9f0abf890b113a287e10d56b66dbab66adc1662d Nathan VanHoudnos <[email protected]> 1347306977 -0400  commit: up to p. 24, including correcting spelling of my name
9f0abf890b113a287e10d56b66dbab66adc1662d af9fc0c5939eee40f6be2ed66381d74ec2be895f Nathan VanHoudnos <[email protected]> 1347358589 -0400  commit: fixed up to page 28

Step 7: Note that from Step 6 we learned that the HEAD is currently pointing to the very last commit. So let's try to just look at the parent commit:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git show 9f0abf890b113a287e10d56b66dbab66adc1662d
commit 9f0abf890b113a287e10d56b66dbab66adc1662d
Author: Nathan VanHoudnos <nathanvan@XXXXXX>
Date:   Mon Sep 10 15:56:17 2012 -0400

    up to p. 24, including correcting spelling of my name

diff --git a/tex/MCMC-in-IRT.tex b/tex/MCMC-in-IRT.tex
index 86e67a1..b860686 100644
--- a/tex/MCMC-in-IRT.tex
+++ b/tex/MCMC-in-IRT.tex

It worked!

Step 8: So now we need to point HEAD to 9f0abf890b113a287e10d56b66dbab66adc1662d.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git update-ref HEAD 9f0abf890b113a287e10d56b66dbab66adc1662d

Which didn't complain.

Step 9: See what fsck says:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229

Step 10: The invalid sha1 pointer in cache-tree seemed like it was from a (now outdated) index file (source). So I killed it and reset the repo.

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/index
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reset
Unstaged changes after reset:
M   tex/MCMC-in-IRT.tex
M   tex/recipe-example/build-example-plots.R
M   tex/recipe-example/build-failure-plots.R

Step 11: Looking at the fsck again...

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a

The dangling blobs are not errors. I'm not concerned with master.u1conflict, and now that it is working I don't want to touch it anymore!

Step 12: Catching up with my local edits:

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#   modified:   tex/MCMC-in-IRT.tex
#   modified:   tex/recipe-example/build-example-plots.R
#   modified:   tex/recipe-example/build-failure-plots.R
< ... snip ... >
no changes added to commit (use "git add" and/or "git commit -a")

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "recovering from the git fiasco"
[master 7922876] recovering from the git fiasco
 3 files changed, 12 insertions(+), 94 deletions(-)

nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git add tex/sept2012_code/example-code-testing.R
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "adding in the example code"
[master 385c023] adding in the example code
 1 file changed, 331 insertions(+)
 create mode 100644 tex/sept2012_code/example-code-testing.R

So hopefully that can be of some use to people in the future. I'm glad it worked.

Remote debugging a Java application

Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):

java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>

Original answer follows.

Try this:

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp

Two points here:

  1. No spaces in the runjdwp option.
  2. Options come before the class name. Any arguments you have after the class name are arguments to your program!

Find the 2nd largest element in an array with minimum number of comparisons

function findSecondLargeNumber(arr){

    var fLargeNum = 0;
    var sLargeNum = 0;

    for(var i=0; i<arr.length; i++){
        if(fLargeNum < arr[i]){
            sLargeNum = fLargeNum;
            fLargeNum = arr[i];         
        }else if(sLargeNum < arr[i]){
            sLargeNum = arr[i];

    return sLargeNum;

var myArray = [799, -85, 8, -1, 6, 4, 3, -2, -15, 0, 207, 75, 785, 122, 17];


Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    width: auto !important;

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue =;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue =;

Works in IE, Chrome and FF, I did not test Safari.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

In my opinion, a dynamic PL/SQL block is somewhat obscure. While is very flexible, is also hard to tune, hard to debug and hard to figure out what's up. My vote goes to your first option,

EXECUTE IMMEDIATE v_query_str INTO v_num_of_employees USING p_job;

Both uses bind variables, but first, for me, is more redeable and tuneable than @jonearles option.

How to filter object array based on attributes?

I prefer the Underscore framework. It suggests many useful operations with objects. Your task:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 &
    num_of_beds >=2 & 
    num_of_baths >= 2.5);

can be overwriten like:

var newArray = _.filter (homes, function(home) {
    return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;

Hope it will be useful for you!

How to find cube root using Python?

You could use x ** (1. / 3) to compute the (floating-point) cube root of x.

The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:

def is_perfect_cube(x):
    x = abs(x)
    return int(round(x ** (1. / 3))) ** 3 == x

print(is_perfect_cube(2146689000)) # no other currently posted solution
                                   # handles this correctly

This takes the cube root of x, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x.

The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).

Simpler way to check if variable is not equal to multiple string values?

If you're planning on building a function in the if statement, I'd also advise the use of in_array. It's a lot cleaner.

If you're attempting to assign values to variables you can use the if/else shorthand:

$variable_to_fill = $some_variable !== 'uk' ? false : true;

How to write log to file

This works for me

  1. created a package called logger.go

    package logger
    import (
    var (
      Log      *log.Logger
    func init() {
        // set location of log file
        var logpath = build.Default.GOPATH + "/src/chat/logger/info.log"
       var file, err1 = os.Create(logpath)
       if err1 != nil {
          Log = log.New(file, "", log.LstdFlags|log.Lshortfile)
          Log.Println("LogFile : " + logpath)
    1. import the package wherever you want to log e.g main.go

      package main
      import (
      const (
         VERSION = "0.13"
      func main() {
          // time to use our logger, print version, processID and number of running process
          logger.Log.Printf("Server v%s pid=%d started with processes: %d", VERSION, os.Getpid(),runtime.GOMAXPROCS(runtime.NumCPU()))

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

You could also see the README and check the documentation here

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

How to add a list item to an existing unordered list?

You can do it also in more 'object way' and still easy-to-read:

$('#content ul').append(
            $('<span>').attr('class', 'tab').append("Message center")

You don't have to fight with quotes then, but must keep trace of braces :)

Difference between const reference and normal parameter

Since none of you mentioned nothing about the const keyword...

The const keyword modifies the type of a type declaration or the type of a function parameter, preventing the value from varying. (Source: MS)

In other words: passing a parameter by reference exposes it to modification by the callee. Using the const keyword prevents the modification.

How to insert an object in an ArrayList at a specific position

You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.

For convenience, you may use this extension function in Kotlin

 * Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
fun <T> MutableList<T>.insert(index: Int, element: T) {
    if (index <= size) {
        add(index, element)
    } else {

Fully backup a git repo?

cd /path/to/backupdir/
git clone /path/to/repo
cd /path/to/repo
git remote add backup /path/to/backupdir
git push --set-upstream backup master

this creates a backup and makes the setup, so that you can do a git push to update your backup, what is probably what you want to do. Just make sure, that /path/to/backupdir and /path/to/repo are at least different hard drives, otherwise it doesn't make that much sense to do that.

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

Groovy - How to compare the string?

If you don't want to check on upper or lowercases you can use the following method.

String str = "India" 

def compareString(String str){ 
  def str2 = "india" 
  if( str2.toUpperCase() == str.toUpperCase() ) { 
    println "same" 
    println "not same" 

So now if you change str to "iNdIa" it'll still work, so you lower the chance that you make a typo.

Retrieve the position (X,Y) of an HTML element relative to the browser window

if using jQuery, the dimensions plugin is excellent and allows you specify exactly what you want.


Relative position, absolute position, absolute position without padding, with padding...

It goes on, let's just say there is a lot you can do with it.

Plus the bonus of using jQuery is it's lightweight file size and easy use, you won't go back to JavaScript without it afterwards.

Call Stored Procedure within Create Trigger in SQL Server

The following should do the trick - Only SqlServer

Alter TRIGGER Catagory_Master_Date_update ON Catagory_Master AFTER delete,Update


Declare @id int
DECLARE @cDate as DateTime
    set @cDate =(select Getdate())

select @id=deleted.Catagory_id from deleted
print @cDate

execute dbo.psp_Update_Category @id


Alter PROCEDURE dbo.psp_Update_Category
@id int

DECLARE @cDate as DateTime
    set @cDate =(select Getdate())
    --Update Catagory_Master Set Modify_date=''+@cDate+'' Where Catagory_ID=@id   --@UserID
    Insert into Catagory_Master (Catagory_id,Catagory_Name) values(12,'Testing11')

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

How to get JSON response from http.Get

The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target structure.

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)

Example use:

type Foo struct {
    Bar string

func main() {
    foo1 := new(Foo) // or &Foo{}
    getJson("", foo1)

    // alternately:

    foo2 := Foo{}
    getJson("", &foo2)

You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):

     for item in dir:

                b = "{}\*".format(item)
                dir += glob(b)

How to efficiently concatenate strings in go

strings.Join() from the "strings" package

If you have a type mismatch(like if you are trying to join an int and a string), you do RANDOMTYPE (thing you want to change)


package main

import (

var intEX = 0
var stringEX = "hello all you "
var stringEX2 = "people in here"

func main() {
    s := []string{stringEX, stringEX2}
    fmt.Println(strings.Join(s, ""))

Output :

hello all you people in here

How to configure SMTP settings in web.config

I don't have enough rep to answer ClintEastwood, and the accepted answer is correct for the Web.config file. Adding this in for code difference.

When your mailSettings are set on Web.config, you don't need to do anything other than new up your SmtpClient and .Send. It finds the connection itself without needing to be referenced. You would change your C# from this:

SmtpClient smtpClient = new SmtpClient("", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;

To this:

SmtpClient smtpClient = new SmtpClient();

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?

If not please let me know where you get stuck.

Install Common Dependencies

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

Install NumArray 1.5.2

wget -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python install

Install Numeric 23.8

wget -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python install

Install HDF5 1.6.5

tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make 
sudo make install

Install Nanoengineer

git clone
cd nanoengineer
sudo make install


On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc is inserted in CFLAGS and gcc will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...

touch sim/src/x86_64-linux-gnu-gcc

If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...

output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);

If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running

export CPPFLAGS=-I/usr/local/include/python2.7
sudo make install

If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:

static char tracePrefix[] = "";
static char tracePrefix[] = "";

If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files


that look like this:


to look like this:

from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB

I also found an additional troubleshooting text file that has been removed, but you can find it here

Difference between style = "position:absolute" and style = "position:relative"

Absolute positioning means that the element is taken completely out of the normal flow of the page layout. As far as the rest of the elements on the page are concerned, the absolutely positioned element simply doesn't exist. The element itself is then drawn separately, sort of "on top" of everything else, at the position you specify using the left, right, top and bottom attributes.

Using the position you specify with these attributes, the element is then placed at that position within its last ancestor element which has a position attribute of anything other than static (page elements default to static when no position attribute specified), or the document body (browser viewport) if no such ancestor exists.

For example, if I had this code:

  <div style="position:absolute; left: 20px; top: 20px;"></div>

...the <div> would be positioned 20px from the top of the browser viewport, and 20px from the left edge of same.

However, if I did something like this:

 <div id="outer" style="position:relative">
   <div id="inner" style="position:absolute; left: 20px; top: 20px;"></div>

...then the inner div would be positioned 20px from the top of the outer div, and 20px from the left edge of same, because the outer div isn't positioned with position:static because we've explicitly set it to use position:relative.

Relative positioning, on the other hand, is just like stating no positioning at all, but the left, right, top and bottom attributes "nudge" the element out of their normal layout. The rest of the elements on the page still get laid out as if the element was in its normal spot though.

For example, if I had this code:


...then all three <span> elements would sit next to each other without overlapping.

If I set the second <span> to use relative positioning, like this:

<span style="position: relative; left: -5px;">Span2</span>

...then Span2 would overlap the right side of Span1 by 5px. Span1 and Span3 would sit in exactly the same place as they did in the first example, leaving a 5px gap between the right side of Span2 and the left side of Span3.

Hope that clarifies things a bit.

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Select element based on multiple classes

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 {
    /* style here */

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector {


Official documentation : CSS2 class selectors.

As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

Fatal error: "No Target Architecture" in Visual Studio

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here:

In fact, there is 99% that error related to /etc/hosts file

X server just unable to resolve localhost and all consequent actions just fails.

Please be sure that you have a record like localhost

in your /etc/hosts file.

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

i would recommend Modern UI for WPF .

It has a very active maintainer it is awesome and free!

Modern UI for WPF (Screenshot of the sample application

I'm currently porting some projects to MUI, first (and meanwhile second) impression is just wow!

To see MUI in action you could download XAML Spy which is based on MUI.

EDIT: Using Modern UI for WPF a few months and i'm loving it!

How do I adb pull ALL files of a folder present in SD Card

If you want to pull a directory with restricted access from a rooted device you need to restart adb as root: type adb root before pull. Otherwise you'll get an error saying remote object '/data/data/' does not exist

How to detect if URL has changed after hash in JavaScript

While doing a little chrome extension, I faced the same problem with an additionnal problem : Sometimes, the page change but not the URL.

For instance, just go to the Facebook Homepage, and click on the 'Home' button. You will reload the page but the URL won't change (one-page app style).

99% of the time, we are developping websites so we can get those events from Frameworks like Angular, React, Vue etc..

BUT, in my case of a Chrome extension (in Vanilla JS), I had to listen to an event that will trigger for each "page change", which can generally be caught by URL changed, but sometimes it doesn't.

My homemade solution was the following :

var oldLength = -1;
function listen(currentLength) {
  if (currentLength != oldLength) {
    // Do your stuff here

  oldLength = window.history.length;
  setTimeout(function () {
  }, 1000);

So basically the leoneckert solution, applied to window history, which will change when a page changes in a single page app.

Not rocket science, but cleanest solution I found, considering we are only checking an integer equality here, and not bigger objects or the whole DOM.

JavaScript click event listener on class

This should work. getElementsByClassName returns an array Array-like object(see edit) of the elements matching the criteria.

var elements = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);

jQuery does the looping part for you, which you need to do in plain JavaScript.

If you have ES6 support you can replace your last line with:

    Array.from(elements).forEach(function(element) {
      element.addEventListener('click', myFunction);

Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName and so they return undefined.

EDIT : Correction

getElementsByClassName doesnt return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)

Thanks to user @Nemo for pointing this out and having me dig in to fully understand.

Split string on whitespace in Python

Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.


>>> "ark".split()

Cross-browser window resize event - JavaScript / jQuery

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {

)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

How to set default value to all keys of a dict object in python?

In case you actually mean what you seem to ask, I'll provide this alternative answer.

You say you want the dict to return a specified value, you do not say you want to set that value at the same time, like defaultdict does. This will do so:

class DictWithDefault(dict):
    def __init__(self, default, **kwargs):
        self.default = default
        super(DictWithDefault, self).__init__(**kwargs)

    def __getitem__(self, key):
        if key in self:
            return super(DictWithDefault, self).__getitem__(key)
        return self.default

Use like this:

d = DictWIthDefault(99, x=5, y=3)
print d["x"]   # 5
print d[42]    # 99
42 in d        # False
d[42] = 3
42 in d        # True

Alternatively, you can use a standard dict like this:

d = {3: 9, 4: 2}
default = 99
print d.get(3, default)  # 9
print d.get(42, default) # 99

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
    std::list<Object>::iterator it = std::next(l.begin(), N);

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

How/When does Execute Shell mark a build as failure in Jenkins?

Plain and simple:

If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).

Why exactly that happens depends on your build script.

I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?

How to add image in Flutter

To use image in Flutter. Do these steps.

1. Create a Directory inside assets folder named images. As shown in figure belowenter image description here

2. Put your desired images to images folder.

3. Open pubpsec.yaml file . And add declare your images.Like:--enter image description here

4. Use this images in your code as.

            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          child: Text("$index",style: TextStyle(color:,fontSize: 16,fontFamily:'LangerReguler')),

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input('Restart?  y/n:')
   ...:         if do_run == 'y':
   ...:             pass
   ...:         elif do_run == 'n':
   ...:             break
   ...:         else: 
   ...:             print 'Invalid input'
   ...:             continue
   ...:     print 'Doing stuff!!!'
   ...:     if start == 1:
   ...:         start = 0
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

How to install packages offline?

For Pip 8.1.2 you can use pip download -r requ.txt to download packages to your local machine.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How to hide the keyboard when I press return key in a UITextField?

Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.

class TextFieldWithReturn: UITextField, UITextFieldDelegate

    required init?(coder aDecoder: NSCoder) 
        super.init(coder: aDecoder)
        self.delegate = self

    func textFieldShouldReturn(_ textField: UITextField) -> Bool
        return true


Then all you need to do in the storyboard is set the fields to use the class:

enter image description here

How to pass values between Fragments

This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.

In receiver fragment add a listener:

    FragmentResultListener { requestKey: String, bundle: Bundle ->
        // unpack the bundle and use data
        val frag1Str = bundle.getString("frag1_data_key")


In sender fragment(frag1):

    bundleOf("frag1_data_key" to value)

Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.

Credits and further reading:

A New Way to Pass Data Between Fragments

Android Fragments: Fragment Result

AssertionError: View function mapping is overwriting an existing endpoint function: main

Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps

Where does Hive store files in HDFS?

Hive database is nothing but directories within HDFS with .db extensions.

So, from a Unix or Linux host which is connected to HDFS, search by following based on type of HDFS distribution:

hdfs dfs -ls -R / 2>/dev/null|grep db or hadoop fs -ls -R / 2>/dev/null|grep db

You will see full path of .db database directories. All tables will be residing under respective .db database directories.

Removing object from array in Swift 3

  1. for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object) is for loop in C-style and has been removed

  2. Change your code to something like this to remove all similar object if it have looped:

    let indexes = arrContacts.enumerated().filter { $0.element == contacts[indexPath.row] }.map{ $0.offset }
    for index in indexes.reversed() {
       arrContacts.remove(at: index)

Increase max execution time for php

PHP file (for example, my_lengthy_script.php)

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

.htaccess file

<IfModule mod_php5.c>
php_value max_execution_time 300

More configuration options

<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200

If wordpress, set this in the config.php file,

define('WP_MEMORY_LIMIT', '128M');

If drupal, sites/default/settings.php

ini_set('memory_limit', '128M');

If you are using other frameworks,

ini_set('memory_limit', '128M');

You can increase memory as gigabyte.

ini_set('memory_limit', '3G'); // 3 Gigabytes

259200 means:-

( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days

More details on my blog

Pass user defined environment variable to tomcat

If you are starting your Tomcat from Eclipse ("Servers" view) then you should have a "Run/Run Configuration" (menu) entry called "Apache Tomcat / Tomcat …". When you select this entry in the list of run configurations you get a window with several tabs, one of which is labeled "Environment". There you can configure environment variables for your Tomcat. Be sure to restart Tomcat afterwards.

Prevent the keyboard from displaying on activity start

Hide it for all activities using the theme

<style name="MyTheme" parent="Theme">
    <item name="android:windowSoftInputMode">stateHidden</item>

set the theme

<application android:theme="@style/MyTheme">

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

How to print a linebreak in a python function?

The newline character is actually '\n'.

How to Join to first row

CROSS APPLY to the rescue:

SELECT Orders.OrderNumber, topline.Quantity, topline.Description
FROM Orders
cross apply
    select top 1 Description,Quantity
    from LineItems 
    where Orders.OrderID = LineItems.OrderID

You can also add the order by of your choice.

Fragments within Fragments

Nested fragments are supported in android 4.2 and later

The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

To nest a fragment, simply call getChildFragmentManager() on the Fragment in which you want to add a fragment. This returns a FragmentManager that you can use like you normally do from the top-level activity to create fragment transactions. For example, here’s some code that adds a fragment from within an existing Fragment class:

Fragment videoFragment = new VideoPlayerFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(, videoFragment).commit();

To get more idea about nested fragments, please go through these tutorials
Part 1
Part 2
Part 3

and here is a SO post which discuss about best practices for nested fragments.

Android device chooser - My device seems offline

I have HTC wildfire and disabling and enabling the debugging worked fine for the "offline" problem. The error does not show up.

However I ran into a new problem when trying to import a python file with sl3a : "no moduled named android" explained here. That being said, I still cannot run this file located somewhere on the SD Card/python folder. I can connect with androidscreencast.jnlp and it works fine :)

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
    static void Main(string[] args)
        var source =  @"
        <!DOCTYPE html>
                <p>An image from W3Schools:</p>

    private static void StartBrowser(string source)
        var th = new Thread(() =>
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
            webBrowser.DocumentText = source;

    static void 
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

Figuring out whether a number is a Double in Java

Since this is the first question from Google I'll add the JavaScript style typeof alternative here as well:

myObject.getClass().getName() // String

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'

How do you format a Date/Time in TypeScript?

  1. You can create pipe inherited from PipeTransform base
  2. Then implement transform method

Used in Angular 4 - it's working. Best way to format a date is a pipe.

Create your custom pipe like this:

import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';

    name: 'dateFormat'
  export class DateFormatPipe extends DatePipe implements PipeTransform {
    transform(value: any, args?: any): any {
       return super.transform(value, "MMM/dd/yyyy");

and it's used in a TypeScript class like this:

////my class////

export class MyComponent
  constructor(private _dateFormatPipe:DateFormatPipe)

     let myDate = this._dateFormatPipe.transform(new Date())//formatting current ///date here 
     //you can pass any date type variable 

How to get the Enum Index value in C#

Firstly, there could be two values that you're referring to:

Underlying Value

If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong

Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:

int eValue = (int)enumValue;

However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to @JohnStock for the poke to clarify).

This example assigns each a new value, and show the value returned:

public enum MyEnum
    MyValue1 = 34,
    MyValue2 = 27

(int)MyEnum.MyValue2 == 27; // True

Index Value

The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.

Android Spinner : Avoid onItemSelected calls during initialization

Try this

spinner.postDelayed(new Runnable() {
        public void run() {
    }, 1000);.o

What's the difference between ".equals" and "=="?

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

The executable gets signed with invalid entitlements in Xcode

Had some issue. Resolve: go to right target -> capabilities -> for me there was issue with "In-App Purchase" and button to fix it. Off-on operation fixed issue.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I faced the same issue while submitting the app using Xcode 4.6. It does not recognise the icons with dimension 120x120, 58x58, 29x29, etc. So when I tried to add these icons into the info.plist and submit the app for review, Xcode 4.6 did not allow me to do so. On submitting the app without the above icons, I got a mail saying -

"Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format."

Since, it was recommended and not necessary, I submitted the app anyhow. I added the above recommended icons to the bundle but did not specify them in the Info.plist. I got the same mail again. This time I ignored it and to my surprise the app was accepted.

I wanted my app to run on iOS 5 and above and therefore, I had to use Xcode 4.6 and not the latest Xcode 5 which properly allows only apps for iOS7 and above only.


NOTE: "Starting February 1st 2014 new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK".

Thus, this scenario will be invalid in future.

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

    return new RestTemplate(requestFactory);

how to start stop tomcat server using CMD?

you can use this trick to run tomcat using cmd and directly by tomcat bin folder.

1. set the path of jdk.


To set path. go to Desktop and right click on computer icon. Click the Properties

go to Advance System Settings.

then Click Advance to Environment variables.

Click new and set path AS,

in the column Variable name=JAVA_HOME

Variable Value=C:\Program Files\Java\jdk1.6.0_19

Click ok ok.

now path is stetted.


Go to tomcat folder where you installed the tomcat. go to bin folder. there are two window batch files.



By using cmd if you installed the tomcate in D Drive

type on cmd screen

  1. D:

  2. Cd tomcat\bin then type Startup.

4. By clicking them you can start and stop the tomcat.


Final step.

if you start and want to check it.

open a Browser in URL bar type.


In Oracle SQL: How do you insert the current date + time into a table?

It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:

insert into errortable (dateupdated, table1id)
    values (sysdate, 1083);

It seems silly to convert the system date to a string just to convert it back to a date.

If you want to see the full date, then you can do:

select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

This problem stems from an improper Java installation.

Possibility 1

NOTE: This scenario only applies to Java 8 and prior. Beginning with Java 9, the JRE is structured differently. rt.jar and friends no longer exist, and Pack200 is no longer used.

The Java standard library is contained in various JARs, such as rt.jar, deploy.jar, jsse.jar, etc. When the JRE is packaged, these critical JAR files are compressed with Pack200 and stored as rt.pack, deploy.pack, jsse.pack, etc. The Java installer is supposed to uncompress them. If you are experiencing this error, apparently that didn't happen.

You need to manually run unpack200 on all .pack files in the JRE's lib/ and lib/ext/ folders.


To unpack one .pack file (for example rt.pack), run:

"%JAVA_HOME%\bin\unpack200" -r -v rt.pack rt.jar

To recursively unpack all .pack files, from the JRE root run:

for /r %f in (*.pack) do "%JAVA_HOME%\bin\unpack200.exe" -r -q "%f" "%~pf%~nf.jar"


To unpack one .pack file (for example rt.pack), run:

/usr/bin/unpack200 -r -v rt.pack rt.jar

To recursively unpack all .pack files, from the JRE root run:

find -iname "*.pack" -exec sh -c "/usr/bin/unpack200 -r -q {} \$(echo {} | sed 's/\(.*\.\)pack/\1jar/')" \;

Possibility 2

You misinstalled Java in some other way. Perhaps you installed without admin rights, or tried to simply extract files out of the installer. Try again with the installer and/or more privileges. Or, if you don't want to use the installer, use the .tar.gz Java package instead.

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

You are using setTimeout wrong way. The (one of) function signature is setTimeout(callback, delay). So you can easily specify what code should be run after what delay.

var codeAddress = (function() {
    var index = 0;
    var delay = 100;

    function GeocodeCallback(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
        else alert("Geocode was not successful for the following reason: " + status);

    return function(vPostCode) {
        if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);

This way, every codeAddress() call will result in geocoder.geocode() being called 100ms later after previous call.

I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay variable.

Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)

In C can a long printf statement be broken up into multiple lines?

The C compiler can glue adjacent string literals into one, like

printf("foo: %s "
       "bar: %d", foo, bar);

The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):

printf("foo %s \
bar: %d", foo, bar);

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status

How to configure Visual Studio to use Beyond Compare

In Visual Studio 2008 + , go to the

Tools menu -->  select Options 

enter image description here

In Options Window --> expand Source Control --> Select Subversion User Tools --> Select Beyond Compare

and click OK button..

Reverse Singly Linked List Java

Use this.

if (current== null || return current;
 Node nextItem =; = null;
 Node reverseRest = reverse(nextItem); = current;
 return reverseRest

or Java Program to reverse a Singly Linked List