Snippets
Convert decimal to octal, hex, or base-36. And vice-versa
function dec2string ($decimal, $base)
{
$base = (int)$base;
if ($base < 2 | $base > 36 | $base == 10)
{
return FALSE;
}
// maximum character string is 36 characters
$charset = '0123456789abcdefghijklmnopqrstuvwxyz';
// strip off excess characters (anything beyond $base)
$charset = substr($charset, 0, $base);
if (!ereg('(^[0-9]{1,16}$)', trim($decimal))) {
return FALSE;
}
$string = '';
do
{
// get remainder after dividing by BASE
$remainder = bcmod($decimal, $base);
$char = substr($charset, $remainder, 1); // get CHAR from array
$string = $char . $string;
//$decimal = ($decimal - $remainder) / $base;
$decimal = bcdiv(bcsub($decimal, $remainder), $base);
}
while ($decimal > 0);
return $string;
}
function string2dec($string, $base)
{
$decimal = 0;
$base = (int)$base;
if ($base < 2 | $base > 36 | $base == 10) {
return FALSE;
}
// maximum character string is 36 characters
$charset = '0123456789abcdefghijklmnopqrstuvwxyz';
// strip off excess characters (anything beyond $base)
$charset = substr($charset, 0, $base);
$string = trim($string);
if (!$string)
{
return FALSE;
}
do
{
$char = substr($string, 0, 1); // extract leading character
$string = substr($string, 1); // drop leading character
$pos = strpos($charset, $char); // get offset in $charset
if ($pos === FALSE)
{
return FALSE;
}
//$decimal = ($decimal * $base) + $pos;
$decimal = bcadd(bcmul($decimal, $base), $pos);
}
while($string);
return $decimal;
}
Posted: 2008.03.20 14:10 |
Language: php |
By: ferdhie |
0 comments
This function will fetch URL from Pipes and execute callback
function getData(url, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
var rnd = Math.random().toString();
var callbackName = 'jsonp' + rnd.substr(rnd.indexOf('.')+1);
window[callbackName] = function(tmp) {
callback(tmp);
window[callbackName] = undefined;
try { delete window[callbackName]; } catch(e){}
}
script.src = url + '&_callback=' + callbackName;
script.onload = function(){ head.removeChild(script); };
head.appendChild(script);
}
// example: fetch flickr streams from pipes
getData('http://pipes.yahoo.com/pipes/pipe.run?_id=7114ce50d2699c7fe2d920a8d2aa17f0&_render=json',
function(data) { alert(data) });
Posted: 2008.03.12 10:09 |
Language: javascript |
By: ferdhie |
0 comments
CrossBrowser way to add event on javascript (Originally by elang526)
function addEvent(event, func) {
if (window.attachEvent) {
window.attachEvent('on'+event, func);
} else if (window.addEventListener) {
window.addEventListener(event, func, false);
} else {
var __old = window['on' + event] || function(){};
window['on' + event] = function() { func(); __old(); };
}
}
// example
addEvent('load', function() { alert('a') });
Posted: 2008.03.11 11:34 |
Language: javascript |
By: ferdhie |
0 comments
This script will do the automatic SSH login setup
#!/usr/local/bin/bash
function usage()
{
echo ""
echo "authorizes a host for automatic SSH use by sending your key to the remote host ..."
echo "usage: $0 remote_host_to_authorize [username:=defaults to current username]"
echo ""
}
function cleanup()
{
if [ -f $TEMP_PUB_KEY_XFER ]
then
rm $TEMP_PUB_KEY_XFER
fi
}
function exit_on_error()
{
cleanup
exit 1
}
if [ $# -lt 1 -o "$1" = "-h" -o "$1" = "--help" ]
then
usage
exit 0
fi
PUB_KEY=~/.ssh/id_dsa.pub
if [ $# -eq 2 ]; then
USER=$2
else
USER=`whoami`
fi
HOST_TO_AUTH=$1
TEMP_PUB_KEY_XFER=/tmp/$USER"_TEMP_KEY"
echo "checking for $PUB_KEY ..."
if [ ! -f $PUB_KEY ]; then
echo "generating your dsa public key (leave passphrase blank and save to $PUB_KEY when prompted) ..."
ssh-keygen -t dsa
if [ $? -ne 0 ]; then
echo "ssh-keygen failed"
exit_on_error
fi
fi
echo "OK"
echo "for the following commands you will be asked to supply your password for $HOST_TO_AUTH:"
echo "copying a temp pub key to $HOST_TO_AUTH ..."
cat $PUB_KEY > $TEMP_PUB_KEY_XFER
chmod 700 $TEMP_PUB_KEY_XFER
echo "OK"
remote_key=`basename $TEMP_PUB_KEY_XFER`
scp $TEMP_PUB_KEY_XFER $USER@$HOST_TO_AUTH:~/$remote_key
if [ $? -ne 0 ]; then
echo "scp failed"
exit_on_error
fi
echo "authorizing $HOST_TO_AUTH for automatic SSH use ..."
ssh $USER@$HOST_TO_AUTH "cat ~/$remote_key >> ~/.ssh/authorized_keys; rm ~/$remote_key"
if [ $? -ne 0 ]; then
echo "ssh failed"
exit_on_error
fi
echo "OK"
cleanup
echo "authorization successful! you can now login automatically to $HOST_TO_AUTH"
exit 0
Posted: 2008.03.06 14:20 |
Language: bash |
By: ferdhie |
1 comments
Kelas untuk mempermudah JDBC dengan Commons DBUtils
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;
/**
*
* @author ferdhie
*/
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/MyJDBC";
/**
* 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) {
&nbs
Posted: 2008.03.03 10:34 |
Language: java |
By: ferdhie |
0 comments
Will list open ports and the application opening that port.
netstat -abon
Posted: 2008.02.01 14:42 |
Language: dos |
By: ferdhie |
0 comments
InnoDB is a fast table for writing but slow when you use SELECT COUNT(*) queries; This is how we can optimize it.
<?php
// Connect to database
// ...
$Result = @mysql_query("show databases");
$cnt = @mysql_num_rows($Result);
while ($cnt)
{
$cnt--;
if (!($Row = @mysql_fetch_array($Result)))
{
continue;
}
$database = $Row[0];
$dbname = $database;
echo "Adding counters to [$database]rn";
flush();
if (!@mysql_select_db("$database")) continue;
$Result1 = @mysql_query("SHOW TABLES FROM $database");
$cnt1 = @mysql_num_rows($Result1);
while ($cnt1)
{
$cnt1--;
if (!($Row1 = @mysql_fetch_array($Result1)))
{
continue;
}
$tablename = $Row1[0];
// 'storage' is the table we use to hold all the counters
if (Strcasecmp($tablename,'storage')==0) continue;
// Insert counters record for this table into our 'storage' table
@mysql_query("INSERT INTO storage (name) ".
" values ('$tablename')");
// Count
$R = @mysql_query("select count(*) from $database.$tablename");
$Q = @mysql_fetch_row($R);
// Update counter
@mysql_query("update $database.storage set cnt_records='".$Q[0]."' where name='$tablename'");
// Create triggers
@mysql_query("create trigger $tablename after insert on $tablename for each row begin update storage set cnt_records=cnt_records+1 where name='$tablename'; end;");
@mysql_query("create trigger $tablename after delete on $tablename for each row begin update storage set cnt_records=cnt_records-1 where name='$tablename'; end;");
}
}
?>
Posted: 2008.01.23 11:44 |
Language: php |
By: ferdhie |
0 comments
Java joining strings
public static String join( String token, String[] strings )
{
StringBuffer sb = new StringBuffer();
for( int x = 0; x < ( strings.length - 1 ); x++ )
{
sb.append( strings[x] );
sb.append( token );
}
sb.append( strings[ strings.length - 1 ] );
return( sb.toString() );
}
Posted: 2008.01.17 14:58 |
Language: java5 |
By: ferdhie |
0 comments
adding rules to iptables
iptables -A [CHANNEL] -p tcp --dport 80 -j ACCEPT
Posted: 2008.01.02 13:14 |
Language: bash |
By: ferdhie |
0 comments
dump http request and response using perl and tcpdump
#!/usr/bin/perl
use Socket;
$|=1;
open (STDIN,"/usr/sbin/tcpdump -lnx -s 1024 dst port 80 |");
while (<>) {
if (/^S/) {
while ($packet=~/(GET|POST|WWW-Authenticate|Authorization).+/g) {
$time = localtime;
$iaddr = inet_aton($client);
$client_name = gethostbyaddr($iaddr, AF_INET);
print "[$time] $client ($client_name) -> $hostt$&n";
}
undef $client; undef $host; undef $packet;
($client,$host) = /(d+.d+.d+.d+).+ > (d+.d+.d+.d+)/
if /P d+:d+((d+))/ && $1 > 0;
}
next unless $client && $host;
s/s+//;
s/([0-9a-fA-F]{2})s?/chr(hex($1))/eg;
tr/x1F-x7Ern//cd;
s/0x.?: //g;
$packet .= $_;
}
Posted: 2007.12.18 18:25 |
Language: perl |
By: ferdhie |
0 comments
1 | 2 | 3 | 4 | 5 | 6 | 7
| next