Never been to CodeSnippets before?

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!)

Pretty-print source code with enscript


man enscript 

open http://trac.macports.org/wiki/InstallingMacPorts
sudo port install enscript


alias enscript='/opt/local/bin/enscript'

man enscript
enscript --help
enscript --list-media
enscript --help-highlight | less
enscript --help-pretty-print | less

# list available fonts for man enscript
cat -n /usr/share/enscript/font.map

man pstopdf   # cf. http://codesnippets.joyent.com/posts/show/1601


FILE="/usr/include/sys/stat.h"

enscript -q -C -Ec --color -f Courier10 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec --color -f Courier10 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec -G --color -f Courier10 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec -G --color --word-wrap -f Courier10 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec -G --color --word-wrap -f Courier10 -MLetter -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec -G --color --word-wrap -f Courier7 -MA4 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
enscript -q -B -C -Ec -G --color --word-wrap -f Courier7 -MA4 -T4 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf

open -a Preview ~/Desktop/test.pdf


FILE="/usr/bin/isc-config.sh"
enscript -q -B -C -Esh -G --color --word-wrap -f Courier7 -MA4 -T4 -p - "$FILE" | pstopdf -i -o ~/Desktop/test.pdf
open -a Preview ~/Desktop/test.pdf

This is Code Test

// description of your code here

// This is test Code

Code snippet test

How does this look?


# weird way to represent \'  // exit using ctrl-D
alias sharecode='curl -si -F '\''content=<-'\'' http://dpaste.com/api/v1/ | grep ^Location: | colrm 1 10'

Code Igniter Smarty Template Library

// Makes it extremely easy to integrate code igniter and smarty as well as provide layout capabilites

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require "smarty/Smarty.class.php";

class Template extends Smarty{

    var $theme = "default";

    function __construct()
    {
        $this->tpl = new Smarty();
        $this->tpl->template_dir = ROOTPATH . "templates/";
        $this->tpl->compile_dir = APPPATH . "libraries/smarty/templates_c/";
        $this->tpl->config_dir = APPPATH . "libraries/smarty/config/";
        $this->tpl->plugins_dir = APPPATH . "libraries/smarty/plugins/";
    }

    function assign($key,$value)
    {
        $this->tpl->assign($key,$value);
    }

    function display($template)
    {
        $this->tpl->display($template);
    }

    function fetch($template)
    {
        $this->tpl->fetch($template);
    }

    function layout($inner_template,$array)
    {
          foreach($array as $key=>$val) {
               $this->assign($key,$val);
          }

          $this->assign("inner_template",$inner_template);

          $this->display($this->theme.".tpl");
          exit;
    }

}

ANSI terminal color chart

1.
#!/bin/bash
#
#   This file echoes a bunch of color codes to the 
#   terminal to demonstrate what's available.  Each 
#   line is the color code of one forground color,
#   out of 17 (default + 16 escapes), followed by a 
#   test use of that color on all nine background 
#   colors (default + 8 escapes).
#
#   Author: Giles Orr
#   URL: http://gilesorr.com/bashprompt/howto/c350.html
#   License: GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation;
#            http://gilesorr.com/bashprompt/howto/a1004.html


T='gYw'   # The test text

echo -e "\n                 40m     41m     42m     43m\
     44m     45m     46m     47m";

