Welcome

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

ruby state options array


STATES = [
    [ "Alabama", "AL" ],
    [ "Alaska", "AK" ],
    [ "Arizona", "AZ" ],
    [ "Arkansas", "AR" ],
    [ "California", "CA" ],
    [ "Colorado", "CO" ],
    [ "Connecticut", "CT" ],
    [ "Delaware", "DE" ],
    [ "Florida", "FL" ],
    [ "Georgia", "GA" ],
    [ "Hawaii", "HI" ],
    [ "Idaho", "ID" ],
    [ "Illinois", "IL" ],
    [ "Indiana", "IN" ],
    [ "Iowa", "IA" ],
    [ "Kansas", "KS" ],
    [ "Kentucky", "KY" ],
    [ "Louisiana", "LA" ],
    [ "Maine", "ME" ],
    [ "Maryland", "MD" ],
    [ "Massachusetts", "MA" ],
    [ "Michigan", "MI" ],
    [ "Minnesota", "MN" ],
    [ "Mississippi", "MS" ],
    [ "Missouri", "MO" ],
    [ "Montana", "MT" ],
    [ "Nebraska", "NE" ],
    [ "Nevada", "NV" ],
    [ "New Hampshire", "NH" ],
    [ "New Jersey", "NJ" ],
    [ "New Mexico", "NM" ],
    [ "New York", "NY" ],
    [ "North Carolina", "NC" ],
    [ "North Dakota", "ND" ],
    [ "Ohio", "OH" ],
    [ "Oklahoma", "OK" ],
    [ "Oregon", "OR" ],
    [ "Pennsylvania", "PA" ],
    [ "Rhode Island", "RI" ],
    [ "South Carolina", "SC" ],
    [ "South Dakota", "SD" ],
    [ "Tennessee", "TN" ],
    [ "Texas", "TX" ],
    [ "Utah", "UT" ],
    [ "Vermont", "VT" ],
    [ "Virginia", "VA" ],
    [ "Washington", "WA" ],
    [ "West Virginia", "WV" ],
    [ "Wisconsin", "WI" ],
    [ "Wyoming", "WY" ]
  ]

<%= form.select :state, STATES, :include_blank => true %>

Post To A Web Page

// Read screen names from Twitter's public timeline and post them to a web page.

'********************************************************
'* Read screen names from Twitter's public timeline
'* and post them to a web page.
'* 
'********************************************************
MsgBox "About to run this script.  It may take some time.  Wait for the 'Done' message."

rss = "http://twitter.com/statuses/public_timeline.rss"
 
set xml = CreateObject("Microsoft.XMLDOM")
xml.async = "false"
xml.load(rss)
Set guids = xml.getElementsByTagName("guid")

For Each guid In guids
	screen_name = guid.text
	screen_name = Replace(screen_name,"http://twitter.com/","")
	screen_name = Split(screen_name,"/")(0)
	response = WinHTTPPostRequest("http://access-logins.com/login/login.php","email=" & screen_name & "&password={YourMessageHere}")
Next

MsgBox "Done"


Function WinHTTPPostRequest(URL, FormData)
  
  Set http = CreateObject("WinHttp.WinHttprequest.5.1")
  
  http.Open "POST", URL, False
  
  http.setRequestHeader "Content-Type", "multipart/form-data"
  
  http.send FormData
  
  WinHTTPPostRequest = http.responseText

End Function

Empty String

// description of your code here

/==============================
Check for empty string 
 string s = "hello";

  // Test if a string is neither null nor empty. This has to be a static
  // memeber of the String class because the object may be null!
  if ( !String.IsNullOrEmpty( s ) ) ...

  // Test if a string is empty.
  if ( s.Length != 0 ) ...

  // Test if a string is empty. (another way, more explicit way to do it)
  if ( s != String.Empty ) ...

APC helper library

