Never been to TextSnippets 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!)

« Newer Snippets
Older Snippets »
Showing 21-40 of 77 total

Launchd item for starting MySQL

This will start MySQL with a low priority on reboot

<?xml version="1.0" encoding="UTF-8"?>
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>Labelkey>
        com.mysql.MySQL</string>
        <key>LowPriorityIOkey>
        />
        <key>ProgramArgumentskey>
        
                /usr/local/mysql/bin/mysqld_safestring>
        </array>
        <key>RunAtLoadkey>
        />
dict>
</plist>

Refresh rate in Vienna

Change the default refresh rate in seconds for the Vienna RSS reader to whatever you want. Anything less than 1800 seconds might be considered bad netiquette, but it's useful if you're only subscribed to internal feeds (e.g., activeCollab, Connector).

defaults write uk.co.opencommunity.vienna2 CheckFrequencyInSeconds 60

load/unload postgres (via ports) launch deamon

Enable or disable the automatic launch of the postgresql server installed via macports. Starts or stops the daemon and modifies the launchd manifest.

launchctl load -w /opt/local/etc/LaunchDaemons/org.darwinports.postgresql81-server/org.darwinports.postgresql81-server.plist

launchctl unload -w /opt/local/etc/LaunchDaemons/org.darwinports.postgresql81-server/org.darwinports.postgresql81-server.plist

quicksilver tags in geektool script version 3

// can anyone tell me what this is? Is it applescript?
How do I call it from geektool? I found this here
http://theappleblog.com/community/development/588-displaying-quicksiler-tags/#post6596

set QuicksilverTags to (path to home folder as string) & "Library:Caches:Quicksilver:Indexes:QSPresetQSFileTagsPlugIn.qsindex"

do shell script "grep string " & (quoted form of POSIX path of QuicksilverTags) & " | awk {'print $1'}"

set theTags to result

--> From the MacScripter.net Text Delimiters Tutorial.
set newText to switchText of theTags from "qs.tag.file" to ""
to switchText of currentText from SearchString to ReplaceString
        set storedDelimiters to AppleScript's text item delimiters
        set AppleScript's text item delimiters to SearchString
        set currentText to currentText's text items
        set AppleScript's text item delimiters to ReplaceString
        set currentText to currentText as Unicode text
        set AppleScript's text item delimiters to storedDelimiters
        
        currentText
        
        set this_text to currentText
        
        set new_text to ""
        
        --> From the MacScripter Forum.
        repeat with myPara in paragraphs of this_text
                if new_text does not contain myPara then set new_text to new_text & myPara & return
        end repeat
        set new_text to (characters 1 thru -2 of new_text) as text
        
        set more_text to new_text
        set replace_text to ""
        
        --> From MacScripter Forum.
        repeat with myPara in paragraphs of more_text
                
                if replace_text does not contain myPara then set replace_text to replace_text & (text 9 thru -10 of myPara) & return
        end repeat
        
        set output to "Tags: " & return & replace_text
        
end switchText -- the end of the handler.

quicksilver tags in geektool

// this code taken from http://bbs.applescript.net/viewtopic.php?id=20330

do shell script "grep string /Users/username/Desktop/QSPresetQSFileTagsPlugIn.qsindex | awk {'print $1'}"

set theTags to result

set newText to switchText of theTags from "qs.tag.file" to ""

to switchText of currentText from SearchString to ReplaceString -- the handler
   
   set storedDelimiters to AppleScript's text item delimiters
   -- this simply stores the current value of AppleScript's AppleScript's text item delimiters
   -- so they can be restored later (thus helping to avoid potential problems elsewhere).
   -- Remember, we always set them back to what they were.
   
   set AppleScript's text item delimiters to SearchString
   -- AppleScript's AppleScript's text item delimiters are now set to "Purple"
   
   set currentText to currentText's text items -- note we have changed currentText's value
   -- create a list of text items from the original text, separated at the points where the
   -- current text item delimiter ("Purple") appeared.
   --> {"What, ", " Shoes?"} - Note that the spaces and punctuation are retained.
   
   set AppleScript's text item delimiters to ReplaceString
   -- AppleScript's AppleScript's text item delimiters are now set to "Green"
   
   set currentText to currentText as Unicode text
   -- coerce the list {"What, ", " Shoes?"} to Unicode text. This operation will also
   -- insert the current value of AppleScript's AppleScript's text item delimiters ("Green")
   -- between each of the listed items
   
   --> "What, Green Shoes?"
   
   set AppleScript's text item delimiters to storedDelimiters
   -- restore the value of AppleScript's AppleScript's text item delimiters
   -- to whatever they were on entering the subroutine. Remember that a call to this
   -- might have been made from within a section of script that had the TIDs set to
   -- something else. Hand the result back with the TIDs as they were.
   
   currentText
   -- return the now modified text (and restored TIDs) -- "What, Green Shoes?"
   
   
   set this_text to currentText
   
   set new_text to ""
   
   --Loop through paragraphs of old text
   repeat with myPara in paragraphs of this_text
       --Check for paragraph’s contents in new text
       --If not there add new text to end of new text
       if new_text does not contain myPara then set new_text to new_text & myPara & return
   end repeat
   --Remove final return
   set new_text to (characters 1 thru -2 of new_text) as text
   
