Snippets

From splike.com
Jump to: navigation, search

python named logger function

def getLogger(object):
    # logging.config.fileConfig(my_log_file)
    if isinstance(object,basestring):
        name = object
        # full filenames
        if '/myapp/' in name:
            name = 'myapp/' + name.split('/myapp/')[1]
        # path separators
        name = name.replace('/','.')
    elif type(object) is types.InstanceType:
        name = str(object.__class__)
    else:
        name = object.__class__.__module__ + '.' + object.__class__.__name__
    return logging.getLogger(name)

geocaching google map hide types

only keeps earthcaches. first run a jquerify bookmarklet

$('img[src^="http://www.geocaching.com/images/wpttypes/sm/"]').each(function(){ if(this.src.indexOf('137.gif')==-1){ this.src='http://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif'} });$('img[src="http://www.geocaching.com/images/gmn/cm.png"]').attr('src','http://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif');jQuery.noConflict();

git status, only showing modified and not all the Untracked files

FIXME: getting a git lock error

git status | head -n $(expr $(git status | sed -n /Untracked/=) - 1)

in an file (e.g. .bashrc)

alias git-st-head="git status | head -n \$(expr \$(git status | sed -n /Untracked/=) - 1)"

most frequent 404s from log file

grep -v '"-"' is used to eliminate hits without referrers change $7 if your log form is different

grep ' 404 ' access.log | grep -v '"-"' | awk '{print $7}' | sort | uniq -c | sort -gr | head

make a filesystem in a file, mount via loopback

I use this to rsync parts of my ext3 filesystem to an ext3 loopback file that lives on a separate hard drive (which is all fat32)

dd if=/dev/zero of=/mnt/fat32drive/homedir-ext3.iso bs=1024 count=1072000
mkfs.ext3 -b 4096 -I 128 -L "homedir backup" homedir-ext3.iso
# if you want to match another filesystem, you can run
tune2fs -l /dev/sda1
mkdir /mnt/homedir-ext3-backup
echo "/mnt/fat32drive/homedir-ext3.iso /mnt/homedir-ext3-backup ext3 auto,rw,loop" >> /etc/fstab

resize an ext3 loopback filesystem

run `stat fs.iso`, see size
divide by the blocksize you're going to use, use that as seek value, e.g.:

dd if=/dev/zero of=fs.iso bs=1024 seek=107200 count=50000
umount /mnt/fs
ext2resize fs.ifo
# could use parted here too, probably
mount /mnt/fs

download all photos from a picasa web album

First install the Picasa package from CPAN
perl -MPicasa -e "Picasa->new()->get_list_of_photos({'userid'=>'TheUserId','album'=>'TheAlbumName'})"

add metadata to a flash video file

I don't know of any standards for which custom metadata tags to use, so for simplicity right now I use title, date, url (html), uri (data), embedurl (for embedding flash player of it in HTML), and copyright. Eventually I want to use XMP, and add geo info and other linked data

flvtool2 -UP "-title:Architecture In Helsinki - It'5! - Live at Metro, Chicago" -copyright:unknown "-url:http://www.youtube.com/watch?v=xxemKiM60SU" "-embedurl:http://www.youtube.com/v/xxemKiM60SU&rel=1" -date:2007-10-16 "-uri:http://gdata.youtube.com/feeds/videos/xxemKiM60SU" It\'5\!.flv

find all used (unique) values of 'background-image' CSS property

uses jQuery; prints them to console (FireBug)

var all_props = $('*').map(function(){prop=$(this).css('background-image');return (prop == "none" ? null : prop)});
var props = new Object;
for (var i = 0; i < all_props.length; i++) {
  props[all_props[i]] = null;
}
for (var p in props) {
  console.debug(p)
}

my gpsbabel command

gpsbabel -i magellanx -f mytrip.log -x track,sdistance=100m -o gpx -F mytrip.gpx

that also splits tracks apart when gaps of 100+ miles

list packages installed in multiple slots

equery l -d

"prune" packages in multiple slots

emerge -pP kde

print Camera Model for each jpg file

  • find . -name '*.jpg' | while read file; do jhead "$file" | awk -F\: '/^Camera model : / {printf substr($2,2)}'; echo -ne "\t\t"; echo $file; done

find all FIXME comments

  • find . -type f ! -path '*/.svn/*' | while read file ; do grep -iHn fixme "$file" >> ../fixmes.txt; done