for FGs in '    m' '   1m' '  30m' '1;30m' '  31m' '1;31m' '  32m' \
           '1;32m' '  33m' '1;33m' '  34m' '1;34m' '  35m' '1;35m' \
           '  36m' '1;36m' '  37m' '1;37m';
  do FG=${FGs// /}
  echo -en " $FGs \033[$FG  $T  "
  for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
    do echo -en "$EINS \033[$FG\033[$BG  $T  \033[0m";
  done
  echo;
done
echo

2.
#!/bin/sh
#
#  colors v1.03
#
#  A simple shell script to output an ANSI terminal color chart.
#  It may be useful when trying to customize your ANSI terminal
#  color scheme!
#
#  Written and placed in the public domain by Ian Abbott <ian@abbott.org>
#
#  ANSI terminal color chart generator
#  Author: Ian Abbott
#  License: BSD License, http://www.opensource.org/licenses/bsd-license.php
#  URL: http://www.snippetcenter.org/de/ansi-terminal-color-chart-generator-s1346.aspx

for h in 0 1; do
  echo -e "\\033[0;${h}m\\c"
  case $h in
  0) echo -e "Normal\\c" ;;
  1) echo -e "High\\c" ;;
  esac
  echo -e " intensity foreground (background color in parentheses)\\033[m"
  for f in 0 1 2 3 4 5 6 7; do
    for b in 0 1 2 3 4 5 6 7 8; do
      echo -e "\\033[${h};3${f}\\c"
      if [ $b -lt 8 ]; then
        echo -e ";4${b}m\\c"
      else
        echo -e "m\\c"
      fi
      case $f in
      0) echo -e " BLACK \\c" ;;
      1) echo -e "  RED  \\c" ;;
      2) echo -e " GREEN \\c" ;;
      3) echo -e " YELLOW\\c" ;;
      4) echo -e "  BLUE \\c" ;;
      5) echo -e "MAGENTA\\c" ;;
      6) echo -e "  CYAN \\c" ;;
      7) echo -e " WHITE \\c" ;;
      esac
      case $b in
      8) echo -e "\\033[m" ;;
      *) echo -e " \\033[m \\c" ;;
      esac
    done
  done
  echo -e "\\033[${h}m\\c"
  for b in 0 1 2 3 4 5 6 7 8; do
    case $b in
    0) echo -e "(black)  \\c" ;;
    1) echo -e " (red)   \\c" ;;
    2) echo -e "(green)  \\c" ;;
    3) echo -e "(yellow) \\c" ;;
    4) echo -e " (blue)  \\c" ;;
    5) echo -e "(magenta)\\c" ;;
    6) echo -e " (cyan)  \\c" ;;
    7) echo -e "(white)  \\c" ;;
    8) echo -e " (none)\\c" ;;
    esac
  done
  echo -e "\\033[m\\n"
done

backup files

// create backup copy

#!/bin/bash

filename=$1
date=`date +%Y%m%d`

usage () {
        echo "Usage: `basename $0` filename"
}

if [ -z "$filename" -a ! -f "$filename" ]; then
        usage
        exit 1
fi

rev=0
backup="$filename.$date.$rev"

while [ -f $backup ]; do
        let rev+=1
        backup="$filename.$date.$rev"
done

cp $filename $backup
exit $?

snippet