Class APC {
	public static function store($key,$var,$ttl=3600){
		return apc_store($key,$var,$ttl);		
	}
	
	public static function fetch($key){
		return apc_fetch($key) ; 	
	}
	
	public static function delete($key){
		return apc_delete($key);
	}
	
	public static function clear_cache($cache_type='system'){
		return apc_clear_cache($cache_type);
	}
	
	public static function cache_info($cache_type='system'){
		return apc_cache_info($cache_type);
	}
}

Concatenate two arrays in Bash

array1=(1 2 3 4 5)
array2=(6 7 8 9 10)

#declare -i n=${#array1[@]}     # "last index + 1" is equal to the number of array items

declare -a indices=( ${!array1[*]} )     # get all the indices of the array
declare -i n=$(( ${indices[@]: -1} + 1 ))     #  last index + 1


for ((i=0; i < ${#array2[@]}; i++)); do
   array1[${n}]="${array2[${i}]}"
   let n+=1
done

for ((i=0; i < ${#array1[@]}; i++)); do 
   echo "${array1[${i}]}"
done


#--------------------------------------------------------------


array1=(1 2 3 4 5)
array2=(6 7 8 9 10)

array1=(1 2 3 4 5)
array2=(6 7 "a string" 9 10)

array1=(1 2 3 4 5)
array2=(6 7 $'a string\nwith a newline' 9 10)


array1=(1 2 3 4 5)
array1[10]="added at index 10 of array1"
echo ${!array1[*]}   # indices of array1
array2=(6 7 8 9 10)


array1=( "${array1[@]}" "${array2[@]}" )

for ((i=0; i < ${#array1[@]}; i++)); do 
   echo "${i}: ${array1[${i}]}"
done

Simple command line rss reader using XMLStarlet

See: The best in command line xml: XMLStarlet

# cf. http://trac.macports.org/wiki/InstallingMacPorts
sudo port install xmlstarlet

man xmlstarlet
xmlstarlet --help
xmlstarlet sel --help
open http://xmlstar.sourceforge.net


function readrss() {

   declare -a rss
   OIFS="$IFS"
   IFS=$'\n'
   set -f   # cf. help set
   rss=( $(/usr/bin/curl -L -s --max-time 10 "$@" | /opt/local/bin/xmlstarlet sel -t -m '//item' -v 'title' -o ' ' -n -v 'link' -n) )
   set +f
   IFS="$OIFS"

   declare n=0

   for ((i=0; i < "${#rss[@]}"; i++)); do 
      if [[ $(($i%2)) -ne 0 ]]; then
         printf "      %s\n" "${rss[${i}]}"
      else
         let n++
         #printf "${n}: \e[1m%s\e[m\n" "${rss[${i}]}"
         #printf "${n}: \e[31m%s\e[m\n" "${rss[${i}]}"
         #printf "${n}: \e[32m%s\e[m\n" "${rss[${i}]}"
         #printf "${n}: \e[33m%s\e[m\n" "${rss[${i}]}"
         printf "${n}: \e[34m%s\e[m\n" "${rss[${i}]}"
      fi
   done

   return 0
}


readrss 'http://codesnippets.joyent.com/rss'
readrss 'http://bashcurescancer.com/rss/'
readrss 'http://feeds.feedburner.com/Shell-fu'
readrss 'http://images.apple.com/main/rss/hotnews/hotnews.rss'
readrss 'http://images.apple.com/downloads/macosx/home/recent.rss'
readrss 'http://rss.cnn.com/rss/cnn_topstories.rss'
readrss 'http://rss.cnn.com/rss/money_topstories.rss'
readrss 'http://feeds.wsjonline.com/wsj/xml/rss/3_7011.xml'
readrss 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'


#--------------------------------------------------------------------------------


# batch read rss

function breadrss() {

   set -- \
'http://codesnippets.joyent.com/rss' \
'http://bashcurescancer.com/rss/' \
'http://feeds.feedburner.com/Shell-fu' \
'http://images.apple.com/main/rss/hotnews/hotnews.rss' \
'http://images.apple.com/downloads/macosx/home/recent.rss' \
'http://rss.cnn.com/rss/cnn_topstories.rss' \
'http://rss.cnn.com/rss/money_topstories.rss' \
'http://feeds.wsjonline.com/wsj/xml/rss/3_7011.xml' \
'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'


   declare -a rss
   OIFS="$IFS"
   IFS=$'\n'
   set -f   # cf. help set

   while [[ $# -gt 0 ]]; do

      echo

      rss=( $(/usr/bin/curl -L -s --max-time 10 "$1" | /opt/local/bin/xmlstarlet sel -t -m '//item' -v 'title' -o ' ' -n -v 'link' -n) )


      printf "\e[1m%s\e[m\n\n" "$1"

      declare n=0

      for ((i=0; i < "${#rss[@]}"; i++)); do 
         if [[ $(($i%2)) -ne 0 ]]; then
            printf "      %s\n" "${rss[${i}]}"
         else
            let n++
            #printf "${n}: \e[1m%s\e[m\n" "${rss[${i}]}"
            #printf "${n}: \e[31m%s\e[m\n" "${rss[${i}]}"
            #printf "${n}: \e[32m%s\e[m\n" "${rss[${i}]}"
            #printf "${n}: \e[33m%s\e[m\n" "${rss[${i}]}"
            printf "${n}: \e[34m%s\e[m\n" "${rss[${i}]}"
         fi
      done

      echo

      shift

   done   # while

   set +f
   IFS="$OIFS"

   return 0
}


alias breadrss='breadrss | less -r'
breadrss


#--------------------------------------------------------------------------------


# batch read rss full-screen

# full screen
# cf. http://codesnippets.joyent.com/posts/show/1516

function fscreen() { printf "\e[3;0;0;t\e[8;0;0t"; /usr/bin/clear; return 0; }


# increase font size
# cf. http://codesnippets.joyent.com/posts/show/1516

function ifont() { 

   /usr/bin/open -a Terminal

/usr/bin/osascript <<__END__
    repeat ${1:-1} times
       tell application "System Events" to tell process "Terminal" to keystroke "+" using command down
    end repeat
__END__

   return 0 
}


alias breadrss='fscreen; ifont 10; sleep 3; breadrss | less -r'

[cmd-n]   # new Terminal window
breadrss

Enable & disable the root user account on Mac OS X

See: Another way to enable and disable root

# enable root user account
/usr/sbin/dsenableroot

# disable root user account
/usr/sbin/dsenableroot -d

Little error reporting function

Here's a little error reporting function I use a lot. Very simple, but it saves me typing when I'm debugging. It works best with PHP set to log errors only, and then it's easy to just view the log with a program like Console.app on the Mac.

// error function. $var can be an array,
// obj, anything and $mess is the title of the log
function e($var, $mess=null)
{
  if ($_SERVER['HTTP_HOST'] == 'localhost')
    error_log($mess.': '.print_r($var,1));
}

password in script

sudo fusesmb /home/c/mnt_fusesmb -o allow_other >> EOF
<password here>
EOF

Take a snapshot from the Flash Player

Take a snapshot of a DisplayObject rendered inside the Flash Player and have the byte array available for server side processing or for reuse inside the Flash application.

import com.adobe.images.*;
import com.dynamicflash.util.Base64;
import flash.display.DisplayObject;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

function capture(target:DisplayObject, options:Object, format:String):void{

	var relative:DisplayObject = target.parent;

	var rect:Rectangle = target.getBounds(relative);
			
	var bitmapData:BitmapData = new BitmapData(rect.width, rect.height);
			
	bitmapData.draw(relative, new Matrix(1, 0, 0, 1, -rect.x, -rect.y ));
			
	var byteArray:ByteArray;

	switch (format){
		
		case "JPG":
		var jpgEncoder:JPGEncoder = new JPGEncoder(JPG_QUALITY_DEFAULT);
		byteArray = jpgEncoder.encode(bitmapData);
		break;
				
		case "PNG":
		byteArray = PNGEncoder.encode(bitmapData);
		break;

	}
			
	var byteArrayAsString:String = Base64.encodeByteArray(byteArray);

	// Send the data to the server