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!

sudo shell

# cf. http://nevali.net/2006/04/sudo-and-su/
#function sudosh() { /usr/bin/sudo -H -i; return 0; }
alias sudosh='/usr/bin/sudo -H -i'

Test ownership of launchd processes

The following launchd item will execute a simple script every 20 seconds to test or show the ownership of the processes executed by the script. In addition, the script will print out the names and values of its shell environment variables.

To set up the launchd item log in to an admin user account. Use at your own risk.

# LAUNCHD ITEM

/usr/bin/sudo /bin/bash -c '

yourname=$(/usr/bin/logname)
LaunchdPlistFile="/Library/LaunchDaemons/user.${yourname}.launchd.test.plist"
EX_MARK='!'

/bin/cat > "${LaunchdPlistFile}" <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<${EX_MARK}DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabled</key>
        <true/>
        <key>Debug</key>
        <true/>


        <key>UserName</key>
        <string>${yourname}</string>
        <key>GroupName</key>
        <string>${yourname}</string>


        <key>EnvironmentVariables</key>
        <dict>
                <key>PATH</key>
                <string>/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin</string>
                <key>YetAnotherEnvironmentVar</key>
                <string>/path/to/dir</string>
        </dict>
        <key>Label</key>
        <string>user.${yourname}.launchd.test</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Users/${yourname}/Desktop/launchd_test.sh</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceDescription</key>
        <string>Test ownership of launchd processes</string>
        <key>StandardErrorPath</key>
        <string>/Users/${yourname}/Desktop/launchd_test_error.log</string>
        <key>StandardOutPath</key>
        <string>/Users/${yourname}/Desktop/launchd_test.log</string>
        <key>StartInterval</key>
        <integer>20</integer>
        <key>Umask</key>
        <integer>002</integer>
</dict>
</plist>
EOF
'



: <<-'COMMENT'

# switch UserName & GroupName

        <key>UserName</key>
        <string>${yourname}</string>
        <key>GroupName</key>
        <string>${yourname}</string>
or
        <key>UserName</key>
        <string>root</string>
        <key>GroupName</key>
        <string>wheel</string>

or ...

COMMENT


yourname=$(/usr/bin/logname)

LaunchdPlistFile="/Library/LaunchDaemons/user.${yourname}.launchd.test.plist"

open -e "${LaunchdPlistFile}"


# SCRIPT

LaunchdTestScript="/Users/${yourname}/Desktop/launchd_test.sh"

/bin/cat > "${LaunchdTestScript}" <<-'EOF'
#!/bin/bash
# /bin/sh

# cf. man 5 launchd.plist | less -p 'A daemon or agent launched by launchd SHOULD:'
trap '/usr/bin/logger -i "received SIGTERM for launchd test"; exit 1' TERM

# write stdout & stderr to console.log in /Library/Logs/Console/
# open -a Console
# (requires /bin/bash to work correctly!)
#exec >/dev/console 2>&1

echo
echo "SYSTEM LOGS:"
/usr/bin/logger -i "logger:  $0"
/usr/bin/syslog -s -l 1 "syslog:  $0"
echo

echo
echo 'id:'
echo
/usr/bin/id | /usr/bin/sed -E \
   -e $'s/,? /\\\n/g' \
   -e $'/groups=/s/groups=/groups:\\\n/' \
   -e 's/=/ = /g' \
   -e $'s/[()]/   /g'
echo

echo
echo "SHELL: $SHELL"
echo "BASH: $BASH"
echo
echo "current set of shell flags: $-"    # cf. help set
echo
echo "SHELLOPTS: $SHELLOPTS"
echo
echo 'set:'
echo
set
echo
printf "%q  %q\n" "IFS:" "$IFS"
echo
echo 'env:'
echo
/usr/bin/env
echo
echo
echo 'shopt ... on:'
echo
shopt | /usr/bin/egrep 'on$'
#set -o | /usr/bin/egrep 'on$'
echo


cd ~
echo "HOME: $PWD"
echo
echo 'try to cd to /private/var/launchd/0'
cd /private/var/launchd/0
return_code=$?
echo "cd exit status: ${return_code}"
echo
if [[ ${return_code} -eq 0 ]]; then echo "ROOT PRIVILEGES"; else echo "NO ROOT PRIVILEGES"; fi
echo

echo "PPID:  $PPID"
echo
echo "PID:  $$"
echo