thunderbird 1.0.2 (and others too i'm sure) break links on ")" closing paren

  • so use %29 instead

log emerge output, check for notifications

  • emerge -uDv system > emerge.out 2> emerge.err
  • search for [[33;01m and [[31;01m

copy directory settings to all subdirs

  • find . -type d | while read line; do echo "---> $line <--"; cp ../path/to/good/.directory "$line"; done

image rotate

  • jhead -autorot *.jpg
  • jpegtran -rotate 270 -copy all img_4227.jpg > img_4227y.jpg

disk usage

  • du -s --si `ls -A`

prompt (return value doesn't show right number)

 GRAY="1;30"
 CYAN="0;36"
 LIGHT_CYAN="1;36"
 LIGHT_BLUE="1;34"
 YELLOW="1;33"
 WHITE="0;1"
 NO_COLOR="0"
 RED="41;1"
 LIGHT_GREEN="1;32"
 BROWN="0;33"
 
 CONDITIONAL_RETURN_VALUE="\`if [[ \$? != "0" ]]; then echo \"\[\033[${RED}m\]\$? \"; fi\`"
 PWD_COUNT="(\`ls \"\$PWD\" | wc | awk '{print \$1}'\`)"
 export PS1="${CONDITIONAL_RETURN_VALUE}\[\033[${LIGHT_BLUE}m\]\u \[\033[${BROWN}m\]\w${PWD_COUNT} \[\033[${YELLOW}m\]\t \[\033[${NO_COLOR}m\]\$ "

doesn't work for files with spaces

gaim aliases

  • alias gaim-last="ls | tail -n 1 | xargs links"
  • alias gaim-chk="cd ~/.gaim/logs/aim/brondsem; ls -latr"

ls aliases

  • alias ls-last='echo "$(pwd)/$(ls -tr | tail -n 1)"'
  • alias ls-first='echo "$(pwd)/$(ls -t | head -n 1)"'
  • e.g. links `ls-last`

many things

  • find . -type d -and -maxdepth 1 -print0 | xargs --replace du --si 2> /dev/null
    • redirect stderr to /dev/null
    • -print0 and --replace to handle single quotes and spaces (respectively, IIUC)

generate javadocs

tab completion ignore files (?)

  • export FIGNORE=CVS

xargs equiv for paths with quotes & spaces

  • find . ... | while read file ; do svn propset svn:eol-style native "$file" ; done

perl OO get/set

One handy thing with OO Perl is that you can define an autoload function, instead of creating a get/set function for each data member. Like so:

   sub AUTOLOAD {
       my $self = shift;
       my $type = ref($self) || croak "$self is not an object";
       my $name = $AUTOLOAD;
       
       # DESTROY builtin will call the autoload if we don't have one
       return if $name =~ /::DESTROY$/;
       
       $name =~ s/.*://;   # strip fully-qualified portion
       
       unless (exists $self->{$name} ) {
               croak "Can't access `$name' field in object of class $type";
       }
       
       # If an argument was passed in, assume the value is being set,
       #        otherwise, assume the value is being requested
       if( @_ ) {
               return $self->{$name} = shift;
       } else {
               return $self->{$name};
       }
   }

so this would automatically define $person->name(), $person->name("Bob"), $person->peers(\@peerlist), etc. This would work better with array/hash references, rather than arrays/hashes themselves, though.

HTML print part of page

mount vfat

# dirs: 775 files: 664 group: users
/dev/hdb1      /data      vfat     rw,nosuid,dev,exec,auto,user,async,umask=113,dmask=002,fmask=113,gid=100     0 0

wma2wav ([1])

  • wma2wav -d -e ogg -r /usr/local/bin/oggscr 01\ Track\ 1.wma

invoke Thunderbird compose window w/ attach

  • if not running: /usr/bin/thunderbird -compose attachment=file:///tmp/sval4.tmp/critique7_2.sxw
  • if running: opt/thunderbird/mozilla-xremote-client -a thunderbird 'xfeDoCommand(composeMessage,attachment=file:///tmp/sval4.tmp/critique7_2.sxw)'
  • [2]
  • [3]

select all table rowcounts in mssql

select i.rowcnt, o.name --, i.name, o.xtype, *
from sysindexes i
inner join sysobjects o
	on i.id = o.id
and o.xtype <> 'S'
and indid < 2
order by o.name