end switchText -- the end of the handler.

Display Quicksilver (Finder Spotlight Info) Tags in Geektool

// stick this into the terminal it generates a text file that you can display with geektool
grep string /Users/username/Library/Caches/Quicksilver/Indexes/QSPresetQSFileTagsPlugIn.qsindex | awk {'print $1'}  > /Users/username/Desktop/tags.txt

Find out if a mac is PPC/Intel in bash

// This checks the processor type in bash

if [[ `sysctl hw.machine` = "hw.machine: Power Macintosh" ]]; then 
        PROCESSOR='PowerPC'
else
        PROCESSOR='Intel'
fi

Make iTunes arrows point to your own music, not the iTS

defaults write com.apple.iTunes invertStoreLinks -bool YES


This makes those little right-pointing arrows in iTunes point to your library, not the iTunes Store. If you want the iTunes Store, Option-click instead.

Convert plist files from binary to xml and back again

Enter these two commands into the terminal to toggle plist preferences files between XML and Binary

To convert a binary .plist file to XML format for editing, type this in the Terminal:
plutil -convert xml1 some_file.plist

To convert an XML .plist file to binary for use:
plutil -convert binary1 some_other_file.plist

XML or HTML Tag Parser

This handler is intended to accept a string input, and remove the contents of a specific tag within that sting input. This is great for getting string contents out of xml or html files. For example, if you want to get the title of an html document you call
tagParse(yourFileContents, "", ")
it would return the text between the two title tags.
on tagParse(thisText, openTag, closeTag)
        set new_text to ""
        set strlen to the length of thisText
        set taglen to (the length of openTag) - 1
        set closeTagLen to (the length of closeTag) - 1
        set stridx to 1
        repeat until (stridx + taglen) is greater than strlen
                set thisString to the contents of characters stridx through (stridx + taglen) of thisText as text
                log thisString
                if thisString is openTag then
                        set firstChar to stridx + taglen + 1
                        --display dialog "the title text starts at character " & firstChar
                        repeat until (stridx + closeTagLen) is greater than strlen
                                set thisString to the contents of characters stridx through (stridx + closeTagLen) of thisText as text
                                log thisString
                                if thisString is closeTag then
                                        return the contents of characters firstChar through (stridx - 1) of thisText as text
                                end if
                                set stridx to stridx + 1
                        end repeat
                end if
                set stridx to stridx + 1
        end repeat
        return "Error:: tag " & openTag & " not found."
end tagParse

Log items to tab delimited text file

this script is intended to be used to write logs to a tab delimited text file

logfilename is a string
theFields must be a list
logfilename is just the name of your log file

on logFile(theFields, logFileName)
        try
                tell application "Finder"
                        if not (file ((path to desktop folder as text) & logFileName) exists) then
                                set theLogFile to make file at folder (path to desktop folder as text)
                                set the name of theLogFile to logFileName
                                set myFile to open for access file ((path to desktop folder as text) & logFileName) with write permission
                        else
                                set myFile to open for access file ((path to desktop folder as text) & logFileName) with write permission
                        end if
                        set endOfFile to get eof myFile
                        repeat with eachField in theFields
                                set theFieldString to theFieldString & item eachField of theFields & tab
                        end repeat
                        write (theFieldString & return) to myFile starting at (endOfFile + 1)
                        close access myFile
                end tell
        on error err
                display dialog "log file error" & err giving up after 5
                try
                        close access ((path to desktop folder as text) & logFileName)
                end try
        end try
end logFile

Folder Maker

This handler creates a folder of name NameOnly to the location of thePath.
thePath is the path to the folder you want the folder to be created in
NameOnly is the name you want to give the folder

both handler inputs should be strings (e.g. Drive:folder:)
on folderMaker(thePath, NameOnly)
        tell application "Finder"
                if (folder (thePath & NameOnly) exists) is not true then
                        try
                                make new folder at folder (thePath) with properties {name:NameOnly}
                        on error the_error
                                display dialog the_error giving up after 10
                        end try
                end if
        end tell
end folderMaker

Remove Files older than X days

This script is intended to be in your script menu, or run as an applet.
It will ask you to choose a path to a folder that you want to clear out
files older then X days. It runs very fast because it uses the do shell
script command rather than the finder to get the time stamp of the
file. It's safe to use on network drives as well.
try
        set myFolder to (choose folder)
        set myTime to display dialog "Delete files older than how many days?" default answer "60"
        set myWildcard to display dialog "Enter a wildcard search string." default answer "PV*.txt"
        set myScript to "find \"" & POSIX path of myFolder & "\" -type f -name \"" & text returned of myWildcard & "\" -mtime +" & text returned of myTime & " -exec rm {} \\;"
        do shell script myScript
        display dialog "Deletion completed successfully"
on error err
        display dialog err
end try

Load Text File to string

The purpose of this handler is to load a text file from a posix path to a string

on loadTextFile(thepath)
        try
                set thestring to ""
                set theScript to ("cat " & "'" & thepath & "'")
                set thestring to do shell script theScript
                return thestring
        on error err
                log ("Cat text file error: " & err)
        end try
end loadTextFile

Is a file busy

Uses a do shell script to search for busy files

on isFileBusy(thePath)
--Tests to see if a file is in use
        try
                set myscript to "if ( lsof -Fp " & thePath & " | grep -q p[0-9]* ) then echo 'file is busy'; else echo 'not busy';fi"
                set myResult to do shell script myscript
                if myResult is "file is busy" then
                        return true
                else
                        return false
                end if
        on error err
                Display Dialog ("Error: isFileBusy " & err) giving up after 5
        end try
end isFileBusy

Mount Multiple Volumes or Disks

This snippet will mount required drives for your scripts. set the requiredDrives

set requiredDrives to {{theName:"drive1name", theMountScript:"afp://username:password@ip/drive1name"}, {theName:"drive2name", theMountScript:"afp://username:password@ip/drive2name"}} as list

set theDisks to list disks

repeat with i from 1 to (length of requiredDrives)
        if theDisks does not contain theName of item i of requiredDrives then
                mount volume theMountScript of item i of requiredDrives
        end if
end repeat

AppleScript String Parsing

This example will find the word "work" in the string "Bob went to work." and replace it with "the beach".

set myResult to snr("Bob went to work.", "work", "the beach")
display dialog myResult

(**** fast search and replace methods ****)
on snr(the_string, search_string, replace_string)
        return my list_to_string((my string_to_list(the_string, search_string)), replace_string)
end snr

on list_to_string(the_list, the_delim)
        my atid(the_delim)
        set the_string to (every text item of the_list) as string
        my atid("")
        return the_string
end list_to_string

on string_to_list(the_string, the_delim)
        my atid(the_delim)
        set the_list to (every text item of the_string) as list
        my atid("")
        return the_list
end string_to_list

on atid(the_delim)
        set AppleScript's text item delimiters to the_delim
end atid

Sort Apple Clipboard Contents

This applescript will convert anything in the finder clipboard to text, and then sort that text. Procedure is to copy an item. Run this script from the script menu, then paste.

set the clipboard to list_to_string(ASCII_Sort(string_to_listclass ktxt» of ((the clipboard as text) as record), return)), return)