echo 'ps -p PID:'
echo
/bin/ps -p $PPID
echo
/bin/ps -p $$
echo
echo 'lsof -p PID:'
echo
/usr/sbin/lsof -p $PPID 2>/dev/null
echo
/usr/sbin/lsof -p $$ 2>/dev/null
echo

echo "users:  $(/usr/bin/users)"
echo
echo "groups:  $(/usr/bin/groups)"    # /usr/bin/id -Gn
echo
echo "logname:  $(/usr/bin/logname)"
echo
echo "whoami:  $(/usr/bin/whoami)"   # /usr/bin/id -un


echo; echo
echo "#----------------------------------------------------------------------------------------------- $(date)"
echo; echo

exit 0
#exit 1

EOF



open -e "${LaunchdPlistFile}"
open -e "${LaunchdTestScript}"

/usr/bin/sudo /usr/sbin/chown root:wheel "${LaunchdPlistFile}"
/usr/bin/sudo /bin/chmod 0644 "${LaunchdPlistFile}"

/usr/sbin/chown ${yourname}:${yourname} "${LaunchdTestScript}"
/bin/chmod u+x "${LaunchdTestScript}"

ls -l "${LaunchdPlistFile}"
ls -l "${LaunchdTestScript}"


# enable launchd item
/usr/bin/sudo /bin/launchctl load -w "${LaunchdPlistFile}" 2>/dev/null

# disable launchd item
/usr/bin/sudo /bin/launchctl unload -w "${LaunchdPlistFile}" 2>/dev/null

ls -l /Users/${yourname}/Desktop/launchd_test.log
ls -l /Users/${yourname}/Desktop/launchd_test_error.log

open -a Console /Users/${yourname}/Desktop/launchd_test.log
#/usr/bin/srm -v /Users/${yourname}/Desktop/launchd_test.log

open -a Console /Users/${yourname}/Desktop/launchd_test_error.log


/usr/bin/sudo /bin/launchctl list
/usr/bin/sudo /usr/bin/fs_usage  | /usr/bin/egrep -i launchd_test


# convert possible tabs to spaces
#/usr/bin/expand "${LaunchdPlistFile}" > ~/Desktop/user.${yourname}.launchd.test.plist
#open -e ~/Desktop/user.${yourname}.launchd.test.plist


man 8 launchd
man 5 launchd.plist
man 5 launchd.conf
man 1 launchctl


#----------------------------------------------------------------


# set launchd log level to debug
# cf. http://www.puredarwin.org/developers/booting/launchd
# sudo launchctl log level debug
sudo bash -c 'echo "log level debug" >> /private/etc/launchd.conf'
echo 'log level debug' >> ${HOME}/.launchd.conf

sudo nano /private/etc/launchd.conf
ls -l /private/etc/launchd.conf


# send all launchd logging output to /private/var/log/launchd.log
# cf. http://developer.apple.com/technotes/tn2004/tn2124.html#SECLAUNCHDLOGGING
sudo cp -ip /etc/syslog.conf /etc/syslog.conf-orig
(cat /etc/syslog.conf-orig ; echo "launchd.* /var/log/launchd.log" ) | sudo cp /dev/stdin /etc/syslog.conf
sudo kill -HUP `cat /var/run/syslog.pid`

