<?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>bitshaq</title>
	<atom:link href="http://bitshaq.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://bitshaq.com</link>
	<description>I am (the other) Shaq and these are my two bits ;)</description>
	<lastBuildDate>Thu, 15 Dec 2011 21:31:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Book Review: Final Jeopardy: Man vs. Machine and the Quest to Know Everything</title>
		<link>http://bitshaq.com/2011/12/15/book-review-final-jeopardy-man-vs-machine-and-the-quest-to-know-everything/</link>
		<comments>http://bitshaq.com/2011/12/15/book-review-final-jeopardy-man-vs-machine-and-the-quest-to-know-everything/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 21:31:13 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[books]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=791</guid>
		<description><![CDATA[I like computers and I also like Jeopardy. So I knew I was going to enjoy this book. But there was a third factor that made it a double delight. Who knew that behind the scenes horse trading was the stuff of compelling narratives? Not me. The protagonist in this story is David Ferrucci. As [...]]]></description>
			<content:encoded><![CDATA[
<p>I like computers and I also like <em>Jeopardy</em>. So I knew I was going to enjoy this book. But there was a third factor that made it a double delight. Who knew that behind the scenes horse trading was the stuff of compelling narratives? Not me. The protagonist in this story is David Ferrucci. As project-manager-cum-pointdexter-in-chief, he wrangled up the best minds in industry to facebookpalm his detractors who said that either the project was too ambitious to succeed or embarrassingly easy to be worth pursuing.</p>
<p>Disproving the &#8216;embarrassingly easy&#8217; tribe was, well, embarrassingly easy. It needed a lone IBM engineer, working three months to build a Jeopardy playing computer that would fail to reach the champions quadrant. In this quadrant, champions win the buzzer sixty percent of the time. Disproving the &#8216;too ambitious&#8217; tribe would need several years of work that culminated in two nationally televised games that are subject of this book. The author also delved into the technical wizardry employed by IBM. Here is the coveted &#8220;intellectual property&#8221; for aspiring wizards:</p>
<ul>
<li>Data sources. Lots of them.</li>
<li>Data mining algorithms. Highly optimized.</li>
<li>Neural Network to apply confidence measures to the data mining algorithms.</li>
<li>CPU cores. Preferably at least two thousand.</li>
<li>1 mechanical finger for buzzer. This is very important!</li>
<li>Cutesy branding. For pandering to the <del datetime="2011-12-15T20:53:56+00:00">eyeballs</del> <del datetime="2011-12-15T20:53:56+00:00">masses</del> viewers at home.</li>
<li>Non-threatening name. Note: Avoid science fiction references.</li>
</ul>
<p>After you&#8217;ve got all these pieces stitched together, you have a computer with the intelligence of a two year old. Optimize, optimize, and optimize some more. Now you&#8217;ve graduated to a three year old, which as any parent will tell you, is worse. Keep optimizing and eventually the machine will reach the champions quadrant.</p>
<p>So now that IBM has proven that it can build a formidable trivia game playing computer, what&#8217;s next? The author thinks it may be re-purposed as an expert system for use by legal, medical or business &#8220;professionals&#8221;. Apparently, computers can be used for other stuff besides web browsing, games, and twittering. </p>
<p>Whatevs.</p>
<p>Checkout the book <a href="http://www.amazon.com/gp/product/0547483163/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;tag=bitshaq-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0547483163">here.</a><img style="border: none !important; margin: 0px !important;" src="http://www.assoc-amazon.com/e/ir?t=bitshaq-20&amp;l=as2&amp;o=1&amp;a=0547483163" border="0" alt="" width="1" height="1" /> Caution: requires reading and may prove to be useful and entertaining.</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/12/15/book-review-final-jeopardy-man-vs-machine-and-the-quest-to-know-everything/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Timing Is Everything</title>
		<link>http://bitshaq.com/2011/12/12/timing-is-everything/</link>
		<comments>http://bitshaq.com/2011/12/12/timing-is-everything/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 04:42:02 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[business]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=781</guid>
		<description><![CDATA[Ultimately, the bets Corzine placed wound up better than the firm itself. The European debt trades were profitable, though too late for MF Global. Before Congress on Thursday, Mr. Corzine continued to emphasize how well his trades held up. “As of today, none of the foreign debt securities that MF Global used,” he said, “has [...]]]></description>
			<content:encoded><![CDATA[
<blockquote><p>Ultimately, the bets Corzine placed wound up better than the firm itself. The European debt trades were profitable, though too late for MF Global.</p>
<p>Before Congress on Thursday, Mr. Corzine continued to emphasize how well his trades held up. “As of today, none of the foreign debt securities that MF Global used,” he said, “has defaulted or been restructured.”</p>
<p>“There actually were no losses.”
</p></blockquote>
<p>Source: <a href="http://dealbook.nytimes.com/2011/12/11/a-romance-with-risk-that-brought-on-a-panic/">NYTimes.com</a></p>
<p>The slot machine rang the jackpot after he was done playing it.</p>
<p>Speaking of gambling&#8230;.</p>
<blockquote><p>Chris Fargis thought his big job interview was over. But when the partners at Wall Street upstart Toro Trading finished with their questions, they broke out a deck of cards and a green-felt card table. Mind playing a few hands of poker?</p></blockquote>
<p>Source: <a href="http://articles.latimes.com/2010/may/16/business/la-fi-poker-traders-20100516">LA Times</a></p>
<p>I wonder if they have $5 buffets specials on Wall Street to entice the <del datetime="2011-12-12T04:34:41+00:00">gamblers</del> traders.</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/12/12/timing-is-everything/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Future of USPS</title>
		<link>http://bitshaq.com/2011/12/08/the-future-of-usps/</link>
		<comments>http://bitshaq.com/2011/12/08/the-future-of-usps/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 04:27:51 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[business]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=770</guid>
		<description><![CDATA[The USPS can&#8217;t be faulted for providing a top-notch in-store experience and extremely reliable delivery service. In fact, their delivery service is the yardstick by which all other delivery services should be measured. Over the decades, they have made it possible for people to purchase goods from a Sears Roebuck catalog, rent movies that arrived [...]]]></description>
			<content:encoded><![CDATA[
<p>The USPS can&#8217;t be faulted for providing a top-notch in-store experience and extremely reliable delivery service. In fact, their delivery service is the yardstick by which all other delivery services should be measured. Over the decades, they have made it possible for people to purchase goods from a Sears Roebuck catalog, rent movies that arrived in the signature red Netflix envelope and even mail in their winning lottery tickets. If it has not been profitable it&#8217;s because as a GSE it has little incentive or motivation to act as a for-profit business.</p>
<p>Its decision to chop over thirty thousand jobs is laced with irony because for the past decade, hundreds, if not thousands of high-priced consultants have have been milking the agency with the promise of helping it reduce its operating costs. Leave it to the suits to come up with the most obvious, uninnovative, non-solutions. Instead, what the USPS needs is a visionary leader, not a career civil servant, to take charge and lead a business process turn around.
</p>
<p>Currently, the biggest revenue generator for the USPS is its <del>junk</del> bulk mail service. Were it not for Super Saver coupon books and other marketing trash, most US residences could go days or even weeks without receiving a letter. If the USPS were to eliminate last-mile delivery for all but the most important mail and have individuals collect their mail from central post office boxes, it could result in a huge saving in fuel costs. By eliminating bulk mail, it could help save the trees and greatly improve the customer experience. Sure, it would lose the easy money but that&#8217;s not so bad if it finds alternative revenue sources. Revenue sources that don&#8217;t rely on bombarding their customers with unsolicited advertisements. For example:</p>
<ul>
<li>On-site business centers ala Kinko&#8217;s.</li>
<li>Mail digitization service (i.e. scan and e-mail correspondence to the recipients).</li>
<li>Door-step delivery as a premium service.</li>
<li>Ancillary or third-party on-site services, eg: electronic recycling deposits.</li>
<li>Electronic Fund Transfers, ala Moneygram or Western Union.</li>
<li>Co-located retail vendors, eg: Mobile phone vendors, H&#038;R Block, etc</li>
<li>Fully automated self-service machines (including mailing supply vending).</li>
<li>Drop-ship warehousing.</li>
<li>&#8230;and many more&#8230;</li>
</ul>
<p>I think the USPS does a great job. It just needs new revenue models to inject a new lease of life into itself. Its massive workforce and prime real estate holdings should be viewed as assets with huge monitzation potential. This could be the time for a historic new start for the agency.</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/12/08/the-future-of-usps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Hookbox @ NoVa Python Meetup</title>
		<link>http://bitshaq.com/2011/11/17/hookbox-nova-python-meetup/</link>
		<comments>http://bitshaq.com/2011/11/17/hookbox-nova-python-meetup/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 03:16:09 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=759</guid>
		<description><![CDATA[I made a few friends at the NoVa Python Meetup and incidentally gave an introduction to Hookbox. Here are the slides: Hookbox (PPT)]]></description>
			<content:encoded><![CDATA[
<p>I made a few friends at the NoVa Python Meetup and incidentally gave an introduction to Hookbox. Here are the slides:</p>
<p><a href='http://www.slideshare.net/slideshow/embed_code/9992124' >Hookbox (PPT)</a></p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/11/17/hookbox-nova-python-meetup/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hyperbolic Discounting Bias</title>
		<link>http://bitshaq.com/2011/11/08/hyperbolic-discounting-bias/</link>
		<comments>http://bitshaq.com/2011/11/08/hyperbolic-discounting-bias/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 17:33:36 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[business]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=750</guid>
		<description><![CDATA[From the WSJ: For some pension recipients, the deals seem like the way out of a financial crisis. Joseph Serina, a metal-fabrication worker who spent 21 years in the Navy, received $57,450 three years ago from a group of investors in return for promising them $125,280 in pension payments over eight years. [snip] The biggest [...]]]></description>
			<content:encoded><![CDATA[
<p>From the <a href="http://online.wsj.com/article/SB10001424052970203733504577022001207017044.html?mod=rss_whats_news_us">WSJ</a>:</p>
<blockquote><p>
For some pension recipients, the deals seem like the way out of a financial crisis. Joseph Serina, a metal-fabrication worker who spent 21 years in the Navy, received $57,450 three years ago from a group of investors in return for promising them $125,280 in pension payments over eight years.</p>
<p>[snip]</p>
<p>The biggest risk for investors is that pension recipients renege on their promises to turn over monthly checks to the investor.
</p></blockquote>
<p>If more people knew how to do basic math and understand interest calculations up front, would fewer of them seek pay day loans??</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/11/08/hyperbolic-discounting-bias/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Popularity of MapReduce</title>
		<link>http://bitshaq.com/2011/11/01/popularity-of-mapreduce/</link>
		<comments>http://bitshaq.com/2011/11/01/popularity-of-mapreduce/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 20:39:09 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[business]]></category>
		<category><![CDATA[hadoop]]></category>
		<category><![CDATA[mapreduce]]></category>
		<category><![CDATA[netezza]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=740</guid>
		<description><![CDATA[Though enterprise users with heavy demand and big budgets might be willing to pay for a commercial system and all the tools, support, and service agreements those systems provide, users with more modest budgets or requirements find open source systems more attractive. &#8211; Stonebraker et al, MapReduce and Parallel DBMSs: Friends or Foes? Communications of [...]]]></description>
			<content:encoded><![CDATA[
<blockquote><p>Though enterprise users with heavy demand and big budgets might be willing to pay for a commercial system and all the tools, support, and service agreements those systems provide, users with more modest budgets or requirements find open source systems more attractive.</p></blockquote>
<p>&#8211; Stonebraker et al, MapReduce and Parallel DBMSs: Friends or Foes? <a href="http://cacm.acm.org/magazines/2010/1/55743-mapreduce-and-parallel-dbmss-friends-or-foes/fulltext">Communications of the ACM Vol. 53 No. 1, Pages 64-71 10.1145/1629175.1629197</a></p>
<p>In other words:<br />
<strong><br />
Open source + easy learning curve + good enough > closed source + sophisticated + performant.<br />
</strong></p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/11/01/popularity-of-mapreduce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rotating Arrays with Python</title>
		<link>http://bitshaq.com/2011/10/31/rotating-arrays-with-python/</link>
		<comments>http://bitshaq.com/2011/10/31/rotating-arrays-with-python/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 15:26:37 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[k]]></category>
		<category><![CDATA[matlab]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[octave]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[r]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=685</guid>
		<description><![CDATA[Consider the following snippet: 2!!7!4 Yes, that&#8217;s a valid expression from the proprietary K programming language [1]. From Wikipedia: Reading from right to left the first ! is modulo division that is performed on 7 and 4 resulting in 3. The next ! is enumeration and lists the integers less than 3, resulting in the [...]]]></description>
			<content:encoded><![CDATA[
<p>Consider the following snippet:</p>
<pre name='code' class='python'>
2!!7!4
</pre>
<p>Yes, that&#8217;s a valid expression from the proprietary K programming language <a class="fn-ref-mark" href="#footnote-1" id="refmark-1"><sup>[1]</sup></a>.</p>
<p>From Wikipedia:</p>
<blockquote><p>
Reading from right to left the first ! is modulo division that is performed on 7 and 4 resulting in 3. The next ! is enumeration and lists the integers less than 3, resulting in the list 0 1 2. The final ! is rotation where the list on the right is rotated two times to the left producing the final result of 2 0 1.
</p></blockquote>
<p>Depending on your application, there are at least three ways this can be done in Python:</p>
<pre name='code' class='python'>
# Using the collections module
from collections import deque
d = deque(range(7%4))
d.rotate(-2) # this is an in-place rotation

# Using the numpy module
from numpy import roll
roll(range(7%4), -2) # this returns a numpy.ndarray

# Using list slicing and concatenation
r = range(7%4)
r= r[2:] + r[:2]
</pre>
<p>So which is faster? Rolling, rotating, or slicing?</p>
<pre name='code' class='python'>
def method_rotate (x, y=500):
    x.rotate(y)

def method_roll (x, y=500):
    roll(x, y)

def method_slice (x, y=500):
    r = x[y:] + x[:y]

x = range(1e7)
xa = array(x)
xd = deque(x)

%timeit method_rotate(x)
100000 loops, best of 3: 7.83 us per loop

%timeit method_roll(xa)
10 loops, best of 3: 95 ms per loop

%timeit method_slice(x)
1 loops, best of 3: 229 ms per loop
</pre>
<p>So deque rotation is blazingly fast which is not surprising given that rotation is equivalent to repeated pop-append which is exactly what deques are optimized for <a class="fn-ref-mark" href="#footnote-2" id="refmark-2"><sup>[2]</sup></a>. Roll and slice-concat are at least three orders of magnitude slower which is probably a testament to the design of deques.</p>
<p>But here is the equivalent slicing and concatenation operation in R <a class="fn-ref-mark" href="#footnote-3" id="refmark-3"><sup>[3]</sup></a>:</p>
<pre name='code' class='python'>
r = 1:1e7
system.time(c(r[500:1e7],r[1:500]) )
    user  system elapsed
  0.184   0.060   0.243
</pre>
<p>So it would seem that R can rotate an array faster than numpy.roll. Now I know it&#8217;s not that much faster and in practice Python would probably come out ahead. But still. R?</p>
<div id="footnote-list" style="display:inherit"><span id=fn-heading>Footnotes</span> &nbsp;&nbsp;&nbsp;(&crarr; returns to text)
<ol>
<li id="footnote-1" class="fn-text"><a href="http://kx.com">KDB</a><a href="#refmark-1">&crarr;</a></li>
<li id="footnote-2" class="fn-text"><a href="http://docs.python.org/library/collections.html">Python Collections Module</a><a href="#refmark-2">&crarr;</a></li>
<li id="footnote-3" class="fn-text"><a href="http://www.r-project.org/">R-Project</a><a href="#refmark-3">&crarr;</a></li>
</ol>
</div>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/10/31/rotating-arrays-with-python/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Predicate logic plus message passing?</title>
		<link>http://bitshaq.com/2011/10/31/718/</link>
		<comments>http://bitshaq.com/2011/10/31/718/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 14:52:09 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[hadoop]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=718</guid>
		<description><![CDATA[Right now I think it would be really nice to go back to the roots of Erlang and add Prolog-like predicate logic to the language, a kind of new mixture of predicate logic plus message passing. &#8212; Joe Armstrong, Creator of Erlang (link) Software frameworks come into existence when general purpose languages are adapted for [...]]]></description>
			<content:encoded><![CDATA[
<blockquote><p>
Right now I think it would be really nice to go back to the roots of Erlang and add Prolog-like predicate logic to the language, a kind of new mixture of predicate logic plus message passing.</p>
<p> &#8212; Joe Armstrong, Creator of Erlang (<a href="http://www.teachersyndicate.com/documents/nov_2010/Seven%20Languages%20in%20Seven%20Weeks%20A%20Pragmatic%20Guide%20to%20Learning%20Programming%20Languages.pdf">link</a>)
</p></blockquote>
<p>Software frameworks come into existence when general purpose languages are adapted for a very specific purpose. Like Python has been adapted for web application development via django. Eventually the frameworks reach a critical level of complexity which takes on a life of its own. Consider Java&#8217;s Hadoop eco-system as a prime example. Eventually, the status quo gets disrupted by a new (renewed?) language/paradigm. I hope that&#8217;s what Joe was talking about.</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/10/31/718/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>100 Easy Steps to a (Employment-Based) Green Card</title>
		<link>http://bitshaq.com/2011/08/24/100-easy-steps-to-a-employment-based-green-card/</link>
		<comments>http://bitshaq.com/2011/08/24/100-easy-steps-to-a-employment-based-green-card/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 15:45:34 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[green card]]></category>
		<category><![CDATA[humor]]></category>
		<category><![CDATA[personal]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=604</guid>
		<description><![CDATA[I arrived in the summer of 1999 as a seventeen year old college student in the United States. In 2004 I started working full time which paved the way for me to receive an employment based (EB) green card. While the green card application was pending, I got married, settled down, bought a house, had [...]]]></description>
			<content:encoded><![CDATA[
<div id="attachment_605" class="wp-caption aligncenter" style="width: 430px"><a href="http://bitshaq.com/wp-content/uploads/2011/06/uscis_game.jpg"><img class="size-full wp-image-605  " src="http://bitshaq.com/wp-content/uploads/2011/06/uscis_game.jpg" alt="" width="420" height="420" /></a><p class="wp-caption-text">Green Card Game</p></div>
<p>I arrived in the summer of 1999 as a seventeen year old college student in the United States. In 2004 I started working full time which paved the way for me to receive an employment based (EB) green card. While the green card application was pending, I got married, settled down, bought a house, had a kid, and paid income and social security taxes. </p>
<p>Finally, in the summer of 2011 we received our green cards in the mail along with a congratulatory letter from the USCIS titled &#8220;Welcome to the United States.&#8221; After having lived in the US for eleven years and anxiously awaiting the green card for the last seven of those years, I would say the congratulatory letter is a tad belated. But as they say, better late than never.</p>
<p>Currently there are several thousand applications for EB green cards pending a decision. Many of them have been pending for more than the seven years it took for my application to be ajudicated and approved. There is no way of accurately determining which stage an application is in or when it will be adjudicated. It&#8217;s a painfully slow and opaque bureaucratic process that can feel like a game of chance with diminishing returns as time wears on.</p>
<p>Those who are still playing the game, know that if you play long enough you will eventually reach the finish line. The end however will feel like it took forever and the satisfaction of reaching it won&#8217;t be as intense as the <i>anticipation</i> of reaching it. Probably best to think of it as a new beginning and chug along&#8230;</p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/08/24/100-easy-steps-to-a-employment-based-green-card/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic Intro To Ruby Meta Programming</title>
		<link>http://bitshaq.com/2011/08/01/basic-intro-to-ruby-meta-programming/</link>
		<comments>http://bitshaq.com/2011/08/01/basic-intro-to-ruby-meta-programming/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 21:45:16 +0000</pubDate>
		<dc:creator>Salman Haq</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://bitshaq.com/?p=650</guid>
		<description><![CDATA[My previous post about Python Meta Programming drew a fair bit of attention including one (that I know of) twitter troll that referred to Python&#8217;s model as &#8216;retarded&#8217;. Overreact much? Anyway, this prompted me to dive deeper into Ruby&#8217;s meta programming model to enlighten myself. One of the practical differences between Python and Ruby is [...]]]></description>
			<content:encoded><![CDATA[
<p>My <a href="/2011/07/14/basic-intro-to-python-meta-programming/">previous post</a> about Python Meta Programming drew a fair bit of attention including one (that I know of) twitter troll that referred to Python&#8217;s model as &#8216;retarded&#8217;. Overreact much? Anyway, this prompted me to dive deeper into Ruby&#8217;s meta programming model to enlighten myself.</p>
<p>One of the practical differences between Python and Ruby is that the latter supports &#8216;open classes&#8217;. That is to say, a class can be defined several times in different files and the interpreter extends the class each time. Here is a simple snippet that demonstrates this in action:</p>
<pre name='code' class='ruby'>
# define class A with one method
class A
    def foo
        puts "in foo"
    end
end

# open class A and add one more method
class A
    def bar
        puts "in bar"
    end
end

a = A.new()
a.foo
in foo
a.bar
in bar
</pre>
<p>This behavior allows a Ruby programmer to extend even a built-in type like <i>Fixnum</i> or <i>String</i>. This is a second practical difference between the two languages. In Python, built-in types are immutable. If a programmer wants to extend a built-in, they have to sub-class it.</p>
<p>And that brings us to a third practical difference: mixins. Python supports mixins via multiple inheritance. Ruby supports mixins via <i>modules</i> which is just a namespace for a logically related set of constants, classes, and functions. A module can be included in a class to enhance it. Let&#8217;s continue the previous example:</p>
<pre name='code' class='ruby'>
# this is a simple module that encompasses one function
module Baz
    def baz
        puts "in baz"
    end
end

# now we extend class A by including the module
class A
    include Baz
end

# create a new instance of 'A' that has three methods: foo, bar, baz
a2 = A.new
a2.baz # this prints "in baz"!
</pre>
<p>If you are a pythonista encountering Ruby for the first time then these differences might give you an uneasy feeling. That&#8217;s because in Python, this behavior of Ruby is referred to as &#8216;monkey patching&#8217; and is generally considered unpythonic. But it lends Ruby its trademark flexibility.</p>
<p>These and some other practical differences aside (<sup><a href="#footnote1">1</a></sup>), Ruby and Python are both dynamic, strongly typed, object-oriented languages so they can accommodate the same kind of programming model.</p>
<p>Now, for an object-oriented language to be able to support meta programming, there typically has to be a way to programatically create a new class during runtime. In Python, I&#8217;ve previously demonstrated this as the purpose of <i>type</i> callable. Its Ruby equivalent is <strong>Class.new</strong>:</p>
<pre name='code' class='ruby'>
# create a new class, B, that inherits from A
B = Class.new(A)
</pre>
<p>So <Strong>Class.new</Strong> affords us a way to create anonymous classes at runtime. It is a powerful technique that is used heavily to generate complex classes for the programmer without having to declare them explicitly.</p>
<p>Ruby also has a very handy class, <strong>Struct</strong>, that allows us to create anonymous classes with user-specified attributes. It is used throughout the excellent <i>PacketFu</i> library (<sup><a href="#footnote2">2</a></sup>) which is Ruby&#8217;s equivalent of Python&#8217;s <i>dpkt</i> (<sup><a href="#footnote3">3</a></sup>) from which we cited code snippets in the previous post.</p>
<p>Here is a snippet from PacketFu that demonstrates how Struct is used:</p>
<pre name='code' class='ruby'>
       # EthHeader is being declared by inheriting from an anonymous class.
       # The anonymous class is being created by calling Struct.new and
       # passing it several symbols as arguments.
       # The anonymous class will be generated so that the aforementioned arguments
       # become instance attributes of the EthHeader. In this sense, it is a meta class
       # of EthHeader.
       class EthHeader < Struct.new(:eth_dst, :eth_src, :eth_proto, :body)
                # StructFu is a module in the PacketFu library. It is being used as a mixin here.
                include StructFu

                # initialize the instance attributes here.
                # EthMac and Int16 are classes defined above EthHeader.
                def initialize(args={})
                        super(
                                EthMac.new.read(args[:eth_dst]),
                                EthMac.new.read(args[:eth_src]),
                                Int16.new(args[:eth_proto] || 0x0800),
                                StructFu::String.new.read(args[:body])
                        )
                end
               # ... more stuff follows here ...
</pre>
<p>Now, the <strong>Struct</strong> class is implemented in C as part of Ruby's core (<sup><a href="#footnote4">4</a></sup>).<br />
But let's see how it could be implemented in Ruby itself:</p>
<pre name="code" class="ruby">
# Let's name our implementation 'Structure'
class Structure

	# The reference implementation includes the Enumerable module
	# so we do it for consistency.
	include Enumerable

	# override the 'new' method of the Structure metaclass.
	# create a new anonymous class with specified
	# symbols as instance variables.
	def self.new (*symbols)

		# the class is created by passing a block to Class.new
		klass = Class.new do

			# iterate through the symbols passed as arguments
			# and create instance attributes from them.
			symbols.each do |sym|
				attr_accessor sym
			end

			# create a class instance attribute 'members' and assign
			# the list of symbols. this attribute is useful for
			# inspecting the class and is also used to initialize
			# an instance. we do this by opening the meta class of klass:
			class << self
				attr_accessor :members
			end
			@members = symbols.clone

			# initialize the instance variables by assigning
			# (optional) program supplied values to them.
			def initialize (*vals)
				if not vals.empty?
					self.class.members.each_with_index do |mem, i|
						instance_variable_set("@"+mem.to_s, vals[i])
					end
				end
			end
		end
	end
end
</pre>
<p>N.B: This is a working implementation but it is not in full conformity with the reference implementation. Among the things that have been left out for brevity:<br />
 * Support for supplying a name for the generated class.<br />
 * 'include'ing the generated class in the Structure module itself.<br />
 * ... and probably a few other things.</p>
<p>The meta programming begins with <strong>def self.new</strong>. The <strong>self</strong> keyword in Ruby is used in a very different sense than in Python. Generally it refers to the meta class of a class. This gives the Ruby programmer the ability to access and modify the meta class inline! In fact meta programming in Ruby is all about managing <strong>self</strong> (<a href="#footnote5">5</a>).</p>
<p>Astute Python programmers will have picked up on two more practical differences between Ruby and Python meta programming by now, namely that Ruby meta classes are anonymous while in Python they are explicit, and secondly, Ruby allows meta class manipulation inline. The latter difference is probably what provoked the troll to dismiss Python as making meta programming hard by forcing them to define the meta class apriori.</p>
<p>Now lets see how this would actually be used:</p>
<pre name="code" class="ruby">
# define EthHeader by inheriting from the class generated by 'Structure' instead of 'Struct'
class EthHeader < Structure.new(:eth_dst, :eth_src, :eth_proto, :eth_body)
	# implement EthHeader exactly as in PacketFu
end

# instantiate an EthHeader object
header = EthHeader.new
header.eth_proto = 0x0800
# ... and so on ...
</pre>
<p>So there you have it... our own working re-implementation of Struct written in Ruby.</p>
<p>There are several tools in Ruby meta programming toolbox that I did not touch upon in this post (<a href="#footnote6">6</a>). For Python programmers, this serves as a quick overview of meta programming in Ruby. While for Ruby programmers  who might already be familiar with the tricks employed here but they may have taken Struct for granted, this hopefully gave them a new appreciation for their favorite factory class.</p>
<p>u can now haz the meta codez. enjoy!</p>
<hr />
<p>(1) <a name='footnote1'></a>For a more comprehensive treatment of the practical differences between Ruby and Python, see <a href="http://blog.ianbicking.org/ruby-python-power.html">Ruby Python "Power" by Ian Bicking</a>.</p>
<p>(2) <a name='footnote2'></a> <a href="http://code.google.com/p/packetfu/">PacketFu repository on Google Code</a></p>
<p>(3) <a name='footnote3'></a> <a href="http://code.google.com/p/dpkt/">dpkt repository on Google Code.</a> </p>
<p>(4) <a name='footnote4'></a> <a href="https://github.com/ruby/ruby/blob/trunk/struct.c">Implementation of the Struct class in the Ruby source code repository on github.com</a></p>
<p>(5) <a name='footnote5'></a>  <a href="http://yehudakatz.com/2009/11/15/metaprogramming-in-ruby-its-all-about-the-self/">Metaprogramming in Ruby: It’s All About the Self</a></p>
<p>(6) <a name="footnote6"></a> <a href="http://weare.buildingsky.net/2009/08/25/rubys-metaprogramming-toolbox"</a>Ruby's Meta Programming Toolbox</a></p>

]]></content:encoded>
			<wfw:commentRss>http://bitshaq.com/2011/08/01/basic-intro-to-ruby-meta-programming/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