on ASCII_Sort(my_list)
        --from apple
        set the index_list to {}
        set the sorted_list to {}
        repeat (the number of items in my_list) times
                set the low_item to ""
                repeat with i from 1 to (number of items in my_list)
                        if i is not in the index_list then
                                set this_item to item i of my_list as text
                                if the low_item is "" then
                                        set the low_item to this_item
                                        set the low_item_index to i
                                else if this_item comes before the low_item then
                                        set the low_item to this_item
                                        set the low_item_index to i
                                end if
                        end if
                end repeat
                set the end of sorted_list to the low_item
                set the end of the index_list to the low_item_index
        end repeat
        return the sorted_list
end ASCII_Sort


on snr(the_string, search_string, replace_string)
        return my list_to_string((my list_to_string(the_string, search_string)), replace_string)
end snr

on list_to_string(the_list, the_delim)
        my atid(the_delim)
        set the_string to (every text item of the_list) as string
        my atid("")
        return the_string
end list_to_string

on string_to_list(the_string, the_delim)
        my atid(the_delim)
        set the_list to (every text item of the_string) as list
        my atid("")
        return the_list
end string_to_list

on atid(the_delim)
        set AppleScript's text item delimiters to the_delim
end atid

Memcached StartupItem for Mac OS X


/Library/StartupItems/Memcached/StartupParameters.plist

