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!

Sorting arrays in Bash

export PATH="$(/usr/sbin/sysctl -n user.cs_path)"

export IFS=$'\n'
#export IFS=$' \t\n'

ar1=('g h c' abc def 123)
ar2=('1 2 3' ABC ghc DEF)
ar3=('-x' '! & ?' $'a test\nsentence' $'another test\nsentence\n.' a64bitapp a32bitapp)

printf "%s\n" "${#ar1[@]}" "${#ar2[@]}" "${#ar3[@]}"  


# ar3
for ((i=0; i < "${#ar3[@]}"; i++)); do echo "${ar3[$i]}"; done | sort | nl
for ((i=0; i < "${#ar3[@]}"; i++)); do echo ${ar3[$i]}; done | sort | nl
for ((i=0; i < "${#ar3[@]}"; i++)); do echo "${ar3[$i]}" | ruby -0777 -n -e 'p $_.to_s'; done | nl
for ((i=0; i < "${#ar3[@]}"; i++)); do printf -- "${ar3[$i]}\n" | ruby -0777 -n -e 'p $_.to_s'; done | nl


# sort a single array
ar3sorted=( $(for ((i=0; i < "${#ar3[@]}"; i++)); do echo ${ar3[$i]}; done | sort) )
for ((i=0; i < "${#ar3sorted[@]}"; i++)); do echo "${ar3sorted[$i]}" | ruby -0777 -n -e 'p $_.to_s'; done | nl
for ((i=0; i < "${#ar3sorted[@]}"; i++)); do printf "%s\n" "${ar3sorted[$i]}" | ruby -0777 -n -e 'p $_.to_s'; done | nl

ar3sorted=( $(printf "%s\000\n" "${ar3[@]}" | sed -e :a -e '$!N; s/\n/NEWLINE/g; ta' | tr '\000' '\n' | sed -e 's/^NEWLINE//' | sort) )
for ((i=0; i < "${#ar3sorted[@]}"; i++)); do printf -- "${ar3sorted[$i]//NEWLINE/\n}" | ruby -0777 -n -e 'p $_.to_s'; done | nl


# sort multiple arrays; convert embedded newline characters into single spaces
ar4=( $(printf "%s\n\000" "${ar1[@]}" "${ar2[@]}" "${ar3[@]}" | tr '\n' ' ' | tr '\000' '\n' | sort) )

# sort multiple arrays; preserve embedded newline characters as NEWLINE
ar4=( $(printf "%s\000\n" "${ar1[@]}" "${ar2[@]}" "${ar3[@]}" | sed -e :a -e '$!N; s/\n/NEWLINE/g; ta' | tr '\000' '\n' | sed -e 's/^NEWLINE//' | sort) )


printf "%s\n" "${#ar4[@]}"  
printf "%s\n" "${ar4[@]}" | nl  

