Latest Snippet

Mass Killing MySQL Connection

// how to mass kill all mysql connection

SELECT concat('KILL ',id,';') FROM information_schema.processlist WHERE user='root';
SELECT concat('KILL ',id,';') FROM information_schema.processlist WHERE user='root' INTO OUTFILE '/tmp/a.txt';
source /tmp/a.txt;

Resize Array in Java

/**
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray  the old array, to be reallocated.
* @param newSize   the new array size.
* @return          A new array with the same contents.
*/
private static Object resizeArray (Object oldArray, int newSize) {
   int oldSize = java.lang.reflect.Array.getLength(oldArray);
   Class elementType = oldArray.getClass().getComponentType();
   Object newArray = java.lang.reflect.Array.newInstance(
         elementType,newSize);
   int preserveLength = Math.min(oldSize,newSize);
   if (preserveLength > 0)
      System.arraycopy (oldArray,0,newArray,0,preserveLength);
   return newArray;
}

// Test routine for resizeArray().
public static void main (String[] args) {
   int[] a = {1,2,3};
   a = (int[])resizeArray(a,5);
   a[3] = 4;
   a[4] = 5;
   for (int i=0; i<a.length; i++)
      System.out.println (a[i]);
}

Capture Screenshot in Java

// http://viralpatel.net/blogs/2009/01/how-to-take-screen-shots-in-java-taking-screenshots-java.html

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

//...

public void captureScreen(String fileName) throws Exception {
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));
}
//..

Set Java HTTP Proxy

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

Create Thumbnail using Java

// creating thumbnail

private void createThumbnail(String filename, 
                             int thumbWidth, 
                             int thumbHeight,
                             int quality, 
                             String outFilename)
                             throws InterruptedException, 
							        FileNotFoundException, 
                                    IOException {
	// load image from filename
	Image image = Toolkit.getDefaultToolkit().getImage(filename);
	MediaTracker mediaTracker = new MediaTracker(new Container());
	mediaTracker.addImage(image, 0);
	mediaTracker.waitForID(0);
	// System.out.println(mediaTracker.isErrorAny());

	// determine thumbnail size from WIDTH and HEIGHT
	double thumbRatio = (double)thumbWidth / (double)thumbHeight;
	int imageWidth = image.getWidth(null);
	int imageHeight = image.getHeight(null);
	double imageRatio = (double)imageWidth / (double)imageHeight;
	if (thumbRatio < imageRatio) {
		thumbHeight = (int)(thumbWidth / imageRatio);
	} else {
		thumbWidth = (int)(thumbHeight * imageRatio);
	}

	// draw original image to thumbnail image object and
	// scale it to the new size on-the-fly
	BufferedImage thumbImage = new BufferedImage(thumbWidth, 
		thumbHeight, 
		BufferedImage.TYPE_INT_RGB);
	Graphics2D graphics2D = thumbImage.createGraphics();
	graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
		RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

	// save thumbnail image to outFilename
	BufferedOutputStream out = new BufferedOutputStream(
		new FileOutputStream(outFilename));
	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
	JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(
		thumbImage);
	quality = Math.max(0, Math.min(quality, 100));
	param.setQuality((float)quality / 100.0f, false);
	encoder.setJPEGEncodeParam(param);
	encoder.encode(thumbImage);
	out.close();
}

Copy File using Java NIO

// faster file copy using java NIO

public static void fileCopy( File in, File out ) throws IOException {
	FileChannel inChannel = new FileInputStream( in ).getChannel();
	FileChannel outChannel = new FileOutputStream( out ).getChannel();
	try {
		// magic number for Windows, 64Mb - 32Kb)
		int maxCount = (64 * 1024 * 1024) - (32 * 1024);
		long size = inChannel.size();
		long position = 0;
		while ( position < size ) {
		   position += inChannel.transferTo( position, maxCount, outChannel );
		}
	} finally {
		if ( inChannel != null ) { inChannel.close(); }
		if ( outChannel != null ) { outChannel.close(); }
	}
}

