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!

Select a random record from a MySQL database

// description of your code here
I needed to select 5 random records from a MySQL database and found this little squib of code from http://peterfreitag.com/item/466.cfm

SELECT column FROM table ORDER BY RAND() LIMIT 5

kv - launch Keyboard Viewer

locate -i *keyboardviewerserver

alias kv='/usr/bin/open /System/Library/Components/KeyboardViewer.component/Contents/SharedSupport/KeyboardViewerServer.app'

kv


# cf. Accented letters and other symbols on the Mac,
# http://mac4translators.blogspot.com/2008/08/accented-letters-and-other-symbols-on.html

[cmd]     #  hold the command key
[alt]
[alt][shift]

Excerpt from article

// Useful form if you want to know how to pull an excerpt of an article onto an existing article/webpage

<h1><txp:title /></h1>
<txp:excerpt />
				
<p class="moreinfo"><txp:permlink>##more_info##</txp:permlink></p>

sitemap

// Sitemap Form that will show the Section title and the list of articles for that section.

<txp:if_article_section name="sitemap">

<txp:else />
<txp:if_different>


   </ul><h2><txp:section title="1" /></h2><ul>

</txp:if_different>

   <li><txp:permlink><txp:title /></txp:permlink></li> 

</txp:if_article_section>


// Sitemap Page template looks like this;

     <div id="content">
<h1>Sitemap</h1>
<ul style="display:none;"><txp:article_custom limit="99999" form="sitemap" sort="section asc,Posted asc" /></ul>	

    </div><!-- content -->	

pcregrep - UTF-8 aware grep replacement

# we first have to download, compile & install the PCRE library, cf. http://www.pcre.org/pcre.txt
# requirement: Xcode, http://developer.apple.com/tools/xcode/index.html

cd ~/Desktop
/usr/bin/curl -L -O http://downloads.sourceforge.net/pcre/pcre-7.7.tar.gz
/usr/bin/tar -xzf pcre-7.7.tar.gz
cd pcre-7.7
./configure --help
./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties
# for Intel Macs, see http://hivelogic.com/articles/2005/12/ruby_rails_lighttpd_mysql_tiger
#./configure --prefix=/usr/local --enable-utf8 --enable-unicode-properties CFLAGS=-O1
/usr/bin/make
/usr/bin/sudo /usr/bin/make install 


ls -l /usr/local/bin/pcregrep
stat -x /usr/local/bin/pcregrep

pcregrep --version
pcregrep --help
pcregrep --help | pcregrep -i 'utf-?8'
pcregrep --help | pcregrep -i multiline

man pcregrep
man pcrepattern
man pcretest
man perlretut

man pcregrep | less -p utf-8
man pcregrep | less -p multiline
man perlretut | less -p 'single line and multi'

open /usr/local/share/doc/pcre/html/pcregrep.html


# check if character set encoding of Terminal.app is set to UTF-8
if [[ "$(/usr/bin/defaults read com.apple.Terminal StringEncoding)" != "4" ]]; then 
   echo 'Terminal.app does not use UTF-8 character set encoding!'
   exit 1
fi


utf8str=$'caf\303\251'

printf $utf8str | /usr/bin/egrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -o '.'
printf $utf8str | /usr/local/bin/pcregrep -ou '.'     # UTF-8 aware

printf $utf8str | /usr/bin/egrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -o '.' | wc -l
printf $utf8str | /usr/local/bin/pcregrep -ou '.' | wc -l     # UTF-8 aware

Tapping the Bash command line history

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


help fc
help history
help bind
help set
help shopt
open /usr/share/doc/bash/builtins.pdf


cp -ip ~/.bashrc ~/.bashrc.orig
cp -ip ~/.inputrc ~/.inputrc.orig
cp -ip ~/.bash_history ~/.bash_history.bak

cp -ip ~/.bashrc{,.orig}  # shortcut version
cp -ip ~/.inputrc{,.orig}
cp -ip ~/.bash_history{,.bak}


history
history | head -n 3
history | tail -n 1
history | egrep 5
history | egrep '^[[:space:]]*5'
history | egrep -m 1 '^[[:space:]]*5'
history | egrep '^[[:space:]]*5[[:space:]]+'

fc
fc -e nano
fc -l | nl
fc -ln | sed 's/^[[:space:]]*//'
fc -l 0
fc -l 1 -1
#exec /bin/bash     # ... in case of "fc: history specification out of range"
#source ~/.bash_login
fc -l -1
fc -l -5
fc -l 5 "cd "
fc -l -r 5 "cd "
fc -l -5 | grep cd | awk '{print $1}'
fc -s cd     # execute last cd command
fc -e vim 3
fc -e nano "cd "


set +o history   # disable adding commands to history list
set -o history   # enable adding commands to history list


/bin/cat >> ~/.bashrc <<-'EOF'

bind Space:magic-space     # enable option to expand & edit a command before running it by entering a [space]
#shopt -s histverify     # expand & edit a command before running it by entering [return]
shopt -s cmdhist
shopt -s histappend

# suppress history recording for the specified commands including commands beginning with a space
export HISTIGNORE="&:[ \t]*:ls:[bf]g:history*:clear:exit"

#export HISTCONTROL=ignorespace
#export HISTCONTROL=ignoredups
#export HISTCONTROL=ignoreboth

