<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ronald! &#187; scripting</title>
	<atom:link href="http://www.rchu.nl/tag/scripting/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rchu.nl</link>
	<description>My own little corner of the world wide web</description>
	<lastBuildDate>Mon, 12 Jul 2010 23:44:52 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Some nice layout changes</title>
		<link>http://www.rchu.nl/2010/04/some-nice-layout-changes/</link>
		<comments>http://www.rchu.nl/2010/04/some-nice-layout-changes/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 18:27:36 +0000</pubDate>
		<dc:creator>ronald</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[LJ Crosspost]]></category>
		<category><![CDATA[Website]]></category>
		<category><![CDATA[applescript]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://www.rchu.nl/?p=444</guid>
		<description><![CDATA[My Wordpress powered website has been running for quite some time now, and today I finally replaced the default theme with something I like better,  Suffusion, and customized it to my needs.
I had installed some syntax highlighting plugins before but disabled them because I couldn&#8217;t get it to work properly. Now with the pretty new [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-449" title="Source code" src="http://www.rchu.nl/wordpress/wp-content/uploads/Screen-shot-2010-04-05-at-19.33.47.png" alt="Source code" width="287" height="225" />My Wordpress powered website has been running for quite some time now, and today I finally replaced the default theme with something I like better,  <a href="http://wordpress.org/extend/themes/suffusion">Suffusion,</a> and customized it to my needs.</p>
<p>I had installed some syntax highlighting plugins before but disabled them because I couldn&#8217;t get it to work properly. Now with the pretty new layout all posts with snippets of unhighlighted source code were a real eye-sore, so that needed to be fixed as wel.</p>
<p><span id="more-444"></span>For some unknown reason the <a href="http://wordpress.org/extend/plugins/syntaxhighlighter/">SyntaxHighlighter Evolved</a> plugin that I couldn&#8217;t get to do as I wanted before now works like a charm. The only difficult part was to get me some <a href="http://developer.apple.com/AppleScript/">AppleScript </a>highlighting. <a href="http://davidchambersdesign.com/applescript-syntax-highlighting/">David Chambers</a> has written a brush, so I only had to install that brush the <a href="http://www.viper007bond.com/wordpress-plugins/syntaxhighlighter/adding-a-new-brush-language/">proper way</a>. Creating the plugin was easy:</p>
<pre class="brush: php;">
&lt;?php
/*
Plugin Name: SyntaxHighlighter Evolved: AppleScript Brush
Description: Adds support for the Applescript language to the SyntaxHighlighter Evolved plugin.
Author: Ronald Chu
Version: 1.0.0
Author URI: http://www.rchu.nl/
*/

// SyntaxHighlighter Evolved doesn't do anything until early in the &quot;init&quot; hook, so best to wait until after that
add_action( 'init', 'syntaxhighlighter_applescript_regscript' );

// Tell SyntaxHighlighter Evolved about this new language/brush
add_filter( 'syntaxhighlighter_brushes', 'syntaxhighlighter_applescript_addlang' );

// Register the brush file with WordPress
function syntaxhighlighter_applescript_regscript() {
 wp_register_script( 'syntaxhighlighter-brush-applescript', plugins_url( 'shBrushAppleScript.js', __FILE__ ), array('syntaxhighlighter-core'), '1.2.3' );
}

// Filter SyntaxHighlighter Evolved's language array
function syntaxhighlighter_applescript_addlang( $brushes ) {
 $brushes['applescript'] = 'applescript';
 $brushes['osascript'] = 'applescript';

 return $brushes;
}
?&gt;
</pre>
<p>But at first the highlighting did not work on AppleScript snippets, and it took me quite some time to find out that I shouldn&#8217;t have copy-pasted the javascriptcode into <a href="http://www.vim.org/about.php">Vim</a> on my ssh shell. Some of the special characters in line 37 were transformed into in a question mark which broke the regular expression.</p>
<p>Now, as far as I know, only one thing is wrong; when I refresh quickly in Chrome (5.0.342.7 beta, OS X 10.6.2) some of the keywords do not light up. I do not know if it is a bug in Chome, SyntaxHighighter or the AppleScript brush, but it is something I can live with for now.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rchu.nl/2010/04/some-nice-layout-changes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GeekTool</title>
		<link>http://www.rchu.nl/2009/06/geektool/</link>
		<comments>http://www.rchu.nl/2009/06/geektool/#comments</comments>
		<pubDate>Sat, 06 Jun 2009 14:59:00 +0000</pubDate>
		<dc:creator>ronald</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[LJ Crosspost]]></category>
		<category><![CDATA[applescript]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[macbook]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.rchu.nl/?p=306</guid>
		<description><![CDATA[The past couple of days I&#8217;ve been playing around with GeekTool a nifty litlle application that can show text files, unix commands output (including scripts), or images (local and from the internet) on your desktop.  There are many sites with examples out there which inspired me to create a GeekTool setup of my own.
I started [...]]]></description>
			<content:encoded><![CDATA[<p><a title="My GeekTool powered desktop" href="http://www.rchu.nl/wordpress/wp-content/uploads/picture-3.png"><img class="size-medium wp-image-337 alignright" title="GeekTool Desktop" src="http://www.rchu.nl/wordpress/wp-content/uploads/picture-3-300x187.png" alt="GeekTool Desktop" width="300" height="187" /></a>The past couple of days I&#8217;ve been playing around with <a href="http://projects.tynsoe.org/en/geektool/">GeekTool</a> a nifty litlle application that can show text files, unix commands output (including scripts), or images (local and from the internet) on your desktop.  There are many <a href="http://www.paulpeelen.com/2009/05/27/geektools-desktop-enhancing/">sites</a> <a href="http://www.macosxhints.com/article.php?story=20090326125916351">with</a> <a href="http://www.keynote2keynote.com/2007/04/10/ultimate-geektool-setup-pimp-your-desktop-part-2/">examples</a> out there which inspired me to create a GeekTool setup of my own.</p>
<p>I started playing around with several scripts and GeekTool because it looked cool at first and it was fun to do some shell scripting. As the amount of information displayed on my desktop grew I started wondering why I was creating a lot of small processes taking up a little CPU time. I hardly ever look at my desktop because of all the windows in front of it. But the stats now on my desktop are easily accesable with one key (F11), and some starts are already displayed in either the menu bar or my <a href="http://www.islayer.com/apps/istatpro/">iStat Pro</a> widget. Removing it there gives me more room in the menu bar (which is starting grow full of icons) and saves some resources used by the widget.</p>
<p>Now I shall explain the GeekTool entries I created more detailed.</p>
<p><span id="more-306"></span></p>
<h2>Battery</h2>
<p>You can get a lot of information about your battery with the <code>ioreg</code> command. I found a <a href="http://www.mitt-eget.com/software/macosx/">battery status script </a>which doesn&#8217;t work on leopard but with plenty of comment in the code to use it as a reference for the output of <code>ioreg</code> and write a little script of my own which prints the status, charge and time remaining. The code should be pretty self-explanatory.</p>
<pre class="brush: bash;">
#! /bin/sh
#
# Battery status script, writen by Ronald Chu for GeekTool usage. Free to
# use as you please.
#
# Prints the current charge, time remaining on battery power or the AC
# power status

# Create an array (Capacity, Voltage, Flags, Current, Amperage, Cycle Count)
# in 10.6 the order has changed to (Amperage, Flags, Capacity, Current, Voltage, Cycle Count) so we need to re-order
if [ -n '`sw_vers |grep ProductVersion:.10.6`' ]; then
  status=(`ioreg -w0 -l|grep LegacyBatteryInfo|sed -e 's/[^1234567890]/ /g'|awk '{print $3&quot; &quot;$5&quot; &quot;$2&quot; &quot;$4&quot; &quot;$1&quot; &quot;$6}'`)
else
  status=(`ioreg -w0 -l|grep LegacyBatteryInfo|sed -e 's/[^1234567890]/ /g'`)# Fix Amperage (convert large number to negative one)
  status[4]=$(expr ${status[4]} + 0)
fi

# if charger connected
if [ $((${status[2]} &amp; 1)) == 1 ]; then
  #if battery is charging
  if [ $((${status[2]} &amp; 2)) == 2 ]; then

    # Calculate minutes until  fullycharged
    if [ ${status[4]} -lt 0 ]; then
      mins=''
    else
      mins=`echo &quot;(${status[0]}-${status[3]})*60/${status[4]}&quot;|bc`
      if [ $mins -gt 59 ]; then
        mins=`printf &quot;, %d:%02d until full&quot; $(( mins / 60 )) $(( mins % 60 ))`
      else
        mins=`printf &quot;, 0:%02d until full&quot; $mins`
      fi
    fi
    echo `echo &quot;${status[3]}*100/${status[0]}&quot;|bc`&quot;% (charging$mins)&quot;
  else
    perc=`echo &quot;${status[3]}*100/${status[0]}&quot;|bc`
    if [ $prec -lt 100 ]; then
      echo &quot;$perc% (not charging)&quot;
    else
      echo &quot;100% (charged)&quot;
    fi
  fi

# if charger not connected
else
  # Calculate minutes until empty
  if [ ${status[4]} -ge 0 ]; then
    mins=''
  else
    mins=`echo &quot;- ${status[3]}*60/${status[4]}&quot;|bc`
    if [ $mins -gt 59 ]; then
      mins=`printf &quot;(%d:%02d remaining)&quot; $(( mins / 60 )) $(( mins % 60 ))`
    else
      mins=`printf (0:%02d remaining)&quot; $mins`
    fi
  fi

  echo `echo &quot;${status[3]}*100/${status[0]}&quot;|bc`&quot;%$mins&quot;
fi
</pre>
<h2>Hard disk</h2>
<p>I only care about the free space on my main hard disk and not at all in what other drives, shares, disk images and so forth are mounted. So I filter and reformat output of <code>df</code> to show just that.</p>
<pre class="brush: bash;">df -h | grep 'disk0s2' | awk '{print $4&quot; free (&quot;$5&quot; of &quot;$2&quot; used)&quot;}'</pre>
<h2>Memory</h2>
<p>Calling <code>top</code> and extracting the memory usage is pretty simple. I am planning to extract much more information from top (like the load en processes using the most CPU time) later.</p>
<pre class="brush: bash;">top -l 1 | awk '/PhysMem/ {print $8 &quot; used, &quot; $10 &quot; free&quot;}'</pre>
<h2>Network</h2>
<p>I&#8217;ve written a bash script that takes the name of a network interface as a parameter and returns its status, IP address, the SSID if it is an airport connection and last but not least the amount of data sent and recieved. The comment in the code should explain everything.</p>
<pre class="brush: bash;">
#! /bin/sh
#
# Network status script, writen by Ronald Chu for GeekTool usage. Free to
# use as you please.
#
# Prints status, ip, trafic and (if aplicable) SSID name of the airport and
# ethernet connection. Network IO is stored with timestamp in milliseconds
# in a text file so with the difference in time and bytes the IO in bytes
# per second can be calculated.

workdir=&quot;/Users/ronaldchu/Applications/Scripts/GeekTool/&quot;

# parameter is a number of bytes * 100 (for float precision)
function formatBytes()
{
  if [ $1 -lt 102400 ]; then echo `echo &quot;scale=2; $1/100&quot;|bc` b; else
    if [ $1 -lt 104857600 ]; then echo `echo &quot;scale=2; $1/102400&quot;|bc` Kb; else
      echo `echo &quot;scale=2; $1/104857600&quot;|bc` Mb;
    fi
  fi
}

# The script takes the name of the interface as a parameter
if [ $# -lt 1 ]; then
  echo &quot;Parameter missing&quot;
  exit 1
fi

# Check if interface exists
ifconfig $1 &gt; /dev/null 2&gt;&amp;1
if [ $? -ne 0 ]; then
  echo &quot;Interface \&quot;$1\&quot; does not exist&quot;
  exit 2
fi

#Extract ip adress
ip=`ifconfig $1 | grep &quot;inet &quot; | grep -v 127.0.0.1 | awk '{print $2}'`

if [ $ip ]; then

  # Make IO info string &quot;
  IO_now=&quot;`${workdir}milliseconds` `netstat -ib | grep -e &quot;$1&quot; -m 1 | awk '{print $7&quot; &quot;$10}'`&quot;

  # If there is an old IO info file
  if [ -f &quot;${workdir}NetworkStatus_$1_IO.txt&quot; ]; then
    IO_old=`cat ${workdir}NetworkStatus_${1}_IO.txt`

  # else create one and sleep for a second
  else
    echo $IO_now &gt; ${workdir}NetworkStatus_${1}_IO.txt
    IO_old=$IO_now
    sleep 1
    IO_now=&quot;`${workdir}milliseconds` `netstat -ib | grep -e &quot;$1&quot; -m 1 | awk '{print $7&quot; &quot;$10}'`&quot;
  fi

  #calculate IO trafic in Kb/s
  IO_in=`echo $IO_old $IO_now|awk '{print &quot;scale=0; (100*(&quot;$5&quot;-&quot;$2&quot;))/(&quot;$4&quot;-&quot;$1&quot;)&quot;}'|bc`
  IO_out=`echo $IO_old $IO_now|awk '{print &quot;scale=0; (100*(&quot;$6&quot;-&quot;$3&quot;))/(&quot;$4&quot;-&quot;$1&quot;)&quot;}'|bc`

  # Write current IO info
  echo $IO_now &gt; ${workdir}NetworkStatus_${1}_IO.txt

  # Echo network status (with SSID iff the network interface is the airport)
  if [ $1 == &quot;en1&quot; ]; then
    SSID=`/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I|grep '[^B]SSID' |sed -e 's/^[^:]*: //'`
    echo &quot;$ip ($SSID) `formatBytes $IO_in`/s down `formatBytes $IO_out`/s up&quot;
  else
    echo &quot;$ip `formatBytes $IO_in`/s down `formatBytes $IO_out`/s up&quot;
  fi

else
  echo &quot;Disconnected&quot;
fi
</pre>
<p>To obtain the timestamp for the network data readings using <code>date</code> isn&#8217;t accurate enough, so I use the following little C program to get a more accurate timestamp.</p>
<pre class="brush: cpp;">
#include &lt;stdlib.h&gt;
#include &lt;sys/time.h&gt;

main()
{
  struct timeval tv;
  gettimeofday(&amp;tv, NULL);
  printf(&quot;%d.%d\n&quot;, tv.tv_sec, tv.tv_usec);
}
</pre>
<h2>Twitter</h2>
<p>What else can I do? Well, whenever you want add something fancy you can always do something with Twitter! It makes you modern and Web 2.0, and stuff like that. Also it was extremely easy to add the latest tweets from my friends to my desktop with only one single command.</p>
<pre class="brush: bash;">
curl -u username:password http://twitter.com/statuses/friends_timeline.rss?count=20| \
grep title|\
tail -n 20 |\
sed -e 's/.*\(.*\)&lt;\/title&gt;/\1/'
</pre>
<h2>iTunes</h2>
<p>For information on the track currently playing in iTunes I&#8217;ve combined several scripts and ideas from others and myself to create an applescript which extracts the album art and returns the artist, title and album of the current song. Add another entry in GeekTool to show the image, which is a PNG file in a fixed location. In my case, this is located at <code>file:///Users/ronaldchu/artwork.png</code></p>
<pre class="brush: applescript;">
# iTunesCurrentSong.scpt
#
# An applescript which returns the title, artist, album and player
# status of iTunes and writes the current album art (or blank if
# iTunes not running, or a default image if no art available) to a
# png file
#
# Network status script, writen by Ronald Chu for GeekTool usage. Free to
# use as you please.

# folders specs
set artworkFolder to ((path to home folder) as text) &amp; &quot;Applications:Scripts:GeekTool:&quot;
set artworkFile to artworkFolder &amp; &quot;artwork.png&quot;
set artworkiTunes to artworkFolder &amp; &quot;artwork.pict&quot;
set artworkBlank to artworkFolder &amp; &quot;blank.png&quot;
set artworkDefault to artworkFolder &amp; &quot;default.png&quot;
set unixArtworkFile to the quoted form of POSIX path of artworkFile
set unixArtworkiTunes to the quoted form of POSIX path of artworkiTunes
set unixArtworkBlank to the quoted form of POSIX path of artworkBlank
set unixArtworkDefault to the quoted form of POSIX path of artworkDefault

# Check if iTunes is running
tell application &quot;System Events&quot;
	set powerCheck to ((application processes whose (name is equal to &quot;iTunes&quot;)) count)
	if powerCheck = 0 then
		# If there's no iTunes running use the Blank Arwork
		do shell script &quot;cp &quot; &amp; unixArtworkBlank &amp; &quot; &quot; &amp; unixArtworkFile
		return &quot;&quot;
	end if
end tell

tell application &quot;iTunes&quot;

	# Get current track name and status
	try
		set playerstate to (get player state)
	end try
	if playerstate = paused then
		set trackPaused to &quot;
&quot;
	else
		set trackPaused to &quot;&quot;
	end if
	if playerstate = stopped then
		# If there's iTunes use the default Arwork.
		do shell script &quot;cp &quot; &amp; unixArtworkDefault &amp; &quot; &quot; &amp; unixArtworkFile
		return &quot;

&quot;
	end if

	set trackID to the current track
	set trackName to the name of trackID
	set artistName to the artist of trackID
	set albumName to the album of trackID

	(* Is there any Artwork? *)
	if (count of artwork of trackID) ≥ 1 then
		set artworkData to data of artwork 1 of trackID
		set fileRef to (open for access artworkiTunes with write permission)
		try
			set eof fileRef to 512
			write artworkData to fileRef starting at 513
			close access fileRef
		on error errorMsg
			try
				close access fileRef
			end try
			error errorMsg
		end try

		tell application &quot;Image Events&quot;
			launch
			set theimg to open artworkiTunes
			scale theimg to size 100
			save theimg as PNG in artworkFile with replacing
			close
		end tell

	else
		(* If there's no Artwork use the default artwork. *)
		do shell script &quot;cp &quot; &amp; unixArtworkDefault &amp; &quot; &quot; &amp; unixArtworkFile
	end if

	return trackPaused &amp; &quot;
&quot; &amp; artistName &amp; &quot;
&quot; &amp; trackName &amp; &quot;
&quot; &amp; albumName
end tell
</pre>
<p>For some reason the code contains html code for special character like &lt; and &amp;. I&#8217;ll look into this later, for now you just have to change that when copying the code. Also I&#8217;m having lot&#8217;s of difficulty with getting syntax highlighting working right, damnit&#8230;</p>
<p><em><strong>Update 07/06/09:</strong> Changed the battery script so it will show &#8220;100% (charged)&#8221; instead of &#8220;100% (not charging)&#8221;.</em></p>
<p><em><strong>Update 23/06/09:</strong> Please leave a comment if you like my scripts, or if you don&#8217;t. I&#8217;d love to get some feedback and know how many of the visitors google analytics reports to me are actualy using the scripts</em></p>
<p><em><strong>Update 24/08/09:</strong> Updated the battery script, changed &gt; to -gt to actualy do a greater-than comparisation instead of dumping into a file called 59.</em></p>
<p><em><strong>Update 27/11/09: </strong>Added a version check to the BatteryStatus script because the order of the battery info has changed since 10.6<br />
</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rchu.nl/2009/06/geektool/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>SVN UP</title>
		<link>http://www.rchu.nl/2009/01/svn-up/</link>
		<comments>http://www.rchu.nl/2009/01/svn-up/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 15:23:15 +0000</pubDate>
		<dc:creator>ronald</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[scripting]]></category>

		<guid isPermaLink="false">http://www.rchu.nl/2009/01/svn-up/</guid>
		<description><![CDATA[The svn commandline tool is great, but when I don&#8217;t receive a e-mail notifying me of a new commit I hardly ever read the log messages. That&#8217;s why I added an alias to my profile called svnup which does an update and then prints the log from the revision before the update to now.

SVN_CURR_REV=`svn info&#124;grep [...]]]></description>
			<content:encoded><![CDATA[<p>The svn commandline tool is great, but when I don&#8217;t receive a e-mail notifying me of a new commit I hardly ever read the log messages. That&#8217;s why I added an alias to my profile called <code>svnup</code> which does an update and then prints the log from the revision before the update to now.</p>
<pre class="brush: bash;">
SVN_CURR_REV=`svn info|grep 'Last Changed Rev'|awk '{ print $4 }'`; \
svn up; \
svn log -r $SVN_CURR_REV:HEAD
</pre>
<p>Now I just have to remember tot type <code>svnup</code> instead of <code>svn up</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rchu.nl/2009/01/svn-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