Parse Date String to Java Date

// parse a date string to java date object

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

//or

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );

Get Current Method Name in Java

// retrieving the current method name in Java

String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();

Save Last Played Video's on Linux

// after you played the video, you can save the video by searching /tmp for fla files

#!/bin/bash
name=$(/usr/bin/zenity --entry --title="Name your Video" --height=100 --width=300 --text="Please name your video ")
cp /tmp/Fla* ~/Videos/"$name"

Self Printing PHP

// the titles explain itself

<? $s='<? $s=%c%s%c%cprintf($s,39,$s,39,10);?>'; 
printf($s,39,$s,39,10);?>

Reverse Text CSS

// using CSS to reverse text

body {direction: rtl; unicode-bidi: bidi-override;}

Cross Browser XMLHttpRequest - Optimized

// retrieveing XMLHttpRequest object - optimized version
// using closure

var xhr = function() {
	if (window.console) console.log( 'xhr()' )
	if (window.XMLHttpRequest) {
		xhr = function() {
			return new XMLHttpRequest();
		};
	} else {
		xhr = function() {
			return new ActiveXObject('Microsoft.XMLHTTP');
		}
	}
	return xhr();
}

//usage
var req = xhr();
var req2 = xhr();

//the second call to xhr will not evaluate the if (window.XMLHttpRequest) again ;)

Photo Collage using ImageMagick

// here's a simple bash command for creating photo collage using ImageMagick

#rename image to random first
$ for f in `ls *.jpg`; do mv $f $RANDOM.jpg; done

#now make collage
montage '*.jpg' -border 2x2 -background black +polaroid -resize 50% -background LightGray -geometry -50-50 -tile x3 collage.jpg

Python Valentine Code

// description of your code here

print "\n".join([" ".join(["valentine"[0:n] for n in t]).center(9) for t in [(3,3),(9,)] + map(lambda n: (n,), range(9,0,-2))])

Adding key_name when saving appengine djangoforms

// You cannot set key_name for models in appengine's djangoforms
// Now you can!

form = TagForm(request.POST or None, instance=tag)
errors = form.errors
if not errors:
  try:
    tag = form.save(commit=False)
  except ValueError, err:
    errors['__all__'] = unicode(err)
  if not errors:
    key_name = 'tag:%s' % tag.name
    saved_tag = Tag(key_name=key_name, **dict([(prop, getattr(tag, prop)) for prop in Tag.properties()]))
    saved_tag.save()

Simple Tag Clouds

// simple tagclouds

import math
for t in tags:
  print t.name, t.count, int(math.ceil(5 * math.log(t.count, math.e)))

console.log when firebug exists or not

//sometimes we forget to comment firebug console.log statement in production web
//and spawn lots of errors, here's the code on how to override console.log method when
//firebug not exists

(function(__global){
  if (!__global.console || (__global.console && !__global.console.log)) {
    __global.console = {
      log: (__global.opera && __global.opera.postError)
        ? __global.opera.postError
        : function(){ }
    }
  }
})(this);

Common JDBC Operation

// this class wrapups common JDBC operation

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.log4j.Logger;

public class DBConn {
    private static Logger logger = Logger.getLogger(DBConn.class);
    private static Context initCtx = null;
    private static DataSource ds = null;
    private static String resource = "java:comp/env/jdbc/MyResource";
    