#PROMPT_COMMAND="history -a; ${PROMPT_COMMAND}"

EOF

source ~/.bashrc


/bin/cat >> ~/.inputrc <<-'EOF'

"\033[3~": delete-char             # get a proper forward delete key in Terminal.app
"\e[A": history-search-backward    # search command history backward with up arrow key
"\e[B": history-search-forward     # search command history forward with down arrow key

set show-all-if-ambiguous on        # enable tab completion with a single tab
set mark-symlinked-directories on
set completion-ignore-case on
#set visible-stats on
#set bell-style visible

#$if Bash   # same effect as "bind Space:magic-space" in ~/.bashrc
#  Space: magic-space
#$endif

EOF


exec /bin/bash    # reinitialize ~/.inputrc
source ~/.bash_login ~/.bashrc


help bind
bind -l | less
bind -P | less
bind -p | less    
bind -V | less
bind -v | less


# insert the last word of the previous command line
echo hello world1
echo hello world1 and world2
echo hello world1 and world2 and world3
echo hello
echo

[esc-.]     # press the esc-. key sequence repeatedly to iterate through the history list
[ctrl-u]    # clear the current command line
echo !$
printf "%s\n" $_


!1[space]            # expand the first command in the history list without executing
!12[space]           # expand command no. 12
sudo !![space]       # expand last command
!-4[space]           # expand the fourth last command
!cd[space]           # expand the last cd command
!?world?[space]      # expand the last command containing the specified word
!$[space]            # last word of the preceding command line
!:1[space]           # first argument of the preceding command
!-1:1[space]         # same
!-1:1-[space]        # all arguments of the previous command except the last on
!-1:1*[space]        # all arguments of the previous command
!-1:1-$[space]       # same
!-2:3[space]         # third argument from the command before the last one

abc def !#[space]     # double the entire command line typed so far

cd ~/Desktop
!cd:p
!cd[space]
[ctrl-u]
!?cd?:p                 # make the last cd command the last command in the history list and print it without executing
history | tail -n 1

cd[up_key]    
cp[up_key]              # hit the up & down arrow keys again and again to iterate through the commands
cp[down_key]           

[ctrl-r]cp              # press ctrl-r repeatedly to iterate through the previous commands
[esc] or [ctrl-j]       # quit searching with ctrl-r
[ctrl-k] + [ctrl-u]     # quit searching with ctrl-r and clear the command line
[ctrl-y]                # recalls the last string removed by ctrl-k or ctrl-u


# cf. http://nubyonrails.com/articles/2007/05/26/useful-shell-shortcuts
cp foo !#^.bak[space]            # !#^ refers to the first word after the command
cp -i foo !#^.bak[space]    
cp -p -i foo !#^.bak[space]    
cp !#$.bak[space] 
cp foo !#$.bak[space]            # !#$ refers to the preceding word
cp -i foo !#$.bak[space]    
echo abc def !#$.bak[space]
echo abc def !#$.bak ghi jkl !#$.foo mno[space]


# tab completion
#[tab]  # all available commands
#ds[tab]  # all available commands beginning with ds
#cd ~/Desktop
#cd ~/Des[tab]
#$[tab]  # all set system variables
#~[tab]  # users
#*[tab] 
#=[tab]
#/[tab]

Ubuntu and writing Java servlets

Kind of a strange, and I'm sure this wouldn't have happened on any other distribution of Linux, but I spent forever looking through blogs, message boards, and all manner of other places looking for an answer to this question.

The problem was with this little itty bitty smidge of code:
/**
 * hello.java
 */
import javax.servlet.*;

class HelloWorld
{
        public static void main(String[] args)
        {
                System.out.println("Hello World!");
        }
}


Everytime I wanted to compile this, I got something like "Could not find javax.servlet. blah blah" So, eventually, I just pulled an apt-cache search j2 (for j2ee) and saw an entry for libservlet2.4-java. Hmmmmm, what the heck is that I wondered. I installed it and went to the Ubuntu site to look at what files were installed and sure enough:

/usr/share/java/jsp-api-2.0.jar
/usr/share/java/jsp-api.jar
/usr/share/java/servlet-api-2.4.jar
/usr/share/java/servlet-api.jar


Perfect! I added these paths to my CLASSPATH variable in my .bashrc and whamo, I'm in business and flaunting my little HelloWorld.class file all around town.

I hope this helps someone else!

Create Javascript Object

Use objects for lists

var obj = {
"elem": document.getElementById('id'),
"description": "here's a description"
};

Edit multiple lines on the command line

export EDITOR=nano
[ctrl-x-e]   # press ctrl-x-e keys


help fc
open /usr/share/doc/bash/builtins.pdf

fc     # edit last command in $EDITOR
fc -l 3 5  
fc 4     # edit command no. 4
fc -2
fc "cd "     # edit last cd command

fc -e vim     # edit last command in vim
fc -e vim "cd "
fc -e vim 4    

Removing <?xml version="1.0"?> from the output of XSLTProcessor->transformToXml()

Just add this as a top level element in your XSL document.

<xsl:output method="html" />


Thanks to this post on php.net for the answer:
http://us3.php.net/manual/en/xsltprocessor.transformtoxml.php#80887