Code Snippets

Here's a random collection of code fragments that may be useful or interesting or spark some thought or start a revolution...



Spinner Progress Indicator

  • It took me a little while to figure out the magic combination of the cursor array and ternary operator. My main goal was to make it as self contained and efficient as possible. I am importing millions of records, and didn't want to waste CPU time on computing modulus on some huge $i value. :)
  • However I wanted some way to know that each of the millions of records was being imported. A "progress indicator" if you will. One that quickly illustrates that "yes, something is still churning away, even though it might be taking minutes, hours or *gasp* days to process".
  • I didn't want to print out a single "." for each one, as that still just takes up pages and pages of scrolling as they whiz by.
  • I didn't want to use the new record ID, as that takes up a wasted SQL call to get LAST_INSERT_ID().
  • So a spinner was a likely candidate. It sits in place and rotates 1/8 turn for each record inserted. As errors occur, I can spit them out where I'm sure to see them (or log them to an error log) and they won't get lost in a maxed out scroll-back buffer.
  • Plus it looks freakin' slick as hell and gives the appearance that I am smarter than I am. *grin*


#!/usr/bin/php -q
<?php
define
("ESC"27);
printf"%c[2J"ESC ); //clear screen

//note how the "-" is at [1], not [0]
$cursorArray = array("/","-","\\","|","/","-","\\","|"); 

echo 
"Processing: ";

printf"%c7"ESC ); //save cursor position

for ($count 1$count <= 30$count++) 
{
    
//note that $i is all self contained.
    //restore cursor position and print
    
printf("%c8(".$cursorArray[ (($i++ > 7) ? ($i 1) : ($i 8)) ].") %02d"ESC$count);
    
sleep(1);
}

echo 
"\nDone.\n";
?>


Ruby

I'm just learning (i.e. struggling) with Ruby. I *really* want to learn it, but it's just so foreign.


# this is a little trick that Rails uses to set this file's path into the search path
# in this case it pushes the current file's directory onto the $LOAD_PATH stack ($:)

$:.unshift File.expand_path(File.dirname(__FILE__) + "/..")
					


Gentoo, Portage, Emerges

I've been a fan of Gentoo Linux for about 4 years or so now (although I am seriously considering switching to Ubuntu).


# This is really handy for any kind of massive emerge where some files might fail.
# It will just keep churning through the list of files until the last one,
# no more starting a big emerge at night only to find out portage puked on the second
# one after you went to bed! 
# You could use 'world' or 'gnome' or 'kde' or whatever instead of 'system' of course.

emerge -avu system || until emerge --resume --skipfirst; do :; done

# I run a clean ship (and VMWare images tend to bloat up), 
# so I like to get rid of things I don't need nohow...

find /var/log/* -mtime +30 -exec rm -rf {} \;
find /var/log/portage-logs/* -type f -empty -exec rm -rf {} \;
rm -rf /var/tmp/portage/*
rm -rf /usr/portage/distfiles/*

for f in $(portageq envvar PORT_LOGDIR)/*.log;
  do
   gzip -f $f 2>/dev/null || echo "Failed to gzip $f"
  done
					



Subversion pre-commit script

I searched high and low to find a script that would do this seemingly simple task. Why did the Subversion people have to make things so complicated?! GRRR. Put this in your subversion repository as 'hooks/pre-commit' and chmod +x it.


#!/bin/bash

#
# written by Daevid Vincent (http://daevid.com) on 05.15.08
#
# based upon code found here: 
# http://pookey.co.uk/blog/archives/33-Automatically-syntax-checking-of-PHP-files-when-checking-to-SVN.html
#

# I would have liked to write this in PHP, but for now bash will have to do
# reference -- http://www.nabble.com/Repository-size-and-dump-size-td15737725.html

# This isn't the most elegant way to do this. 
# TODO: it would be nice to store all the PHP errors in an array and spit them all out at once.

REPOS="$1"
TXN="$2"
#echo "REPOS = $REPOS" 1>&2
#echo "TXN = $TXN" 1>&2

SVNLOOK=/usr/bin/svnlook
PHP=/usr/bin/php

BANNEDFILES=( '.DS_Store' 'Thumbs.db' ) 

# redirect all output to stderr rather than line by line
exec 1>&2

# Make sure that the log message contains some text.
LOGMSG=`$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]"`
#echo "LOGMSG = '$LOGMSG'"  
if [ -z "$LOGMSG" ] ; then
	echo " "  
    echo "A commit log message is required."  
	exit 1
fi

COMMIT_FILES=`$SVNLOOK changed -t "$TXN" "$REPOS" | awk '{print $2}'`
for MYFILE in $COMMIT_FILES
  do
	# echo "MYFILE = ${MYFILE} and COMMIT_FILES = ${COMMIT_FILES}"  
	BASENAME=`basename $MYFILE`
	FILENAME=${BASENAME%.*}
	FILEEXT=${BASENAME##*.}
	echo "FILENAME = ${FILENAME} and FILEEXT=${FILEEXT}"  

	if [[ "${FILEEXT}" =~ r([0-9]+) ]] ; then 
		echo " "  
	    echo "Files of type .r${BASH_REMATCH[1]} indicate a conflict remains and are not allowed to be commited."  
		exit 1
	fi
	
	if [[ 'mine' == ${FILEEXT} ]] ; then 
		echo " "  
	    echo "Files of type .mine indicate a conflict remains and are not allowed to be commited."  
		exit 1
	fi

	for i in ${BANNEDFILES[@]}; do 
		if [[ $i == ${BASENAME} ]] ; then 
			echo " "  
		    echo "Files of type ${BASENAME} are not allowed to be commited."  
			exit 1
		fi
	done 

	#if [FILEEXT == "php" ]; then
	PHPFILE=`echo $MYFILE | egrep \\.php$`
	if [ $? == 0 ]; then
		MESSAGE=`$SVNLOOK cat -t "$TXN" "$REPOS" "${PHPFILE}" | $PHP -l`
		if [ $? -ne 0 ] ; then
			echo " "  
			echo "---------------------------------------------------------------------------------"  
			echo "During automatic PHP syntax checking we found the following PHP errors: "  
			echo " "  
			echo "$MESSAGE" | sed "s| -| $PHPFILE|g"  
			echo " "  
			echo "Please correct the error and try the commit again."  
			echo " "  
			echo "You can check for syntax error on your computer by running the command:"  
			echo "${PHP} -l ${PHPFILE}"  
			echo "---------------------------------------------------------------------------------"  
			exit 1
		fi
	fi
 done

# All checks passed, so allow the commit.
exit 0