for ((i=0; i < "${#ar4[@]}"; i++)); do echo ${ar4[$i]//NEWLINE/\\n}; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do echo -e ${ar4[$i]//NEWLINE/\\n}; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do printf -- ${ar4[$i]//NEWLINE/\\n}"\n"; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do printf -- "${ar4[$i]//NEWLINE/\n}\n"; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do printf "%s\n" ${ar4[$i]//NEWLINE/\\n}; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do printf -- "${ar4[$i]//NEWLINE/\n}\n" | ruby -0777 -n -e 'p $_.to_s'; done | nl
for ((i=0; i < "${#ar4[@]}"; i++)); do printf "%s\n" "${ar4[$i]//NEWLINE/\n}" | ruby -0777 -n -e 'p $_.to_s'; done | nl

Switch to the login window from the command line

# cf. http://www.mactipper.com/2008/07/securely-lock-your-mac-system.html,
# http://www.macosxhints.com/article.php?story=20040724203315798 and
# http://www.apple.com/downloads/macosx/automator/lockdesktop.html

/System/Library/CoreServices/"Menu Extras"/User.menu/Contents/Resources/CGSession -suspend

/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -switchToUserID username


alias lo='/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend'

# <ctrl> + l
help bind
bind -P | grep -i c-l
bind -x '"\C-l"':'/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend'

# <esc> + l
bind -x '"\M-l"':'/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend'


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


open -a 'Keychain Access'

# go to  Keychain Access > Preferences ... > General > activate "Show Status in Menu Bar" 
# now you can use "Lock Screen" via the Keychain Access menu bar item

rmagick gem install on intel mac

sudo env ARCHFLAGS="-arch i386" gem install rmagick

rmagick test

// Check if rmagick is installed properly by running gem list. Now we are going to test if rmagick works properly. Create a file called test_rmagick.rb, and copy and paste the code below.

#!/usr/bin/env ruby -wKU

# Test if rmagick is working properly or not.
# When run, this file creates a image file 'path.gif' in the same directory.

# the sample code is from http://rmagick.rubyforge.org/portfolio3.html

require 'rubygems'
require 'rmagick' # Don't use a capital 'R'.

canvas = Magick::Image.new(240, 300,
              Magick::HatchFill.new('white','lightcyan2'))
gc = Magick::Draw.new

gc.fill('red')
gc.stroke('blue')
gc.stroke_width(2)
gc.path('M120,150 h-75 a75,75 0 1, 0 75,-75 z')
gc.fill('yellow')
gc.path('M108.5,138.5 v-75 a75,75 0 0,0 -75,75 z')
gc.draw(canvas)

canvas.write('path.gif')

Beware the trailing slash in mod_proxy_balancer (part 2)

It is a little tricky to prevent mod_proxy_balancer from adding a trailing slash.

This will redirect /MyService?wsdl to http://example.com:X0000/MyService/

    ProxyPass /MyService balancer://playlist_service_balancer

    <Proxy balancer://playlist_service_balancer>
      BalancerMember http://example.com:10000/MyService
      BalancerMember http://example.com:20000/MyService

      ProxySet lbmethod=byrequests
    </Proxy>


This will redirect /MyService?wsdl to http://example.com:X0000/MyService?wsdl
  ProxyPass /MyService balancer://playlist_service_balancer/MyService

  <Proxy balancer://playlist_service_balancer>
    BalancerMember http://example.com:10000/
    BalancerMember http://example.com:20000/

    ProxySet lbmethod=byrequests
  </Proxy>


see https://issues.apache.org/bugzilla/show_bug.cgi?id=39203

Simple perl script to merge SVN commits from a source branch to the current destination directory with a search string (Bugzilla id, for example) in the comments.

Today i have made my first PERL script!

For me it is very painful when it arrives the time to merge, into another branch, all the commits that i have done in the “trunk”. I have searched a little and did not find anything that could magically solve all my problems. I know that it’s better to create a separated branch when there are lot’s of commits, but there are some cases that a super-simple functionality can explode into a big ball of mud.

Practically the script merge all the commits of a bugzilla id to another branch. If someone knows a standard way to do this; please tell me!

The script take three inputs:

1. The starting revision ID to filter the search.
2. The SVN address of the source.
3. The search string to filter the results. Here you put your bugzilla bug id.

Commands that are executed when you launch the script:

1. Go to the directory of the destination branch.
2. To execute the script simply do:
3. svn_search_merge.pl 0 https://svn.example.com/main/trunk/ “1: “
4. Note that “1: ” is the bugzilla bug id. What happens next is:
5. svn log -r 1:HEAD https://svn.example.com/main/trunk/
6. With that command we get the log of all commits from the revision 1 to the HEAD. After it’s just matter of check if the string “1: ” is inside the log. Then we simply execute:
7. svn merge -r (ACTUAL_REVISION-1):ACTUAL_REVISION https://svn.example.com/main/trunk/

Source code of the script:
#!/usr/bin/perl

# Simple script to merge commits from a source branch to the current destination directory.
# http://mufumbo.wordpress.com/2008/05/10/simple-script-to-merge-commits-from-a-bugzilla-id/
#
# Example:
# $ cd my-branch-destination/
# $ svn_search_merge.pl 3000 https://svn.example.com/main/trunk/ "bug 673"
# Where 3000 is the starting revision and "bug 673" is the string to match in the comments.
#
use strict;
use warnings;

my $prev_revision = shift;
my $svnHost = shift;
my $searchStr = shift;

print "Starting Revision: $prev_revision\n";
print "SVN addr: $svnHost\n";
print "Search pattern: $searchStr\n";

my $buffer;
$buffer = `svn log -r $prev_revision:HEAD $svnHost`;
my $shouldContinue = "y";
LOGS: foreach my $changelog_entry (split(/----+/m, $buffer)) {
	if($changelog_entry =~ m/($searchStr)/) {
	        #my (undef, $info, undef, $comment) = split(/\n/, $changelog_entry);
	        #next unless $info =~ m/^r/;

		print "\n--------------------------------------------------";
		print $changelog_entry;
		my $revisionId = substr($changelog_entry, 2, 5);
		$revisionId =~ s/^\s+//;
		$revisionId =~ s/\s+$//;

		if ($shouldContinue ne 'a') {
			PROMPT: while(1) {
				print "\nShould continue with merge of revision '$revisionId'? (Yes,Always,Skip,Exit): ";
				$shouldContinue = <>;
				chomp($shouldContinue);

				last PROMPT if $shouldContinue eq 'y';
				last PROMPT if $shouldContinue eq 'a';
				next LOGS if $shouldContinue eq 's';
				die("User requested to stop.") if $shouldContinue eq 'e';
			}
		}
		else {
			print "\nAuto merging '$revisionId'\n";
		}

		my $pRevisionId = $revisionId-1;
		my $mergeBuffer = `svn merge -r $pRevisionId:$revisionId $svnHost`;
		print $mergeBuffer;
	}
}

Delete all _svn folders from Windows command prompt

FOR /R . %f IN (_svn) DO RD /s /q %f

Snip - extract a named element from an html file using bash

This is a primitive way of achieving the kind of data extraction that is more commonly associated with true XML for any reasonably modern html file (i.e. that it is well-formed and makes proper use of the id property). The purpose is mainly to get simple, yet fast and efficient text browsing, especially useful for quick look-ups and the like, e.g. dictionaries, thesauruses (thesauri?), encyclopedias etc. Since the data you're interested in is usually put into a specific element, text browsing is often greatly enhanced by extracting the element in question and discarding the rest. You run the script by specifying an element in the standard css way (element#id) and the file which is to be 'parsed', and the script responds by spitting out the element (and only that element) through html2text which does a really nice job of turning html code into legible console text.

EDIT: Added a quick check for the presence/absence of the element type in the line (before the grep operations) - greatly increases speed with large elements like #content on wikipedia.

#! /bin/bash

printhelp () {
echo "snip is a simple bash html cutter that works by extracting a specific element 
from an html file and feeding it to html2text. It presupposes wellformed html
and that you know the kind of element you want and it's id.

Syntax:
snip <element  type>#<element id> <file to parsed>

Example:
snip div#bodyContent /tmp/index.html
"
exit
}

quitter () {
echo "Element id not found. Quitting."; exit
}

[ "$1" = "-h" -o "$1" = "--help" -o "$1" = "" ] && printhelp

elementtype="$(echo $1 | cut -d '#' -f 1)"
id="$(echo $1 | cut -d '#' -f 2)"
htmlfile="$2"
thebegin=$(grep -nioE "id=\"$id\"" $htmlfile | cut -d ':' -f 1)
# echo $thebegin
[ -n "$thebegin" ] || quitter

sed -n ${thebegin}p "$htmlfile" | sed -re "s/^.*id=\"$id\"/<$elementtype id=\"$id\"/g" > /tmp/snipfile
sed -n $(($thebegin+1)),\$p "$htmlfile"  >> /tmp/snipfile

i=0
element=0
cat /tmp/snipfile | while read line; do
	let i++
	if [[ "$line" =~ "$elementtype" ]]; then
		elementbegincount="$(echo $line | grep -io "<$elementtype" | grep -c .)"
		elementendcount="$(echo $line | grep -io "</$elementtype" | grep -c .)"
		element=$(($element+$elementbegincount-$elementendcount))
		if [ "$element" -le 0 ]; then
			sed -n 1,${i}p /tmp/snipfile | html2text
			exit
		fi
	fi
done


As an example of how the script can be put to use, here's my Wikipedia lookup (the script above is referred to as 'snip' here):

#! /bin/bash

useragent="Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071619 Firefox/3.0.1"
if wget -q -U "$useragent" -O /tmp/wpfile "http://en.wikipedia.org/wiki/Special:Search?search=$*"; then
	clear
	echo "Page downloaded..."
	snip div#content /tmp/wpfile | less
else
	echo "No connection, sorry. Please try again."
fi

Password request dialog from the command line with AppleScript

unset -v input

#input="$(/usr/bin/osascript <<-'__HEREDOC__'
input="$(/usr/bin/osascript 2>/dev/null <<-'__HEREDOC__'
   with timeout of 300 seconds
      tell application "Finder"
--      tell application "System Events"
         activate
         set Input to display dialog "Please enter your password:" \
            with title "Password" \
            with icon caution \
            default answer "" \
            buttons {"Cancel", "OK"} \
            default button 2 \
            with hidden answer \
            giving up after 295
         return text returned of Input as string
      end tell
   end timeout
__HEREDOC__
)"