Download code snippets (http://codesnippets.joyent.com) from the command line and convert them to text files using man textutil (on Mac OS X 10.4).

See also: Batch download code snippets, http://codesnippets.joyent.com/posts/show/1840

Usage:
snippet 345
snippet 1268
snippet 1281
snippet 182
snippet 1282
snippet 1115
snippet 5
snippet 23444


# $ cat $HOME/.bashrc

function snippet() {

   declare NL OPWD download_dir outputfile postnum title url

   if [[ "${1//[[:digit:]]/}" != "" ]]; then echo "Argument error. No positive integer: ${1}"; return 1; fi

   postnum="${1}"
   url="http://codesnippets.joyent.com/posts/show/${postnum}"
   download_dir="${HOME}/Desktop/Snippets"
   download_dir="${download_dir%/}"
   #printf "\n\e[0K\e[1;30m%s\e[0m:  %s\n\n" "download directory" "${download_dir}"
   /bin/mkdir -p "${download_dir}"
   OPWD="$PWD"
   cd "${download_dir}"
   /usr/bin/curl -L -O -s --max-time 25 "${url}" || exit 1    # download snippet
   file="${download_dir}/${url##*/}"

   title="$(/usr/bin/sed -E -n -e '/<[tT][iI][tT][lL][eE]>/{s/^.*<[tT][iI][tT][lL][eE]>(.*)<\/[tT][iI][tT][lL][eE]>.*$/\1/p;q;}' "${file}" | \
             sed -E -e 's/\[[^][:space:]]*\]//g')"    # delete [xxx] tag elements of title

   title="${title//CodeSnippets:/}"
   title="${title//\//:}"
   title="${title// /_}"
   title="${title//[[:cntrl:]]/}"
   title="${title%"${title##*[!_]}"}"   # remove trailing "_" characters

   if [[ $title == '_CodeDrive_Snippets_courtesy_of_Peter_Coopers_handy_little_app' ]] || [[ -z "$title" ]]; then
      printf "\e[0K\e[31m%s\e[0m:  %s\n" "couldn't access" "${url}"
      /bin/rm "${file}"
      return 1
   fi

   outputfile="${HOME}/Desktop/Snippets/${postnum}_${title}.txt"
   #outputfile="${outputfile//__/_}"  # uniq underscores

   printf "\n\e[0K\e[1;30m%s\e[0m:  %s\n\n" "saved as" "${outputfile}"

   /usr/bin/textutil -output "${outputfile}" -convert txt "${file}"
   /bin/rm "${file}"

   # escape backslashes
   # man bash 2>/dev/null | less -p 'Each command in a pipeline'
   #outputfile="$(printf "%q" "${outputfile}")"  # cf. help printf
   outputfile="${outputfile//\\/\\\\}"

   NL=$'\\\n'


# get rid of comments (spam)

cat <<EOF | /bin/ed -s "${outputfile}"
H
1,/^Snippets is a public source code repository/d
/(See related posts)$/s/.See related posts.$/${NL}${NL}/
,g/^Comments on this post//^Comments on this post/,\$d
,g/^You need to create an account or log in to//^You need to create an account or log in to/,\$d
,g|^to.* by.* on .*[[:digit:]]$|s|^to\(.*\) by\(.*\) on \(.*[[:digit:]]\)$|${NL}${NL}Author:\2${NL}Date: \3${NL}URL: ${url}${NL}Tags:\1${NL}|
1i

.
wq
EOF

# compare
#,g/^You need to create an account or log in to//^You need to create an account or log in to/,\$d
#,g|^You need to create an account or log in to||^You need to create an account or log in to|,\$d


: <<-'COMMENT'

cat <<EOF | /bin/ed -s "${outputfile}"
H
1,/^Snippets is a public source code repository/d
/(See related posts)$/s/.See related posts.$/${NL}${NL}/
/^Comments on this post/,\$d
,g|^to.* by.* on .*[[:digit:]]$|s|^to\(.*\) by\(.*\) on \(.*[[:digit:]]\)$|${NL}${NL}Author:\2${NL}Date: \3${NL}URL: ${url}${NL}Tags:\1${NL}|
1i

.
wq
EOF


cat <<EOF | /bin/ed -s "${outputfile}"
H
,g/Snippets is a public source code repository/1,/Snippets is a public source code repository/d
,g/You need to create an account or log in to post comments to this site//You need to create an account or log in to post comments to this site/,\$d
,g|(See related posts)$|s|.See related posts.|${NL}${NL}|
,g|^to.* by.* on .*[[:digit:]]$|s|^to\(.*\) by\(.*\) on \(.*[[:digit:]]\)$|${NL}${NL}Author:\2${NL}Date: \3${NL}URL: ${url}${NL}Tags:\1${NL}|
,g|^Comments on this post$|s|\(Comments on this post\)|${NL}\1:|
,g| posts on .* at |s|\(.* posts on .* at .*\)|${NL}\1:|
w
EOF

COMMENT


   cd "$OPWD"
   return 0

}


Rewrite SPAM subject line with procmail

// Remove textdrive's ***SPAM*** addition
// by phearlez
// http://discuss.joyent.com/viewtopic.php?pid=154695#p154695

# Remove the word ***SPAM*** from SpamAssassin's subject line re-write

 :0 fHw
 * ^Subject: \*\*\*SPAM\*\*\*
 | sed -e 's/\*\*\*SPAM\*\*\*//g'

Substrings in Ruby

The other day I was wondering why some really simple Ruby code of mine wasn’t working. The code under test looked something like this:

    def find_directories
        directories = []
        entries = `ls -l`.split/\n/  # get long-format directory listing
        entries.shift   # toss away the totals line
        entries.each do |entry|
            is_directory = (entry[0] == 'd')  # is it a directory?
            directories &lt;&lt; dir if is_directory
        end
        directories
    end

I figured that my ls -l.split/\n/ trickery wasn’t working. So I fired up irb and tried it manually. It worked fine.
Then I sprinkled a few puts statements throughout. entries was fine, and each entry was perfect, looking something like this:
drwx------ 24 jcohen jcohen 816 Aug 19 11:04 Documents

I couldn’t figure out what was wrong. All I had to do was look at the first character of entry; if it was a ‘d’, then I knew I had a directory. But for some reason, is_directory was always false. I googled, checked the RDocs for the String class, thumbed through the PickAxe, and something I read triggered one of those ah-ha moments.
Rats: My C# brain is still alive and kicking.

To confirm my fears, I fired up irb again:

irb> s = "Jeff" 
=> "Jeff" 
irb> s[0]
=> 74

That’s right, folks: on a string, the bracket syntax – when given only one parameter – will return the ASCII value of the character inside. Not the actual character, as it will in C#.
To correctly grab a one-character substring from a string, you have to supply two parameters:

irb> s[0,1]
=> "J" 

Publishing raw code

Here is how to add code to a blog post in a way that you can see the code...so you can show the actual raw code without it actually working.

&lt;strong&gt;hello&lt;/strong&gt;


Just incase the head and tail in the code tags.

This is handy, I can keep this code here, as I was always searching for where I kept this handy info...now I have a place where I can quickly find all my code, and better still I'm sharing it by default.