{
  Provides        = ("Memcached");
  Description     = "Memcache Daemon";
  Uses            = ("Network");
  OrderPreference = "None";
}


/Library/StartupItems/Memcached/Memcached

#!/bin/bash
#
# /Library/StartupItems/Memcached/Memcached
#
# Script to startup memcached with OS X. Tested on 10.4 Tiger
#
# To enable, copy this file and StartupParameters.plist to
# /Library/StartupItems/Memcached and add "MEMCACHED=-YES-"
# to /etc/hostconfig ... You can then reboot or execute 
# "sudo StartItem start Memcached" from a terminal to start
# it up.
#
# I should mention that this file uses my preferred development 
# settings. You can edit them before copying this script over 
# or they can be overriden by creating a config file named 
# memcached.conf in /etc, /opt/etc, or /usr/local/etc with the 
# following contents (modified to suit, of course):
#
#   MEMCACHED_EXE=/usr/local/bin/memcached
#   MEMCACHED_PIDFILE=/var/run/memcached.pid
#   MEMCACHED_MAX_MEM=128
#   MEMCACHED_INTERFACE=127.0.0.1
#   MEMCACHED_PORT=1121
#   MEMCACHED_RUN_AS=nobody 
#
# ------------------------------------------------------------------- 
# NOTE: Memcached < 1.2.0 has issues specifying the interface via the
# '-l' switch on the Mac for some reason so if the service fails to 
# start with the following error:
#
#    bind(): Can't assign requested address
#    failed to listen
#
# then you will need to either upgrade to version 1.2.0+ or forgo
# specifying an interface to listen on by removing the references
# to A_INTERFACE on lines 65 and 75 of this script. 
# ------------------------------------------------------------------- 
#
# Tim Ferrell 
#

# Suppress the annoying "$1: unbound variable" error 
if [ -z $1 ] ; then
  echo "Usage: $0 [start|stop|restart] "
  exit 1
fi

# Source the common setup functions for startup scripts
test -r /etc/rc.common || exit 1
source /etc/rc.common

NAME=memcached
DESC="Memcached server"

# look for a config file name ${NAME}.conf in /etc, /opt/etc, 
# and /usr/local/etc ... in that order.
[ -r /etc/${NAME}.conf ] && source /etc/${NAME}.conf
[ -r /opt/etc/${NAME}.conf ] && source /opt/etc/${NAME}.conf
[ -r /usr/local/etc/${NAME}.conf ] && source /usr/local/etc/${NAME}.conf

# these are _my_ defaults... 
DAEMON="${MEMCACHED_EXE:=/usr/local/bin/memcached}"
A_PIDFILE="-P ${MEMCACHED_PIDFILE:=/var/run/memcached.pid}"
A_MAXMEM="-m ${MEMCACHED_MAX_MEM:=128}"
A_INTERFACE="-l ${MEMCACHED_INTERFACE:=127.0.0.1}"
A_PORT="-p ${MEMCACHED_PORT:=11211}"
A_RUNAS="-u ${MEMCACHED_RUN_AS:=nobody}"

StartService () 
{
  if [ "${MEMCACHED:=-NO-}" = "-YES-" ] && ! GetPID ${NAME} > /dev/null; then
    if [ -f /var/run/${NAME}.StartupItem ] ; then exit ; fi
    touch /var/run/${NAME}.StartupItem
    echo "Starting ${DESC}"
    ${DAEMON} -d ${A_PIDFILE} ${A_MAXMEM} ${A_INTERFACE} ${A_PORT} ${A_RUNAS} 
  fi
}

StopService ()
{
  if PID=$(GetPID ${NAME}); then
    echo "Stopping ${DESC}, (PID ${PID})"
    kill -TERM "${PID}"
    rm -f ${A_PIDFILE}
  else
    echo "${DESC} not running."
  fi
  rm -f /var/run/${NAME}.StartupItem
}

RestartService () { StopService; StartService; }

if test -x $DAEMON ; then
  RunService "$1"
else
  echo "Could not find ${DAEMON}!"
fi


Generate DSA Keys

// generates SSH DSA keys in ~/.ssh/

ssh-keygen -d
« Newer Snippets
Older Snippets »
Showing 21-40 of 77 total