printf "%s\n" "${input}"


open -a 'Script Editor'

# copy & paste the following snippet into Script Editor 

with timeout of 300 seconds
	tell application "Finder"
		activate
		set Input to display dialog "Please enter your password:" with title "Password" with icon caution default answer "" buttons {"Cancel", "OK"} default button 2 giving up after 295 with hidden answer
		return text returned of Input as string
	end tell
end timeout


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


unset -v input name
#export name="$(/usr/bin/logname)"
export name="$(/usr/bin/whoami)"

input="$(/usr/bin/osascript 2>/dev/null <<-__HEREDOC__
   with timeout of 300 seconds
      tell application "Finder"
--      tell application "System Events"
         activate
         set my_name to "${name}"
         set my_pass to display dialog "Enter password for " & quoted form of my_name \
            with title "Login Window" \
            with icon note \
            default answer "" \
            buttons {"Cancel", "OK"} \
            default button 2 \
            with hidden answer \
            giving up after 295
            return text returned of my_pass as string
      end tell
   end timeout
__HEREDOC__
)"


printf "%s\n" "${input}"

Login window from the command line with Pashua

export PATH="/usr/bin:/bin:/usr/sbin:/sbin"
export IFS=$' \t\n'

mkdir -p ~/Applications

ls -ld ~/Applications
stat -x ~/Applications