    /**
     * Get a connection from pool
     *
     * @return a Connection
     */
    public static Connection getConnection() throws SQLException {
        try {
            if (initCtx == null) {
                initCtx = new InitialContext();
            }
            if (ds == null) {
                ds = (DataSource) initCtx.lookup(resource);
            }
            Connection conn = ds.getConnection();
            return conn;
        } catch(NamingException ne) {
            logger.warn("exception while getting connection: " + resource + ":" + ne);
            throw new SQLException(ne.getMessage());
        }
    }   
    /**
     * Look up the DataSource
     *
     * @return the DataSource
     */
    public static DataSource getDataSource() throws SQLException {
        try {
            DataSource ds = null;
            if (initCtx == null) {
                initCtx = new InitialContext();
            }
            if (ds == null) {
                ds = (DataSource) initCtx.lookup(resource);
            }
            return ds;
        } catch(NamingException ne) {
            logger.warn("exception while getting datasource: " + resource + ":" + ne);
            throw new SQLException(ne.getMessage());
        }
    }
    
    /**
     * Execute an SQL SELECT query without any replacement parameters and
     * place the column values from the first row in an Object[].
     *
     * Usage Demo:
     * <pre>
     *      Object[] result = searchToArray(sql);
     *      if (result != null) {
     *          for (int i = 0; i < result.length; i++) {
     *              System.out.println(result[i]);
     *          }
     *      }
     * </pre>
     *
     * @param sql The SQL to execute.
     * @return An Object[] or null if there are no rows in the ResultSet.
     */
    public static Object[] select(String sql) throws SQLException {
        Object[] result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayHandler();
        logger.info("select: sql=" + sql);
        result = (Object[]) run.query(sql, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter and
     * place the column values from the first row in an Object[].
     *
     * @param sql The SQL statement to execute.
     * @param param The replacement parameter.
     * @return An Object[] or null if there are no rows in the ResultSet.
     */
    public static Object[] select(String sql, Object param) throws SQLException {
        Object[] result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayHandler();
        logger.info("select: sql=" + sql + ",param=" + param);
        result = (Object[]) run.query(sql, param, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL query and place the
     * column values from the first row in an Object[].
     *
     * @param sql The SQL statement to execute.
     * @param params Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return An Object[] or null if there are no rows in the ResultSet.
     */
    public static Object[] select(String sql, Object[] params) throws SQLException {
        Object[] result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayHandler();
        logger.info("select: sql=" + sql + ",params=" + Arrays.asList(params));
        result = (Object[]) run.query(sql, params, h);
        return result;
    }
   
    /**
     * Execute an SQL SELECT query without any replacement parameters and
     * place the ResultSet into a List of Object[]s
     *
     * Usage Demo:
     * <pre>
     *      ArrayList result = searchToArrayList(sql);
     *      Iterator iterator = result.iterator();
     *      while (iterator.hasNext()) {
     *          Object[] temp = (Object[])iterator.next();
     *          for (int i = 0; i < temp.length; i++) {
     *              System.out.println(temp[i]);
     *          }
     *      }
     * </pre>
     * @param sql The SQL statement to execute.
     * @return A List of Object[]s, never null.
     */
    public static List selectList(String sql) throws SQLException {
        ArrayList result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayListHandler();
        logger.info("selectList: sql=" + sql);
        result = (ArrayList) run.query(sql, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter
     * and place the ResultSet into a List of Object[]s
     *
     * @param sql The SQL statement to execute.
     * @param param The replacement parameter.
     * @return A List of Object[]s, never null.
     */
    public static List selectList(String sql, Object param) throws SQLException {
        ArrayList result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayListHandler();
        logger.info("selectList: sql=" + sql + ",params=" + param);
        result = (ArrayList) run.query(sql, param, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL query and place
     * the ResultSet into a List of Object[]s
     *
     * @param sql The SQL statement to execute.
     * @param params Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return A List of Object[]s, never null.
     */
    public static List selectList(String sql, Object[] params) throws SQLException {
        ArrayList result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new ArrayListHandler();
        logger.info("selectList: sql=" + sql + ",params=" + Arrays.asList(params));
        result = (ArrayList) run.query(sql, params, h);
        return result;
    }
   
    /**
     * Execute an SQL SELECT query without any replacement parameters
     * and converts the first ResultSet into a Map object.
     *
     * Usage Demo:
     * <pre>
     *      Map result = searchToMap(sql);
     *      System.out.println(map.get(columnName));
     * </pre>
     * @param sql The SQL to execute.
     * @return A Map with the values from the first row or null if there
     * are no rows in the ResultSet.
     */
    public static Map selectMap(String sql) throws SQLException {
        Map result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapHandler();
        logger.info("selectMap: sql=" + sql);
        result = (Map) run.query(sql, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter
     * and converts the first ResultSet into a Map object.
     *
     * @param sql The SQL to execute.
     * @param param The replacement parameter.
     * @return A Map with the values from the first row or null if there
     * are no rows in the ResultSet.
     */
    public static Map selectMap(String sql, Object param) throws SQLException {
        Map result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapHandler();
        logger.info("selectMap: sql=" + sql + ",param=" + param);
        result = (Map) run.query(sql, param, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL query and converts
     * the first ResultSet into a Map object.
     *
     * @param sql The SQL to execute.
     * @param params Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return A Map with the values from the first row or null if there
     * are no rows in the ResultSet.
     */
    public static Map selectMap(String sql, Object[] params) throws SQLException {
        Map result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapHandler();
        logger.info("selectMap: sql=" + sql + ",param=" + Arrays.asList(params));
        result = (Map) run.query(sql, params, h);
        return result;
    }
   
    /**
     * Execute an SQL SELECT query without any replacement parameters
     * and converts the ResultSet into a List of Map objects.
     *
     * Usage Demo:
     * <pre>
     *      ArrayList result = searchToMapList(sql);
     *      Iterator iterator = result.iterator();
     *      while (iterator.hasNext()) {
     *           Map map = (Map)iterator.next();
     *           System.out.println(map.get(columnName));
     *      }
     * </pre>
     * @param sql The SQL to execute.
     * @return A List of Maps, never null.
     */
    public static List selectMapList(String sql) throws SQLException{
        List result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapListHandler();
        logger.info("selectMapList: sql=" + sql);
        result = (ArrayList) run.query(sql, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter
     * and converts the ResultSet into a List of Map objects.
     *
     * @param sql The SQL to execute.
     * @param param The replacement parameter.
     * @return A List of Maps, never null.
     */
    public static List selectMapList(String sql, Object param) throws SQLException {
        ArrayList result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapListHandler();
        logger.info("selectMapList: sql=" + sql + ",param=" + param);
        result = (ArrayList) run.query(sql, param, h);
        return result;
    }
   
    /**
     * Executes the given SELECT SQL query and converts
     * the ResultSet into a List of Map objects.
     *
     * @param sql The SQL to execute.
     * @param params Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return A List of Maps, never null.
     */
    public static List selectMapList(String sql, Object[] params) throws SQLException  {
        ArrayList result = null;
        QueryRunner run = new QueryRunner(getDataSource());
        ResultSetHandler h = new MapListHandler();
        logger.info("selectMapList: sql=" + sql + ",param=" + Arrays.asList(params));
        result = (ArrayList) run.query(sql, params, h);
        return result;
    }
   
    /**
     * Execute an SQL SELECT query without any replacement parameters
     * and Convert the first row of the ResultSet into a bean with the
     * Class given in the parameter.
     *
     * Usage Demo:
     * <pre>
     *      String sql = "SELECT * FROM test";
     *      Test test = (Test)searchToBean(Test.class, sql);
     *      if (test != null) {
     *          System.out.println("test:" + test.getPropertyName());
     *      }
     * </pre>
     * @param type The Class of beans.
     * @param sql The SQL to execute.
     * @return An initialized JavaBean or null if there were no rows in
     * the ResultSet.
     */
    public static Object selectObject(Class type, String sql) throws SQLException {
        Object result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanHandler(type);
            logger.info("selectObject: sql=" + sql);
            result = run.query(sql, h);
            return result;
        } catch(Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter
     * and Convert the first row of the ResultSet into a bean with the
     * Class given in the parameter.
     *
     * @param type The Class of beans.
     * @param sql The SQL to execute.
     * @param param The replacement parameter.
     * @return An initialized JavaBean or null if there were no rows in
     * the ResultSet.
     */
    public static Object selectObject(Class type, String sql, Object param) throws SQLException {
        Object result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanHandler(type);
            logger.info("selectObject: sql=" + sql + ",param=" + param);
            result = run.query(sql, param, h);
            return result;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given SELECT SQL query and Convert the first row of
     * the ResultSet into a bean with the Class given in the parameter.
     *
     * @param type The Class of beans.
     * @param sql The SQL to execute.
     * @param params Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return An initialized JavaBean or null if there were no rows in
     * the ResultSet.
     */
    public static Object selectObject(Class type, String sql, Object[] params) throws SQLException {
        Object result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanHandler(type);
            logger.info("selectObject: sql=" + sql + ",param=" + Arrays.asList(params));
            result = run.query(sql, params, h);
            return result;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Execute an SQL SELECT query without any replacement parameters
     * and Convert the ResultSet rows into a List of beans with the
     * Class given in the parameter.
     *
     * Usage Demo:
     * <pre>
     *      ArrayList result = searchToBeanList(Test.class, sql);
     *      Iterator iterator = result.iterator();
     *      while (iterator.hasNext()) {
     *           Test test = (Test)iterator.next();
     *           System.out.println(test.getPropertyName());
     *      }
     * </pre>
     * @param type The Class that objects returned from handle() are created from.
     * @param sql The SQL to execute.
     * @return A List of beans (one for each row), never null.
     */
    public static List selectObjectList(Class type, String sql) throws SQLException {
        ArrayList result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanListHandler(type);
            logger.info("selectObjectList: sql=" + sql);
            result = (ArrayList) run.query(sql, h);
            return result;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given SELECT SQL with a single replacement parameter
     * and Convert the ResultSet rows into a List of beans with the
     * Class given in the parameter.
     *
     * @param type The Class that objects returned from handle() are created from.
     * @param sql The SQL to execute.
     * @param param The replacement parameter.
     * @return A List of beans (one for each row), never null.
     */
    public static List selectObjectList(Class type, String sql, Object param) throws SQLException {
        ArrayList result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanListHandler(type);
            logger.info("selectObjectList: sql=" + sql + ",param=" + param);
            result = (ArrayList) run.query(sql, param, h);
            return result;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given SELECT SQL query and Convert the ResultSet rows
     * into a List of beans with the Class given in the parameter.
     *
     * @param type The Class that objects returned from handle() are created from.
     * @param sql The SQL to execute.
     * @param params  Initialize the PreparedStatement's IN
     *               parameters with this array.
     * @return A List of beans (one for each row), never null.
     */
    public static List selectObjectList(Class type, String sql, Object[] params) throws SQLException {
        ArrayList result = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            ResultSetHandler h = new BeanListHandler(type);
            logger.info("selectObjectList: sql=" + sql + ",param=" + Arrays.asList(params));
            result = (ArrayList) run.query(sql, params, h);
            return result;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Execute a batch of SQL INSERT, UPDATE, or DELETE queries.
     *
     * @param sql The SQL to execute.
     * @param params An array of query replacement parameters. Each row
     * in this array is one set of batch replacement values.
     * @return The number of rows updated per statement.
     */
    public static int[] batch(String sql, Object[][] params) throws SQLException {
        int[] rows = null;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            logger.info("batch: " + sql);
            rows = run.batch(sql, params);
            return rows;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given INSERT, UPDATE, or DELETE SQL statement without any
     * replacement parameters.
     *
     * @param sql The SQL statement to execute.
     * @return The number of rows updated.
     */
    public static int update(String sql) throws SQLException {
        int rows = 0;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            logger.info("update: " + sql);
            rows = run.update(sql);
            return rows;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given INSERT, UPDATE, or DELETE SQL statement with a single
     * replacement parameter.
     *
     * @param sql The SQL statement to execute.
     * @param param The replacement parameter.
     * @return The number of rows updated.
     */
    public static int update(String sql, Object param) throws SQLException {
        int rows = 0;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            logger.info("update: " + sql + ",params=" + param);
            rows = run.update(sql, param);
            return rows;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Executes the given INSERT, UPDATE, or DELETE SQL statement.
     *
     * @param sql The SQL statement to execute.
     * @param params Initializes the PreparedStatement's IN (i.e. '?') parameters.
     * @return The number of rows updated.
     */
    public static int update(String sql, Object[] params) throws SQLException {
        int rows = 0;
        try {
            QueryRunner run = new QueryRunner(getDataSource());
            logger.info("update: " + sql + ",params=" + Arrays.asList(params));
            rows = run.update(sql, params);
            return rows;
        } catch (Exception ex) {
            throw new SQLException(ex.getMessage());
        }
    }
   
    /**
     * Get total number of records
     * @param sqlcnt sql statement used to count number of records
     *    for example: SELECT COUNT(*) AS cnt FROM demotable
     * @return total number of records
     */
    public static int getNumRows(String sql) throws SQLException {
        int numRows = 0;
        Map result = DBConn.selectMap(sql);
        if  (result.get("cnt") != null) {
            numRows = (int)((Long)result.get("cnt")).longValue();
        }
        return numRows;
    }
}

Django Filter Terbilang

// Django filter to say indonesian number

from django import template

register = template.Library()

def terbilang(value):
	value = int(value)
	bunyi = ""
	satuan = ("", "satu", "dua", "tiga", "empat", "lima", "enam","tujuh","delapan","sembilan","sepuluh", "sebelas")
	if value >= 0 and value < 12:
		bunyi = ' ' + satuan[value]
	if value >= 12 and value < 20:
		bunyi = terbilang(value%10) + ' belas'
	if value >= 20 and value < 100:
		bunyi = terbilang(value/10) + ' puluh' + terbilang(value%10)
	if value >= 100 and value < 200:
		bunyi = ' seratus' + terbilang(value - 100)
	if value >= 200 and value < 1000:
		bunyi = terbilang(value/100) + ' ratus' + terbilang(value%100)
	if value >= 1000 and value < 2000:
		bunyi = ' seribu' + terbilang(value - 1000)
	if value >= 2000 and value < 1000000:
		bunyi = terbilang(value / 1000) + ' ribu' + terbilang(value % 1000)
	if value >= 1000000 and value < 1000000000:
		bunyi = terbilang(value/1000000) + ' juta' + terbilang(value % 1000000)
	return bunyi

register.filter('terbilang', terbilang)

Open URL in Browser using Java

// this class will open new browser window

public class StartBrowser {
    public static void main(String args[]) {
        String url = "http://www.id-snippet.com";
        String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();
        try {
            if (os.indexOf( "win" ) >= 0) {
                // this doesn't support showing urls in the form of "page.html#nameLink" 
                rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
            } else if (os.indexOf( "mac" ) >= 0) {
                rt.exec( "open " + url);
            } else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) {
                // Do a best guess on unix until we get a platform independent way
                // Build a list of browsers to try, in this order.
                String[] browsers = {"epiphany", "firefox", "mozilla", 
					"konqueror", "netscape","opera","links","lynx"};

                // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
                StringBuffer cmd = new StringBuffer();
                for (int i=0; i<browsers.length; i++)
                    cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");

                rt.exec(new String[] { "sh", "-c", cmd.toString() });
            } else {
                return;
            }
        }catch (Exception e){
            return;
        }
        return;    
    }
}