— Animation w/Processing Workshop

— Generate Semitones

my $m = 2 ** (1/12);
foreach my $s (0..12) {
    print int(0.5 + 1000 * $m ** $s-1000), "\n";

semitone - fine
0  - 0 
1  - 59 
2  - 122 
3  - 189 
4  - 260 
5  - 335 
6  - 414 
7  - 498 
8  - 587 
9  - 682 
10 - 782 
11 - 888 
12 - 1000


— count words in html file with python


import nltk
import string
from urllib import urlopen
from itertools import imap

url = "http://google.com"
html = urlopen(url).read()
text = nltk.clean_html(html)
text_noPunc = text.translate(string.maketrans("",""), string.punctuation)
words = text_noPunc.split()
max_word_len = max(imap(len, words))
vocabulary = nltk.probability.FreqDist(words)

for word in vocabulary:
    print word,
    print ' ' * (max_word_len + 5 - word.__len__()),
    print str(vocabulary[word])

Using NTLK.

Gist on Github.

— DualBoot Archlinux/Windows7 Installation

Documentation of the process of installing archlinux and Windows 7 in a dual-boot configuration.

System Specs

  • AMD X2 dual-core processor, running at 2.8 ghz, circa 2002
  • ASUS ATX motherboard
  • 2 gigs of ram
  • 100gb drive
  • nvidia gtx 550 ti graphics card
  • linksys wmp54g wireless pci network card
  • 550w power supply

Installing Windows

Windows was installed from a USB stick using Microsoft's Windows 7 USB/DVD tool. It's required to create this key from a Windows 7 system. Boot with the USB drive, then install Windows on the drive in a single partition. Windows also creates a System Reserved partition for itself. Once installed, via Start Menu > Administrative Tools > Computer Management > Disk Manamagent, select 'Shrink Partition' on the main Windows parition to create another partition for Arch. The default value for the shrink is 50%, so for my setup the value for the new disk size was ~50GB, which was ideal.

Note about this install. I have an old Linksys (Cysco) WMP54G Wireless PCI Card. Drivers from Linksys/Cysco's website didn't work, but following this blog post, the generic RALink drivers worked great.

Installing Archlinux

I downloading the Core Image via torrent from http://www.archlinux.org/download/. This ISO includes all core packages so the system doesn't need to be online to install.

Once downloaded, I followed the notes on how to create a bootable ISO onto another USB drive with yet another machine. There are also numerous free tools available to make a bootable ISO on Windows. After booting into Arch with the USB stick, boot into Arch, and type:


The installation article on the archwiki is an excellent resource.

Disk Partitions

It's pretty straight forward until the drive partitions. My 100GB drive can only support 4 logical partitions, so the rest have to be Logical. Note: The numbers are out of order, because I used Logical partitions for everything except for the Windows partitions and /home. Logical partitions end up being counted last in the partition table, but I made my /home folder LAST so I could use the up the remaining space on the drive. You'll also need to set the /boot partition's 'bootable' flag to true.

• sda1
    Windows 7 System Reserved
• sda2
    Windows 7
• sda5
    /boot - 100MB is enough
• sda6
    / - about 25GB is appropriate
• sda7
    swap - between 1024MB and 4096MB
• sda4
    /home - use rest of hard drive

Some of these, namely boot, swap, and home, are optional.

Select Packages

At minimum, you'll need the core packages that are already selected. I also included certain key packages such as OpenSSH. Basically, include any packages you need for internet connectivity, as everything else will be updated from the net.

Configure System

Configure system does multiple things, including setting the root password, network settings, and some other configuration tools. Here's a reference of where Arch installs all the base config files for the system.

/etc/rc.conf                    system config
/etc/fstab                      filesystem mountpoints
/etc/mkinitcpio.conf            initramfs config
/etc/modprobe.d/modprobe.conf   kernel modules
/etc/resolv.conf                dns servers
/etc/hosts                      network hosts
/etc/locale.get                 glibc locals
/etc/pacman.conf                pacman.confg
/etc/pacman.d/mirrorlist        pacman mirror list

You should edit any of these files that are specific to your system. At minimum I enabled my network card in rc.conf.

You'll also need to enable at least one mirror in pacman.d/mirrorlist if you plan to update the system or download new packages.


Install Bootloader will install and help you configure the bootloader you selected in the Select Packages stage (GRUB, in my case). After double-checking your bootloader configuration, you'll be prompted for a disk to install the loader to. You should install GRUB to the MBR of the installation disk, in this case sda1.

Finalizing Installation

Once installed, exit the installer, remove the USB, type reboot in the command line, and the system will reboot. You'll boot into a login screen, which you can login with via root.

You can create new users interactively with useradd.

You can install/update packages with Arch's package manager, pacman.

Before installing any packages, sync the package list with:

pacman --sync --refresh

To add a new package (vim, in this case), type:

pacman -S vim

next: getting node and a webserver installed.

— print formatted JSON, XML from osx command line

Working with various interfaces that output json or xml results in lots of situations where you have a single-line, unformatted output. Here's a quick way to format json, xml from the CLI.

via the command line:

format json

cat unformatted.json | python -m json.tool

format json from clipboard

pbpaste | python -m json.tool

format xml from clipboard

pbpaste | xmllint --format -
xmllint is part of libxml2 and installed by default on OSX. Be aware that xmllint cleans up XML as well as formatting it, ocassionally modifying the output.

for all above examples, you can pipe back to the clipboard with | pbcopy at the end of the command, or output to a file with > output.json or > output.xml.

— command line audio on OSX

Since there is no equivilent to /dev/dsp or /dev/audio on OSX, you need to install an alternative like sox.

Install sox by either downloading the OSX binary from http://sox.sourceforge.net/ or install homebrew, and then install sox with brew install sox


cat audio from /dev/urandom/ :

cat /dev/urandom | sox -traw -r44100 -b16 -u - -tcoreaudio

audio from an executable

cat > test.c
main(t) {
  for( t = 0;;t++)
    putchar( t * ((( t >> 12 ) | (t >> 8)) & (63& (t >> 4 ))));
gcc test.c -o test
./test | sox -traw -r8000 -b8 -u - -tcoreaudio


— command history

history | awk {'print $2'} | sort | uniq -c | sort -k1 -rn | head


// brand new netbook
  24 ls
  14 cd
  12 defaults
   9 unzip
   8 ssh
   5 mv
   3 mkdir
   3 chmod
   3 cat
   2 unrar
// quilime.com
 173 git
 140 ls
  84 cd
  18 emacs
  15 cat
  13 mv
  12 rm
   5 ln
   4 mkdir
   4 ./scripts/content

— Terminal Emulator on Windows via Cygwin

How to install cygwin on windows:

  1. Install Cygwin from setup.exe

  2. Install the following packages:

    • xorg-server (required, the Cygwin X Server)
    • xinit (required, scripts for starting the X server: xinit, startx, startwin (and a shortcut on the Start Menu to run it), startxdmcp.bat )
    • xorg-docs (optional, man pages)
    • X-start-menu-icons (optional, adds shortcuts to X Clients and Server to the Start menu)
    • mintty (windows-feel terminal)
  3. Optional Packages

    • openssh
    • git, svn
    • wget, curl
    • rsync
    • vim, emacs
    • any additional fonts

  1. ~/.XDefaults dark theme:

    ! terminal colors ------------------------------------------------------------
    ! tangoesque scheme
    *background: #111111
    *foreground: #babdb6
    ! Black (not tango) + DarkGrey
    *color0:  #000000
    *color8:  #555753
    ! DarkRed + Red
    *color1:  #ff6565
    *color9:  #ff8d8d
    ! DarkGreen + Green
    *color2:  #93d44f
    *color10: #c8e7a8
    ! DarkYellow + Yellow
    *color3:  #eab93d
    *color11: #ffc123
    ! DarkBlue + Blue
    *color4:  #204a87
    *color12: #3465a4
    ! DarkMangenta + Mangenta
    *color5:  #ce5c00
    *color13: #f57900
    !DarkCyan + Cyan (both not tango)
    *color6:  #89b6e2
    *color14: #46a4ff
    ! LightGrey + White
    *color7:  #cccccc
    *color15: #ffffff
    Some more themes on the Arch forums.

  2. ~/.bashrc To enable color ls and human readable size format, add:

    alias ls='ls -h --color=tty'
    By default, the .bashrc in CygwinX has many options you can uncomment.

  3. ~/.emacs Disable emacs temp (~) file pooping

    (setq make-backup-files nil)


Other emulators for Windows: - Terminator/

— create bootable iso from unix/osx terminal

  1. diskutil list
    Determines the device node assigned to your flash media (e.g. /dev/disk2)

  2. diskutil unmountDisk /dev/disk#
    Replace # with the disk number from the last command; in the previous example, # is 2)

  3. sudo dd if=/path/to/example.iso of=/dev/diskN bs=1m
    Replace /path/to/example.iso with the path to the iso; for example: ./windows7.iso. After typing in your sudo password, the process will start invisibly.

  4. diskutil eject /dev/disk#
    Remove your flash media device when the command completes. Done!

Referenced from BurningIsoHowto

Bonus tip! You want to see how far the dd copy is coming along? Run in another terminal instance:
$ sudo killall -INFO dd
The process info will display in the original terminal.

— filebrowser

File Browser PHP script on GitHub.

demo: media.quilime.com

— show hidden files (OSX Finder)

via Terminal

show hidden files:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

hide hidden files:

defaults write com.apple.finder AppleShowAllFiles FALSE
killall Finder

— Combine Files (Windows)

copy /b file1+ file2 output


copy /b picture.jpg + archive.rar file.jpg

Open file.jpg with the default application, it will show the picture "picture.jpg". Change the extension to "file.rar" or if you try to open "file.jpg" with an archiver you will get the contents of "archive.rar".

— create ssh keys

ssh-keygen -t rsa
// linux
ssh-copy-id [user@]host
// osx
cat ~/.ssh/id_rsa.pub | ssh user@machine "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"
eval `ssh-agent`

— linux bash profile

alias ls='ls --color'
export CLICOLOR=1
export LSCOLORS=gxFxCxDxBxgggdabagacad

export EDITOR='emacs'

— osx bash profile

# color ls
export CLICOLOR=1
export TERM=xterm-color
export LSCOLORS=GxFxCxDxBxegedabagacad

function parse_git_branch {
  ref=$(git symbolic-ref HEAD 2> /dev/null) || return
  echo "("${ref#refs/heads/}")"

#Black       0;30     Dark Gray     1;30
#Blue        0;34     Light Blue    1;34
#Green       0;32     Light Green   1;32
#Cyan        0;36     Light Cyan    1;36
#Red         0;31     Light Red     1;31
#Purple      0;35     Light Purple  1;35
#Brown       0;33     Yellow        1;33
#Light Gray  0;37     White         1;37

# colors

# prompt with git repo
export PS1="$WHITE_B\u@\h $BLUE_B\w $RED\$(parse_git_branch) $NO_COLOR \n$BLUE_B\$ $NO_COLOR"
export PS2="$BLUE_B> $NO_COLOR";

# aliases
alias ff="find . -type f -name "

— resize multiple images

for k in $(ls *.JPG); do convert $k -resize 50% -quality 80 r_$k; done

— Maya render bat batch file

*.bat file structure

REM // .bat comment syntax
C:\Progra~1\Autodesk\Maya2010\bin\render -s 1 -e 30 -im output_image myscene.ma
C:\Progra~1\Autodesk\Maya2010\bin\render -s 1 -e 30 -im output_image2 anotherscene.ma

The path to render.exe must be the 8.3 character DOS version.
To execute the file, save as a *.bat and double click it in Explorer.

// Render Flags
usage: Render <options> <filename>
where <filename> is a Maya ASCII or a Maya Binary file.

startFrame            -s   <float>     starting frame for an animation sequence

endFrame              -e   <float>     end frame for an animation sequence

byFrame               -b   <float>     by frame (or step)
                                       for an animation sequence

startExtension        -se  <int>       starting number for the output image
                                       frame file name extensions

byExtension           -be  <int>       by extension (or step) for the output
                                       image frame file name extension

extensionPadding      -pad <int>       number of digits in the output image
                                       frame file name extension

project               -proj <dir>      project directory to use

renderDirectory       -rd  <path>      directory in which to store image file

image                 -im  <filename>  image file output name (identical to -p)

pix                   -p   <filename>  image file output name (identical to -im)

mayaExtension         -me  <boolean>   append maya file name to image name
                                       if true

mayaFormat            -mf  <boolean>   append image file format to image name
                                       if true

cameraOverride        -cam <name>      all subsequent -im -p -ar -sa flags
                                       apply only to <camera_name>
                                       (specifying '-cam <camera_name>' enables
                                       rendering for that camera). If '-cam
                                       <camera_name>' is on the command line,
                                       then only the camera(s) specified on the
                                       command line will be rendered.

gamma                 -g   <float>     gamma value

ignoreFilmGate        -ifg <boolean>   use the film gate for rendering if false

imageHeight           -ih  <int>       height of image in pixels

imageWidth            -iw  <int>       width of image in pixels

deviceAspectRatio     -ard <float>     device aspect ratio for the rendered image

aspectRatio           -ar  <float>     aspect ratio for the film aperture

maximumMemory         -mm  <int>       renderer maximum memory use
                                       (in Megabytes)

motionBlur            -mb  <boolean>   motion blur on/off

motionBlurByFrame     -mbf <float>     motion blur by frame

shutterAngle          -sa  <float>     shutter angle for motion blur (1-360)

motionBlur2D          -mb2d <boolean>  motion blur 2D on/off

blurLength            -bll <float>     2D motion blur blur length

blurSharpness         -bls <float>     2D motion blur blur sharpness

smoothValue           -smv <int>       2D motoin blur smooth value

smoothColor           -smc <boolean>   2D motion blur smooth color on/off

keepMotionVector      -kmv <boolean>   keep motion vector for 2D motion blur on/off

useFileCache          -uf  <boolean>   use the tessellation file cache

optimizeInstances     -oi  <boolean>   dynamically detects similarly
                                       tessellated surfaces

reuseTessellations    -rut <boolean>   reuse render geometry to
                                       generate depth maps

useDisplacementBbox   -udb <boolean>   use the displacement bounding box scale to
                                       optimize displacement-map performance

enableDepthMaps       -edm <boolean>   enable depth map usage

enableRayTrace        -ert <boolean>   enable ray tracing

reflections           -rfl <int>       maximum ray-tracing reflection level

refractions           -rfr <int>       maximum ray-tracing refraction level

renderLayers          -rl <boolean|name>  render each layer separately

renderPasses          -rp <boolean|name>  render passes separately

renderSubdirs         -rs <boolean>    render layer output placed in subdirectories

shadowLevel           -sl  <int>       maximum ray-tracing shadow ray depth

edgeAntiAliasing      -eaa <quality>   The anti-aliasing quality of EAS
                                       (Abuffer). One of highest high medium low

useFilter             -ufil <boolean>  if true, use the multi-pixel filtering
                                       otherwise use single pixel filtering.

pixelFilterType       -pft  <filter>   when useFilter is true, identifies one of the
                                       following filters: box, triangle
                                       gaussian, quadraticbspline, plugin

shadingSamples        -ss  <int>       global number of shading samples
                                       per surface in a pixel

maxShadingSamples     -mss <int>       maximum number of adaptive shading
                                       samples per surface in a pixel

visibilitySamples     -mvs <int>       number of motion blur visibility samples

maxVisibilitySamples  -mvm <int>       maximum number of motion blur
                                       visibility samples

volumeSamples         -vs  <int>       global number of volume shading samples

particleSamples       -pss <int>       number of particle visibility samples

redThreshold          -rct <float>     red channel contrast threshold

greenThreshold        -gct <float>     green channel contrast threshold

blueThreshold         -bct <float>     blue channel contrast threshold

coverageThreshold     -cct <float>     pixel coverage contrast threshold
                                       (default is 1.0/8.0)

outputFormat          -of  <format>    output image file format. One of: si soft
                                       softimage, gif, rla wave wavefront, tiff
                                       tif, tiff16 tif16, sgi rgb, sgi16 rgb16
                                       alias als pix, iff tdi explore maya, jpeg
                                       jpg, eps, maya16 iff16, cineon cin fido,
                                       qtl quantel, tga targa, bmp

shadowPass            -sp <boolean>    generate shadow depth maps only

abortOnMissingTexture -amt             abort renderer when encountered missing texture

dontReplaceRendering  -rep             do not replace the rendered image if it already exists

verbose               -verbose <boolean> perform the render verbosely if on

iprFile               -ipr             create an IPR file

xResolution           -x   <int>       set X resolution of the final image

yResolution           -y   <int>       set Y resolution of the final image

xLeft                 -xl  <int>       set X sub-region left pixel boundary
                                       of the final image

xRight                -xr  <int>       set X sub-region right pixel boundary
                                       of the final image

yLow                  -yl  <int>       set Y sub-region low pixel boundary
                                       of the final image

yHigh                 -yh  <int>       set Y sub-region high pixel boundary
                                       of the final image

displayLayer          -l  <name>       one or more displayLayer names to render

numberOfProcessors    -n  <int>        number of processors to use. 0 indicates
                                       use all available.

tileWidth             -tw <int>        force the width of the tiles.  Valid valu
                                       are between 16 and 256.

tileHeight            -th <int>        force the height of the tiles.  Valid values
                                       are between 16 and 256.

                      -cont            allow renderer to continue when it hits errors

                      -keepPreImage    keep the renderings prior to post-process around

any boolean works: yes, true, or 1, as TRUE,and off, no, false, or 0 as FALSE.

example: Render -x 512 -y 512 -cam persp -im test -of sgi -mb on -sa 180 file.ma

— Rewrite URL: Replace Double Slashes With Single Slash

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

— date for new filename

# Shell script to create file named after the current date
# YYYY-MM-DD format

DATE=$(date +%Y"-"%m"-"%d)
echo -e "new file" > $DATE

— Rename Multiple Files via Shell

ls | nl -nrz -w2 | while read a b; do mv "$b" filename.$a.png; done;

— Sphere Intersect in Maya/MEL

Function to return location of intersect with poly mesh and spherical object moving in the positive direction on the Y axis.

mel source

global proc intersectSphereY()
    print(". . . . . go go go\n");

int $iter = 50;
float $start[3] = {0, -0.5, 0};
float $limit[3] = {0, 5.0, 0};
    $mesh = "test_mesh";    
$tmpCN = "cpom";

$obj = "rod1";
    float $radius = 0.5;
    float $curPos[3] = {0, 0, 0};

for ($i = 0; $i <= $iter; $i++)
    $mesh = "test_mesh";
    $shape = `listRelatives -shapes $mesh`;

    createNode -n $tmpCN closestPointOnMesh;
    connectAttr -f ($shape[0] + ".outMesh") ($tmpCN + ".inMesh");
    setAttr ($tmpCN + ".inPosition") $curPos[0] $curPos[1] $curPos[2];

    $cpom = `getAttr ($tmpCN + ".position")`;

    if ( pointDist($curPos, $cpom) <= $radius ) {
        return ". . bonk\n";

    $curPos[1] = ($limit.y) / $iter * $i;
    setAttr ($obj + ".translateY") $curPos[1];

    delete $tmpCN;
return ". nope\n";


global proc float pointDist(float $p1[], float $p2[]) { return sqrt( (($p1[0] - $p2[0]) * ($p1[0] - $p2[0])) + (($p1[1] - $p2[1]) * ($p1[1] - $p2[1])) + (($p1[2] - $p2[2]) * ($p1[2] - $p2[2]))); }


— Image Slice

Shell script that slices a single image into any number of vertical and horizontal sections.

#@author  gabriel dunne <quilime.com>


if [ $# -eq 0 ]
    echo "usage: image width height rows cols"
    echo "example: ./slice.sh Sunset.jpg 800 600 16 16"

    for (( x = 1; x <= COLS; x++ ))
        for (( y = 1 ; y <= ROWS; y++ ))
            let CROP_X = `expr $IMAGE_W-IMAGE_W/$x`
            let CROP_Y = `expr $IMAGE_H-IMAGE_H/$y`
            let CROP_W = `expr $IMAGE_W/$ROWS`
            let CROP_H = `expr $IMAGE_H/$COLS`
            echo -n "crop ${CROP_W}x${CROP_H}+${CROP_X}+${CROP_Y} result: [${x},${y}]_$IMAGE"
            echo ""
            convert $IMAGE -crop ${CROP_W}x${CROP_H}+${CROP_X}+${CROP_Y} [${x},${y}]_$IMAGE

To Use

navigate to slice.sh in your terminal and do

chmod +x slice.sh
./slice.sh Sunset.jpg 800 600 16 16
replace Sunset.jpg with your image name.
params: Image Height, Image Width, Vertical Divisions, Horizontal Divisions

— MEL Notepad

mel notepad with various code snippets

process selection list

string $select[] = ls -sl;
for ( $node in $select ) // process each
   /* ... */

if node exists

string $node = "object";
if ( objExists $node )
   // The node exists


Strip component

string $node = "pCube1.f[2]";
string $no_component = match "^[^\.]*" $node;
// Result: "pCube1" //

Extract component or attribute, with '.'

string $node = "pCube1.f[2]";
string $component = match "\\..*" $node;
// Result: ".f[2]" //

string $nodeAttr = "blinn1.color"; string $attrName = match "\\..*" $nodeAttr; // Result: ".color" //

Extract attribute name, without '.'

string $node = "pCube1.f[2]";
string $component = `substitute "^[^.]*\\." $node ""`;
// Result: "f[2]" //

string $nodeAttr = "blinn1.color";
string $attrName = `substitute "^[^.]*\\." $nodeAttr ""`;
// Result: "color" //

Extract parent UI control from full path

string $uiControl = "OptionBoxWindow|formLayout52|formLayout55|button6";
string $uiParent = substitute "|[^|]*$" $uiControl "";
// Result: OptionBoxWindow|formLayout52|formLayout55 //

Strip trailing Line Break (\n), if any.

This is useful when processing text input read from a file using fgetline.

string $input = "line\n";
$string $line = match "^[^(\r\n)]*" $input;
// Result: "line" //

Extract directory from path.

Keep the trailing slash for ease of use.

string $path = "C:/AW/Maya5.0/bin/maya.exe";
string $dir = match "^.*/" $path;
// Result: "C:/AW/Maya5.0/bin/"

Extract file from path

string $path = "C:/AW/Maya5.0/bin/maya.exe";
string $filepart = match "[^/\\]*$" $path;
// Result: "maya.exe"

Strip numeric suffix

string $node = "pCube1|pCubeShape223"; string $noSuffix = match ".*[^0-9]" $node; // Result: "pCube1|pCubeShape"

Extract numeric suffix

string $node = "pCube1|pCubeShape223";
string $suffix = match "[0-9]+$" $node;
// Result: "223" //

Extract short name of DAG or control path

string $dagPath = "pCube1|pCubeShape223";
string $shortName = match "[^|]*$" $dagPath;
// Result: pCubeShape223 //

other reference

↑ index