cd ~/Applications
curl -L -O http://www.bluem.net/files/Pashua.dmg
hdiutil mount Pashua.dmg
cp -R /Volumes/Pashua ~/Applications/Pashua
hdiutil unmount /Volumes/Pashua

cd ~/Applications/Pashua/Examples
cp -p example.sh example.sh.orig   # backup


# some in-place text editing commands to modify ~/Applications/Pashua/Examples/example.sh
# cf. http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed

export FILE="${HOME}/Applications/Pashua/Examples/example.sh"

# replace #!/bin/sh with #!/bin/bash
/bin/ed -s "${FILE}" <<< $'1,1s|bin/sh|bin/bash|\nw'

# to set the encoding to UTF-8 we add: set -- test utf8
/bin/ed -s "${FILE}" <<< $',s|\(.*Manage encoding.*\)|set -- test utf8 # set $2 to "utf8"\\\n\\\n\\1|\nw'

# delete all lines after first regex match /conf="/
/bin/ed -s "${FILE}" <<< $'/conf="/;$d\nw'


# add the following configuration

/bin/cat >> "${FILE}" <<-'EOF'

conf="

# Set transparency: 0 is transparent, 1 is opaque
*.transparency=0.95

# Set window title
*.title = Login Window

*.x = 550
*.y = 300
*.autoclosetime = 300

name.type = textfield
name.label = Please enter your name:
name.width = 280
name.x = 0
name.y = 110

password.type = password
password.label = Please enter your password:
password.width = 280
password.x = 0          
password.y = 45        

# Add a cancel button with default label
cb.type = cancelbutton

";   # end conf


pashua_run "$conf"
#pashua_run "$conf" "utf8"   # alternative to "set -- test utf8" above


if [[ ${cb} -ne 0 ]]; then echo 'Login cancelled!'; exit 1; fi

printf "%s\n" "name = ${name}"

printf "%s\n" "${name}" | ruby -n -e 'p $_.to_s'

# the following command requires #!/bin/bash
# cf. http://www.lugbz.org/pipermail/lugbz-list/2006-December/016360.html
/bin/ed -s <((printf "%s\n" "${name}")) <<< $',l'   

printf "%s\n" "password = ${password}"
printf "%s\n" "cb = ${cb}"

#printf "%s\n" "${password}" | /usr/bin/sudo -S /bin/ls | /usr/bin/head -n 5

/sbin/md5 -qs "${password}"

EOF


# run the script
~/Applications/Pashua/Examples/example.sh