<?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>Altentee » Performance &#38; Test Automation Experts &#187; code</title>
	<atom:link href="http://altentee.com/blogs/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://altentee.com</link>
	<description>Performance and Test Automation Experts</description>
	<lastBuildDate>Fri, 04 Nov 2011 03:17:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Polling a Resource with Fibonacci Determined Sleep Intervals</title>
		<link>http://altentee.com/blogs/2009/polling-a-resource-with-fibonacci-determined-sleep-intervals/</link>
		<comments>http://altentee.com/blogs/2009/polling-a-resource-with-fibonacci-determined-sleep-intervals/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 00:13:04 +0000</pubDate>
		<dc:creator>Tim Koopmans</dc:creator>
				<category><![CDATA[Altentee]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://90kts.com/blog/2009/polling-a-resource-with-fibonacci-determined-sleep-intervals/</guid>
		<description><![CDATA[In mathematics, Fibonacci numbers are the following sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, &#8230; By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. This naturally occurring sequence is useful for determining the amount of time to sleep [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>In mathematics, Fibonacci numbers are the following sequence of numbers:<br />
0, 1, 1, 2, 3, 5, 8, 13, &#8230;</p>
<p>By definition, the first two <a href="http://en.wikipedia.org/wiki/Fibonacci_number"><strong>Fibonacci</strong></a> numbers are 0 and 1, and each remaining number is the sum of the previous two. This naturally occurring sequence is useful for determining the amount of time to sleep whenever you are polling a resource.</p></blockquote>
<p>I&#8217;m often required to poll a database resource in some sort of daemon. For example, check a table for some asynchronous tasks to complete. If you have a lot of threads polling this resource at quick intervals, the impact on the resource can be excessive/high. Rather than poll at a set interval, I use a Fibonacci sequence to determine what the next sleep interval will be. Following are code examples of this polling technique hosted on GitHub in my most commonly used programming languages&#8230;<br />
<span id="more-253"></span><br />
<a href="http://github.com/90kts/poll_resource/blob/master/poll_fibonacci.rb"><strong>Ruby</strong></a><br />
<a href="http://github.com/90kts/poll_resource/blob/master/poll_fibonacci.pl"><strong>Perl</strong></a><br />
<a href="http://github.com/90kts/poll_resource/blob/master/poll_fibonacci.php"><strong>PHP</strong></a></p>
<p>Essentially what each script does is the following &#8230;</p>
<p>Initialise a thread with a sleep interval of 5 seconds (or F5 in reference to the Fibonacci sequence number)</p>
<p>The thread will then:<br />
  1. Check if there is work to do by polling the resource<br />
  2. Complete any work and indicate if work has been done<br />
  3. If work has been done then next sleep interval will be 3 seconds (or F5-1)<br />
  4. If work has not been done then next sleep interval will be 8 seconds (or F5+1)<br />
  5. Sleep for the desired interval and loop</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://altentee.com/blogs/2009/polling-a-resource-with-fibonacci-determined-sleep-intervals/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>[Bump] MyThree Bandwidth Usage Widget</title>
		<link>http://altentee.com/blogs/2008/mythree-bandwidth-usage-widget/</link>
		<comments>http://altentee.com/blogs/2008/mythree-bandwidth-usage-widget/#comments</comments>
		<pubDate>Thu, 07 Feb 2008 10:00:50 +0000</pubDate>
		<dc:creator>Tim Koopmans</dc:creator>
				<category><![CDATA[Altentee]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://90kts.com/blog/2008/mythree-bandwidth-usage-widget/</guid>
		<description><![CDATA[Download it &#8216;ere&#8230; I currently have a mobile broadband account (HSDPA) provided by three.com.au, and after a hexy surcharge from the previous month when exceeding my limit, thought it would be prudent to build a dashboard widget that tracks my monthly bandwidth usage. Building on a previous post that automates calls to a https website, [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://90kts.com/blog/wp-content/uploads/2008/02/threeusagemeterwdgtv2.zip' title='Download MyThree Bandwidth Usage Widget Download'>Download it &#8216;ere&#8230;</a></p>
<p>I currently have a mobile broadband account (HSDPA) provided by three.com.au, and after a hexy surcharge from the previous month when exceeding my limit, thought it would be prudent to build a dashboard widget that tracks my monthly bandwidth usage.</p>
<p><del datetime="2008-02-08T02:57:23+00:00">Building on a previous <a href="http://90kts.com/blog/2007/automating-your-scripts-with-wwwmechanize/">post</a> that automates calls to a https website, I followed a nifty tutorial <a href="http://ruk.ca/article/3145">here</a> to turn that perl script into a Mac OSX dashboard widget.</del> I have since revised my original code and opted for a <strong>Ruby</strong> version of the script, as I found Ruby is easier to setup for a noob as opposed to Perl and its dependencies &#8230;<br />
<span id="more-291"></span></p>
<p>Since Mac OSX already comes with a suitable version of Ruby, the only pre-installation requirement for this widget is to install the relevant gem that I use to automate http. So from a console type and accept the defaults.<br />
<code>sudo gem install -y mechanize</code></p>
<p><a href='http://90kts.com/blog/wp-content/uploads/2007/09/picture-1.png' title='picture-1.png'><img src='http://90kts.com/blog/wp-content/uploads/2007/09/picture-1.png' alt='picture-1.png' /></a></p>
<p><del datetime="2008-02-08T02:56:40+00:00">Not anticipating a huge readership that wants this magic explained, I will just post the source code instead for your own use.</del> You can download the widget <a href='http://90kts.com/blog/wp-content/uploads/2008/02/threeusagemeterwdgtv2.zip' title='ThreeUsageMeter Widget V2'>here</a>. After you decompress the archive, you can look at the source code by right mouse clicking on the widget and show package contents.</p>
<p>The main difference between my code and the example code is that I&#8217;m not making a system call to the curl binary as per the following:<br />
<code>widget.system("/usr/bin/curl<br />
    http://www.example.com/dashboard.php?return=sales",<br />
    null).outputString;</code></p>
<p>Rather, I am making a call to the <del datetime="2008-02-08T02:57:23+00:00">Perl</del> Ruby binary, which calls the mech script I had created in the previous post as per the following:<br />
<code>/usr/bin/ruby ~/Library/Widgets/ThreeUsageMeter.wdgt/scripts/MyThreeV2.rb ' + mobile + ' ' + password + ' ' + pin;</code></p>
<p>I have also added some fields that retain their values (for configuration) for your mobile number, password and pin.</p>
<p>If you are keen to just look/run the Ruby code on its own without the dashboard widget feel free to copy it from below.</p>
<p>Let me know if you have any difficulties installing the widget &#8230;</p>
<p><code>#!/usr/bin/env ruby<br />
#sigh, my very first Ruby script ... Will I ditch Perl ? 8^)<br />
#sudo gem install -y mechanize</p>
<p>require 'rubygems'<br />
require 'mechanize'</p>
<p>login     = ARGV[0]<br />
password  = ARGV[1]<br />
pin       = ARGV[2]</p>
<p>url = "https://www.my.three.com.au/My3/jfn"</p>
<p># init agent<br />
agent = WWW::Mechanize.new<br />
agent.user_agent_alias = 'Windows IE 6'</p>
<p># get first page<br />
page = agent.get(url)</p>
<p># login page<br />
form = page.forms.find {|f| f.name == 'login'}<br />
form.fields.find {|f| f.name == 'login'}.value = login<br />
form.fields.find {|f| f.name == 'password'}.value = password<br />
page = agent.submit(form, form.buttons.first)</p>
<p># pin page<br />
form = page.forms.find {|f| f.name == 'myForm'}<br />
form.fields.find {|f| f.name == 'pin'}.value = pin<br />
page = agent.submit(form, form.buttons.first)</p>
<p># get rc1<br />
if page.body.match /Mobiles on this account.+?src='(.+?)'/m<br />
  url = $1<br />
  oid = url.match /;(.+)?mfunc/m<br />
  oid = oid[1]<br />
  url = url.gsub("&amp;","&#038;")<br />
  page = agent.get url<br />
end</p>
<p># get rc2<br />
if page.body.match /paddingText">.+?<a href='(.+?)'/m<br />
  url = $1.gsub("amp;&amp;",oid)<br />
  url = url.gsub("&amp;","&#038;")<br />
  page = agent.get url<br />
end</p>
<p># get rc3<br />
if page.body.match /iframe src='(.+?)'/m<br />
  url = $1.gsub("&amp;","&#038;")<br />
  page = agent.get url<br />
end</p>
<p># spend data<br />
if page.body.match /bill.+?TextRPHeadings">(.+?)<\/span>/m<br />
  spend = $1.gsub(/\n\t\s+/m,"")<br />
end</p>
<p># other data<br />
results = page.body.scan(/span class="paddingText">\s+(Mobile Broadband.+?)<\/tr>/m)</p>
<p>results.each { |e|<br />
  # size<br />
  if e.to_s.match /\(([\w\d]+)\)/m<br />
    size = $1<br />
  end</p>
<p>  # remain<br />
  if e.to_s.match /
<td>\s+([\d\.]+)\s+<\/td>/m<br />
    remain = $1<br />
  end</p>
<p>  # date<br />
  if e.to_s.match /rightPadding">(.+?)</m<br />
    date = $1.gsub(/\n\t\s+/m,"")<br />
  end</p>
<p>  print spend,"|",size,"|",remain,"|",date,"\n"<br />
}</code></p>
]]></content:encoded>
			<wfw:commentRss>http://altentee.com/blogs/2008/mythree-bandwidth-usage-widget/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>An exercise in correlation &#8211; playing MySpace music via iTunes</title>
		<link>http://altentee.com/blogs/2008/an-exercise-in-correlation-playing-myspace-music-via-itunes/</link>
		<comments>http://altentee.com/blogs/2008/an-exercise-in-correlation-playing-myspace-music-via-itunes/#comments</comments>
		<pubDate>Thu, 07 Feb 2008 09:00:02 +0000</pubDate>
		<dc:creator>Tim Koopmans</dc:creator>
				<category><![CDATA[Altentee]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://90kts.com/blog/2008/an-exercise-in-correlation-playing-myspace-music-via-itunes/</guid>
		<description><![CDATA[[UPDATE] Mr Gecko, has since implemented this logic and sorted out downloading woes (for u US folk) in a nifty little OSX app here &#8230; In between contracts, I have been practicing the art of correlation by scraping data from public web sites. The legality of this is perhaps a little unclear so I&#8217;ve aimed [...]]]></description>
			<content:encoded><![CDATA[<p><strong>[UPDATE]</strong> <a href="http://www.programmerslife.co.cc/2008/05/myspacer/">Mr Gecko</a>, has since implemented this logic and sorted out downloading woes (for u US folk) in a nifty little OSX app <a href="http://www.programmerslife.co.cc/2008/05/myspacer/">here</a> &#8230;</p>
<p>In between contracts, I have been practicing the art of correlation by scraping data from public web sites. The legality of this is perhaps a little <a href="http://en.wikipedia.org/wiki/Web_scraping#_note-0">unclear</a> so I&#8217;ve aimed not to infringe on copyrights by not storing the content, but just changing the way in which content is displayed from a live site. One such example was to open up MySpace songs via iTunes, rather than using the flash player MySpace provide. This required a fair analysis of web server to client traffic, in order to piece together the necessary conversation required to achieve all this via Perl &#8230;<br />
<img src='http://90kts.com/blog/wp-content/uploads/2008/02/itunes-myspace.jpg' alt='itunes-myspace' /><br />
<span id="more-110"></span></p>
<p>My tools of choice were Firefox with the LiveHTTP Headers plugin to see what&#8217;s happening between the browser and server, tcpdump to catch those harder to find pieces of information, sometimes critical in determining how to correlate necessary data, and Perl to faciliate the automation, namely using the WWW::Mechanize module.</p>
<p>So for an exercise in correlation, I chose to play content from MySpace. Basically what I wanted to do was figure out how to create my own standalone player in order to play MySpace music via iTunes &#8230;</p>
<p>I&#8217;ve come up with the following script, which takes into account the dynamic nature of MySpace content (as well as all the necessary tokens and so forth) in order to play back content &#8230; This has been crafted for a Mac OSX platform. You will need to install the necessary modules via cpan for your own installation in order for it to work.</p>
<p>An example of the script running is shown below:<br />
[WINDOWSMEDIA http://90kts.com/blog/wp-content/uploads/2008/01/MySpacer.avi 511 362 false true]</p>
<p><a href="http://90kts.com/blog/wp-content/uploads/2008/01/MySpacer.avi">Download video &#8230;</a></p>
<p><code><br />
#!/usr/bin/perl -w<br />
use WWW::Mechanize;<br />
use Getopt::Long;<br />
use Time::HiRes qw(gettimeofday tv_interval);<br />
use Mac::iTunes;</p>
<p>GetOptions(<br />
	"username:s"     =>\$opts{username},<br />
	"download:s"     =>\$opts{download},<br />
	"songname:s"     =>\$opts{songname},<br />
	"debug!"         =>\$opts{debug}<br />
);</p>
<p>{<br />
    # suppress all stderr warnings<br />
    local $SIG{__WARN__}=sub{};</p>
<p>    # make stdout hot<br />
    $| = 1;</p>
<p>    # get opts<br />
    my $url    	    = "http://www.myspace.com/".$opts{username}  ||<br />
    "http://www.myspace.com/djkraftykuts";<br />
    my $download    = $opts{download} || "/tmp";<br />
    my $songname    = $opts{songname};<br />
    my $debug       = $opts{debug};</p>
<p>    # init new mech<br />
    my $mech        = WWW::Mechanize->new(cookie_jar => {});<br />
    $mech->agent_alias( 'Linux Mozilla' );</p>
<p>    print "\nInitializing :\n--------------\n";<br />
    # get band id<br />
    $result = &#038;getParse($url);<br />
    $bandid = ($result =~ /DisplayFriendId":(.+?),/g) ? $1 : undef;<br />
    print "\t\tBand ID      :\t$bandid\n" if $bandid;</p>
<p>    # enum standalone player<br />
    $url    = "http://collect.myspace.com/music/popup.cfm".<br />
    "?num=0&#038;time=undefined&#038;fid=$bandid&#038;uid=1";<br />
    $result = &#038;getParse($url);<br />
    $url    = ($result =~ /EMBED src="(.+?)"/g) ? $1 : undef;<br />
    print "\t\tPlayer       :\tFound\n" if $url;</p>
<p>    # launch standalone player<br />
    $result = &#038;get($url);<br />
    print "\t\tPlayer       :\tLaunched\n" if($result->is_success);</p>
<p>    # cross domain<br />
    $url = "http://mediaservices.myspace.com/crossdomain.xml";<br />
    $result = &#038;get($url);<br />
    print "\t\tXDomain      :\tReceived\n" if($result->is_success);</p>
<p>    # css<br />
    $url = "http://collect.myspace.com/music/player.css";<br />
    $result = &#038;get($url);<br />
    print "\t\tCSS          :\tReceived\n" if($result->is_success);</p>
<p>    # xml<br />
    $url = "http://mediaservices.myspace.com/services/media/".<br />
    "musicplayerxml.ashx?b=$bandid";<br />
    $result = &#038;getParse($url);<br />
    print $result if $debug;<br />
    my $n=0;<br />
    $result =~ s/<song bsid/\n<song bsid/g;<br />
    while ($result =~ m/<song(.+?)\/>\n/g) {<br />
        $xml      = $1;<br />
        $bsid     = ($xml =~ /bsid="(.+?)"/g)     ? $1 : undef;<br />
        $title    = ($xml =~ /title="(.+?)"/g)    ? $1 : undef;<br />
        $songid   = ($xml =~ /songid="(.+?)"/g)   ? $1 : undef;<br />
        $plays    = ($xml =~ /plays="(.+?)"/g)    ? $1 : undef;<br />
        $songurl  = ($xml =~ /url="(.+?)"/g)      ? $1 : undef;<br />
        $durl     = ($xml =~ /durl="(.+?)"/g)     ? $1 : undef;<br />
        $token    = ($xml =~ /token="(.+?)"/g)    ? $1 : undef;<br />
        $i        = ($songurl =~ /i=(.+)/g)       ? $1 : undef;</p>
<p>        $songs{$n} = {<br />
            'bsid'      => $bsid,<br />
            'title'     => $title,<br />
            'songid'    => $songid,<br />
            'plays'     => $plays,<br />
            'songurl'   => $songurl,<br />
            'durl'      => $durl,<br />
            'token'     => $token,<br />
            'i'         => $i<br />
            };<br />
        $n++;<br />
    }<br />
    print "\t\tXML          :\tParsed\n";</p>
<p>    # connecting to content<br />
    print "Connecting  :\n--------------\n";<br />
    for(0..$n-1){<br />
        print "\t\tSong         :\t".$songs{$_}{'title'}."\n";<br />
        print "\t\tPlays        :\t".$songs{$_}{'plays'}."\n";<br />
        &#038;getSong($_);<br />
    }</p>
<p>    undef $mech;</p>
<p>    # subs<br />
    sub getSong {<br />
        # start script timer<br />
        &#038;startTimer();</p>
<p>        # mediahitcounter<br />
        $url = "http://mediaservices.myspace.com/services/media/".<br />
        "mediahitcounter.ashx?i=".$songs{$_[0]}{'i'};<br />
        $result = &#038;get($url);<br />
        print "\t\tCounters     :\tUpdated\n" if($result->is_success);</p>
<p>        # token<br />
        $url = "http://mediaservices.myspace.com/services/media/token.ashx".<br />
        "?b=$bandid&#038;s=".$songs{$_[0]}{'songid'}."&#038;f=0";<br />
        $result = &#038;get($url);<br />
        print "\t\tTokens       :\tReceived\n" if($result->is_success);</p>
<p>        # beacon<br />
        $c = int(rand(99999999));<br />
        $url = "http://lads.myspace.com/music/start_beacon.txt?c=$c";<br />
        $result = &#038;get($url);<br />
        print "\t\tBeacon       :\tUpdated\n" if($result->is_success);</p>
<p>        # play song<br />
        if($download) {<br />
            print "\t\tPlaying song :\t";<br />
            $url = $songs{$_[0]}{'durl'}."?bandid=$bandid".<br />
            "&#038;songid=".$songs{$_[0]}{'songid'}.<br />
            "&#038;token=".$songs{$_[0]}{'token'};</p>
<p>            print $url if $debug;<br />
            my $controller = Mac::iTunes->controller;<br />
            $controller->open_url( $url );</p>
<p>            # use keyboard to control playback<br />
            print "Press 's' to skip song or 'q' to quit ";<br />
            system "stty cbreak < /dev/tty > /dev/tty 2>&#038;1";<br />
            while (($key=getc) ) {<br />
              last if $key eq "s";<br />
              $controller->quit if $key eq "q";<br />
              print "\r\t\tExiting    :\t Complete".<br />
              "                        \n\n" if $key eq "q";<br />
              exit if $key eq "q";<br />
            };</p>
<p>            # optional download<br />
            #my $result  = $mech->get( $url, ':content_file' =><br />
            #"$download/".$songs{$_[0]}{'title'}.".mp3" );<br />
            #die "\tERROR!\n\tGET failed on $url \n"<br />
            #unless $result->is_success;<br />
        }</p>
<p>        # end script timer<br />
        &#038;endTimer();<br />
        print "\r\t\tPlaying song :\t[$elapsed secs] elapsed time".<br />
        "                \n\n" if($result->is_success);</p>
<p>    }</p>
<p>    sub get {<br />
        my $url     = $_[0];<br />
        my $result  = $mech->get( $url );<br />
    	warn "\tERROR!\n\tGET failed on $url \n ".$result->content.<br />
    	" \n\n" unless $result->is_success;<br />
        return $result;<br />
    }</p>
<p>    sub getParse {<br />
        my $url     = $_[0];<br />
        my $result  = $mech->get( $url );<br />
    	die "\tERROR!\n\tGET failed on $url \n" unless $result->is_success;<br />
        $result     = $mech->content;<br />
        $result     =~ s/\n//g;<br />
        return $result;<br />
    }</p>
<p>    sub startTimer {<br />
        $timer = [gettimeofday];<br />
    }</p>
<p>    sub endTimer {<br />
        $elapsed = tv_interval ($timer);<br />
        $elapsed = sprintf("%.4s", $elapsed);<br />
    }</p>
<p>};</code></p>
]]></content:encoded>
			<wfw:commentRss>http://altentee.com/blogs/2008/an-exercise-in-correlation-playing-myspace-music-via-itunes/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