ls -1 /private/var/log/*log
ls -l /private/var/log/launchd.log

open -a Console /private/var/log/launchd.log


Further information on launchd:

- Getting started with launchd
- AFP548: launchd in Depth
- Wikipedia: launchd
- Mac OS Forge: launchd
- PureDarwin: launchd
- Mac OS X Debugging Magic: launchd
- Daemons and Agents
- Daemons and Agents: Execution Contexts
- Daemons and Agents: Hints and Tips
- Mac OS X Server 10.5: Setting a custom umask
- launchd gotcha
- Re: how to run scripts at shutdown - how does launchd shutdown a system?
- Starting PostgreSQL 8.3 through launchd on Mac OS X 10.5.1 Leopard
- The Future of Init, Part IIb: OS X Launchd

CSS Global Reset w/ strong, em

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-weight: inherit;
    font-style: inherit;
    font-size: 100%;
    font-family: inherit;
    vertical-align: baseline;
    background: transparent;
}

:focus {
    outline: 0;
}

body {
	
}

ol, ul {list-style: none;}

caption, th, td {
  text-align: left;
  font-weight: normal;
}

blockquote:before, blockquote:after, q:before, q:after {content: "";}
blockquote, q {quotes: "" "";}

strong{font-weight: bold;}
em{font-style: italic;}
.clear{clear: both;}

#content:after{
  content: ".";
  height: 0;
  display: block;
  clear: both;
  visibility: hidden;
}

.left, #left{
	float: left;
	display: inline;
}

.right, #right{
	float: right;
	display: inline;
}

CSS Clear

#something:after{
 content: ".";
  height: 0;
  display: block;
  clear: both;
  visibility: hidden;
}

iregex

function iregex() {
   declare escaped_str iregexstr lower upper
   escaped_str="$(printf "%q" "${1}")"
   iregexstr=
   lower="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:upper:]]' '[[:lower:]]')"
   upper="$(printf "%s" "${escaped_str}" | /usr/bin/tr '[[:lower:]]' '[[:upper:]]')"

   for ((i=0; i < "${#lower}"; i++)); do
      iregexstr="${iregexstr}[${lower:${i}:1}${upper:${i}:1}]"
   done

   printf "%s" "${iregexstr}" | /usr/bin/sed -E -e 's/\[([[:space:]])[[:space:]]\]/\1/g'  -e 's/\[([[:punct:]])[[:punct:]]\]/\1/g'
   return 0
}


iregex 'hello \ | / again!?'
re="$(iregex 'hello \ | / again!?')"


# replace the following string
string='helLo \ | / again!?'

re_str='hello \ | / again!?'
iregex "${re_str}"
regex="$(iregex "${re_str}")"   # always use iregex "${re_str}"
echo "${regex}"

echo "${string}" | sed "s/${regex}/replacement worked/g"   # / not escaped in regex
echo "${string}" | sed "s|${regex}|replacement worked|g"   # always use "s|${re}|replacement|"


# note: printf does not escape / to \/ in function iregex above
#printf "%q\n" "/|\ "
printf "%q\n" '/|\'   


# cf. gnused, http://codesnippets.joyent.com/posts/show/1835
string='helLo \ | / again!?'
echo "${string}" | gnused 's/hello \\ | \/ again!?/replacement worked/ig'
echo "${string}" | gnused 's|hello \\ \| / again!?|replacement worked|ig'


#---------------------------------------------------------


# replace the following string containing a tab character \t
string=$'helLo \ | / \tagain!?'
echo "${string}"
iregex "${string}"


re_str1='hello \ | / '
re_str2=$'\t'
re_str3='again!?'

re1="$(iregex "${re_str1}")"
re2="${re_str2}"
re3="$(iregex "${re_str3}")"

echo "${string}" | sed "s|${re1}${re2}${re3}|replacement worked|g"

echo "${string}" | gnused 's|hello \\ \| / \tagain!?|replacement worked|ig'


#---------------------------------------------------------


TAB=$'\t'

echo $'abc\tdef'
echo $'abc\tdef' | sed $'s/\t//'
echo $'abc\tdef' | sed s/$'\t'//
echo $'abc\tdef' | sed "s/${TAB}//"

echo $'abc\tdef' | sed $'s/\t/TAB/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed $'s/TAB/\t/'
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed s/TAB/$'\t'/
echo $'abc\tdef' | sed $'s/\t/TAB/' | sed "s/TAB/${TAB}/"


# gnused

echo $'abc\tdef' | sed 's/\t/TAB/'
echo $'abc\tdef' | gnused 's/\t/TAB/'

echo $'abc\tdef' | gnused $'s/\t/TAB/'
echo $'abc\tdef' | gnused "s/${TAB}/TAB/"


echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused $'s/TAB/\t/'
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused s/TAB/$'\t'/
echo $'abc\tdef' | gnused $'s/\t/TAB/' | gnused "s/TAB/${TAB}/"

echo $'abc\tdef' | gnused 's/\t/TAB/' | gnused 's/TAB/\t/'

Debugging a file name with a backslash character in Bash

# create a file name containing a backslash character \
file=${HOME}/Desktop/'te:st\file'.txt
echo "${file}"
echo "${file}" | sed -n -e 'l'

echo 'This is a test case for a file name containing a backslash \ character!' > "${file}"
open -e "${file}"

set -vx

# note: avoid trailing spaces in ed commands
cat <<EOF | /bin/ed -s "${file}"
H
,g|^This|s|test case|SUCCESSFUL TEST CASE|
w
EOF

open -e "${file}"


# escape backslashes
cat <<EOF | /bin/ed -s "${file//\\/\\\\}"
H
,g|^This|s|test case|SUCCESSFUL TEST CASE|
w
EOF

open -e "${file}"


# printf "%q"
help printf | sed -E "s/(%q)/$(printf '\e[1m\\1\e[m')/"
echo "${file}"
echo "$(printf "%q" "${file}")"   # cf. help printf
echo "$(printf "%q" "${file}")" | sed -n -e 'l'

# escape file name
cat <<EOF | /bin/ed -s "$(printf "%q" "${file}")"
H
,g|^This|s|backslash|BACKSLASH|
w
EOF

open -e "${file}"


echo "${file}"
echo "${file}" | sed -n -e 'l'

file="${file//\\/\\\\}"
echo "${file}"
echo "${file}" | sed -n -e 'l'


# references
man bash 2>/dev/null | less -p 'backslash'
man bash 2>/dev/null | less -p 'Each command in a pipeline'
man bash 2>/dev/null | less -p 'Functions are executed'
help printf | sed -E "s/(%q)/$(printf '\e[1m\\1\e[m')/"
open http://en.wikipedia.org/wiki/Filename


# "Each command in a pipeline is executed as a separate process (i.e., in a subshell)."
# From: man bash

# "Functions are executed in the context of the current shell; no new process is created to 
# interpret  them (contrast this with the execution of a shell script)."
# From: man bash

# "Unix-like systems are an exception, as the only control character forbidden in file names 
# is the null character, as that's the end-of-string indicator in C. Trivially, Unix also 
# excludes the path separator / from appearing in filenames."
# From: http://en.wikipedia.org/wiki/Filename

Contact form with dropdowns and radio buttons

This is how a contact form with select dropdown and radio buttons may look like.

<txp:zem_contact_text label="Full Name" name="Name" required="1" min="2" max="40" /><br />
<txp:zem_contact_email required="1" /><br />
<txp:zem_contact_text label="Phone (optional)" min=7 max=15 required="0" /><br />

<txp:zem_contact_text label="Building Address" name="Name" required="1" min="2" max="60" /><br />
<txp:zem_contact_text label="Unit #" name="Name" required="1" min="2" max="40" /><br />

<txp:zem_contact_select break="br" label="Pets" list="None, Cat, Dog, Other" /><br />


<txp:zem_contact_select break="br" label="What needs fixed?" list="Bedroom, Bathroom, Kitchen, Dining Room, Living Room, Outdoor Area" /><br />

<txp:zem_contact_textarea label="Description goes here" cols="40" rows="10"  /><br />

Check off one of the following;<br />
<txp:zem_contact_checkbox label="I give permission for maintenance to enter my unit." required="0" /><br />
<txp:zem_contact_checkbox label="Please call to set up time for maintenance to enter my unit" required="0" /><br />

<txp:zem_contact_submit label="Submit" />



And then simply insert the following into an article
<txp:zem_contact to="email@email.com" form="form_name" />

Subpage Listing Form and Page Template

how to show subpages/secondary pages for a section in the sidebar

<li><a href="<txp:permlink />"><txp:title /></a></li>



and this is the page template
     <txp:if_section name="home">
       <h2 class="subpage"><txp:section title="1" /></h2>
       <ul id="subpage"><txp:article_custom section="home" form="subpagelist" sort="Title asc" />
       </ul>
     </txp:if_section>

Rails numbered migrations instead of timestamps

change migrations to the old rails way of just version numbers instead of the mysql timestamp. Only recommended if a few people are working on a project.
config.active_record.timestamped_migrations = false

Horizontal Navigation

how to build horizontal navigation
<div id="nav">

    <ul id="navlist">

<txp:section name="home" link="1" title="1" wraptag="li" />
<txp:section name="about" link="1" title="1" wraptag="li" />
<txp:section name="portfolio" link="1" title="1" wraptag="li" />
<txp:section name="packages" link="1" title="1" wraptag="li" />
<txp:section name="clientlogin" link="1" title="1" wraptag="li" />
<txp:section name="contact" link="1" title="1" wraptag="li" />
  </ul>
</div><!-- end nav-->