<?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>Nine Mohs</title>
	<atom:link href="http://code.scrapcrap.org/feed" rel="self" type="application/rss+xml" />
	<link>http://code.scrapcrap.org</link>
	<description>Ruby, Programming, Technology, Fun</description>
	<lastBuildDate>Sun, 07 Feb 2010 11:19:20 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Internet Relay Story &#8211; I</title>
		<link>http://code.scrapcrap.org/internet-relay-story-i</link>
		<comments>http://code.scrapcrap.org/internet-relay-story-i#comments</comments>
		<pubDate>Sun, 07 Feb 2010 10:21:39 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[IRC]]></category>
		<category><![CDATA[Lame]]></category>
		<category><![CDATA[Internet]]></category>
		<category><![CDATA[kitallis]]></category>
		<category><![CDATA[Relay Story]]></category>
		<category><![CDATA[sid0]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=339</guid>
		<description><![CDATA[
EVENTS OCCUR IN REAL-TIME.

09:56 [Users #kit-room]
09:56 [@ChanServ] [ kitalis_] [ kitallis]
09:56 --&#62; #kit-room: Total of 2 nicks (1 ops, 0 halfops, 0 voices, 1 normal)
09:57 --&#62; kitallis (n=kitallis@343.345.232.27) has joined #kit-room
09:59         kitallis : *Yawn*
10:00         kitallis : Darn. It's 10 [...]]]></description>
			<content:encoded><![CDATA[<pre class="brush: plain; gutter: false">
EVENTS OCCUR IN REAL-TIME.

09:56 [Users #kit-room]
09:56 [@ChanServ] [ kitalis_] [ kitallis]
09:56 --&gt; #kit-room: Total of 2 nicks (1 ops, 0 halfops, 0 voices, 1 normal)
09:57 --&gt; kitallis (n=kitallis@343.345.232.27) has joined #kit-room
09:59         kitallis : *Yawn*
10:00         kitallis : Darn. It's 10 P.M. already. Better finish my work off
10:00         kitallis : or I'll have to face KCs sad breath tommorow morning.
10:02  ! kitallis snaps out his Dell, starts working
10:03  ! kitallis goes and grabs a can of b33r
10:03         kitallis : Hmm, LaTeX is giving me the creeps
10:04         kitallis : might as well make this in PowerPoint.
10:06         kitallis : *Sigh*
10:06         kitallis : I'm a fucking programmer, why do I even need to make this shite :S
10:06         kitallis : I'd rather ... ohh, what's this ... hmm, p0rn ... naaaicee.
10:07         kitallis : These clothes are rather uncomfortable
10:07         kitallis : I should change to something comfortable first.
10:08  ! kitallis opens his wardrobe, grabs some pyjamas.
10:08  ! kitallis sees something glimmering in the dark corridor
10:08         kitallis : Hmm, that was odd. I swear I saw two white round balls shining
10:08         kitallis : over there. Probably cuz of this stupid little b33r
10:10         kitallis : Argh, WTH. Shouldn't waste time. I'm so pumped already.
10:11  ! kitallis turns the music on
10:11         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:12         kitallis : Ahhh, /me feel so trippy.
10:12         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:13         kitallis : This is so nice ...
10:13         kitallis : so where was I ...
10:13         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:14  ! kitallis does a Control+Shift+P
10:14         kitallis : naicce, fuck work, living alone is awesome ...
10:14         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:16         kitallis : Shit, need moar b33r.
10:16         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:16  ! kitallis stands up, minimizing the browser, turns around ...
10:17             sid0 : &lt;_&lt;
10:17  ! kitallis drops the empty can in his hands
10:18         ChanServ : *DHUGH DHUG.
10:18         kitallis : ...
10:18         kitallis : ...
10:18             sid0 : &lt;_&lt;
10:18         kitallis : ...
10:19             sid0 : &lt;_&lt;
10:19         kitallis : ...
10:19  ! kitallis quietly goes around him and leaves the room
10:20         kitallis : ...
10:19             sid0 : &lt;_&lt;
10:19         kitallis : ...
10:19             sid0 : @_@
10:19         kitallis : ...
10:20             sid0 : &gt;_&gt;
10:20 --&gt; kitallis (n=kitallis@343.345.232.27) has left #kit-room ()
10:20  ! kitallis calls m1k3y
10:20         kitallis : m1k3y: dude, you won't fucking believe what happened just now
10:21         kitallis : m1k3y: can't even begin to explain you ...
10:21            m1k3y : kitallis, bhut
10:21  ! kitallis starts running
10:21         kitallis : m1k3y: well, nvm, I'll explain later
10:21         kitallis : m1k3y: can I just sleep over at your house, for tonight?
10:22            m1k3y : kitallis, shyoar
10:23         kitallis : ...
10:23         kitallis : Can't think. Gotta think. Not right. Rite. Right.
10:23         kitallis : Something is wrong. Wrong. Lights. Something is wrong.
10:23         kitallis : Probably the b33r. No, I'm good. You're good. We. Us.
10:23         kitallis : Gotta run. Fast. Something was wrong.
10:24         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:24         kitallis : ...
10:24         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:24         kitallis : What's happening. Run. Big strides. Alcohol. No. Fast.
10:25         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:25         kitallis : ...
10:27  ! kitallis rings m1k3y's doorbell
10:27         kitallis : ...
10:27         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:27         kitallis : Need to get this music outta my mind. Need to. Now.
10:28            m1k3y : haye kitallis
10:28            m1k3y : kitallis, Dude, you look drunk
10:28         kitallis : m1k3y: sorta, just a little b33r, wasn't feeling right over there.
10:29            m1k3y : kitallis, oya, iy understand, cum on in.
09:29 [Users #m1k3y-room]
09:29 [@ChanServ] [ m1k3y] [ prostitute]
09:29 --&gt; #m1k3y-room: Total of 2 nicks (1 ops, 0 halfops, 0 voices, 1 normal)
10:29 --&gt; kitallis (n=kitallis@343.345.232.27) has joined #m1k3y-room
10:29         kitallis : m1k3y: KTHX
10:29         kitallis : m1k3y: Dude, I should sleep now, very tired.
10:30            m1k3y : kitallis, :S
10:30            m1k3y : kitallis, err... k
10:30            m1k3y : kitallis: we'll tawk in tah mornin'
10:31         kitallis : m1k3y: thx, for all this
10:31            m1k3y : kitallis: np, d00d.
10:32         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:33         kitallis : Must go to sleep. Right fucking now.
10:34  ! kitallis lies on the bed, grabs the blanket
10:34         kitallis : Hmm. Teddy Bear. Tomatoes. Cold. Need to sleep
10:34         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:35  ! kitallis turns the lights off, dissolves into a sleeping shape
10:36         kitallis : I'm not sure why it came
10:36         kitallis : It just stood. I wasn't ready.
10:37         kitallis : I swear I wanted to shout
10:37         kitallis : But for some reason I didn't.
10:37         kitallis : I don't think I'll be able to sleep this way.
10:39  ! kitallis turns around to check the time on m1k3y's Bose clock
10:39         kitallis : 10:41 it says. Ain't even mid-night yet.
10:39         kitallis : Gotta try sleeping in any case.
10:40             sid0 : &gt;_&gt;
10:40  ! kitallis wiggles his head
10:40         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:41             sid0 : &gt;_&gt;
10:41         kitallis : ...
10:41             sid0 : &gt;_&gt;
10:41         kitallis : HOLY FUCKING GAWD, HE'S BLOODY HERE AGAIN.
10:41         kitallis : LEAVE ME FUCKING ALONE, YOU S.O.B.
10:42             sid0 : &gt;_&gt;
10:43  ! kitallis storms out of the room
10:43            m1k3y : kitallis: wut happened?
10:43 --&gt; kitallis (n=kitallis@343.345.232.27) has left #m1k3y-room ()
10:44            m1k3y : ...
10:45         kitallis : Why is this happening. Why is it there.
10:47         kitallis : I gotta run. Gotta find a loophole
10:47         kitallis : Need to get rid of him
10:49         kitallis : There should be a way. There always is.
10:50         kitallis : Need to find something to get sober first.
10:50         kitallis : Can't think this way. Chemist. Adrenaline shot. Need one.
10:50         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:52  ! kitallis crosses the road, runs over to the Chemist
10:53         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:53         kitallis : Can I get some Epinephrine shots?
10:53          ChemGuy : are you god?
10:53         kitallis : No :S
10:53          ChemGuy : sucks duzunnit?
10:53         kitallis : not really.
10:53          ChemGuy : wife? kids?
10:54         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:54         kitallis : No
10:54          ChemGuy : single lol
10:54         kitallis : yaahh /0/
10:54         kitallis : Just gimme the meds already.
10:54          ChemGuy : kk
10:58  ! kitallis injects some Adrenaline
10:59         kitallis : There must be some place it can't enter.
10:59         kitallis : Why is it doing this to me.
10:59  ! kitallis spits twice in a gap of three seconds, then spits again.
11:00         kitallis : Hmm, this is making me feel so alive
11:00         kitallis : I should just fucking run away as far as I can
11:02  ! kitallis starts leaping into the infinite road ahead.
11:03         kitallis : ...
11:03         kitallis : ...
11:03         kitallis : Truck.
11:04  ! kitallis slams into the speeding truck
11:04         kitallis : ...
11:03      TruckDriver : HOLY SHIT. CALL THE AMBULANCE. FUCKING CALL THE HOSPITAL!
11:04          SomeGuy : WTF happened!
11:04       AnotherGuy : Dear god...
11:05      TruckDriver : Somebody get a fucking ambulance!!
11:05      TruckDriver : He was fucking running like maniac in the middle of the street
11:05      TruckDriver : in the opposite fucking direction, slammed straight into me
11:05       AnotherGuy : Dear god...
11:06         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
11:06         kitallis : bhut ha...ppened...
11:06      TruckDriver : OMG he's waking up!! ...try relaxing kid.
11:06       AnotherGuy : Dear god...
11:07          SomeGuy : They're here, the ambulance is here!
11:07            Medic : Get him in! Get him in! Go! Go! GO!
11:07       AnotherGuy : Dear god...
11:08         kitallis : wha ...
11:08         kitallis : mhmmmhmm ...
11:08       AnotherGuy : Dear god...
11:09         kitallis : AnotherGuy: stfu n00b.
11:09       AnotherGuy : kk
11:10          SomeGuy : I Think he'll be alright
11:10      TruckDriver : You never know. You never do.
11:58  ! kitallis wakes up, in the hospital, drowsy
11:58         kitallis : Plaster. Bandage. Blood. Peace.
11:58  ! kitallis looks around.
11:58         kitallis : I think it's over.
11:58         kitallis : He was just a fragment of my pervert imagination, I guess
11:58  ! kitallis closes his eyes for a while
11:59  ! kitallis looks around again.
11:59         kitallis : Yep. It's over.
11:59  ! kitallis does a shut-eye and goes back to sleep.
12:00             sid0 : &lt;_&lt;
</pre>
<p>Obligatory blog post. An intended mockery on the deeds of the great <a href="http://monogatari.doukut.su/">sid0</a>. He&#8217;s watching.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/internet-relay-story-i/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design Patterns in Ruby : The Factory Method</title>
		<link>http://code.scrapcrap.org/dpr2</link>
		<comments>http://code.scrapcrap.org/dpr2#comments</comments>
		<pubDate>Sun, 26 Apr 2009 17:47:09 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Creational]]></category>
		<category><![CDATA[Factory Method]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Russ Olsen]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=291</guid>
		<description><![CDATA[This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here&#8217;s a link to the last article on the Template Design Pattern.
The Factory Method Pattern
I have to this say this, but Wikipedia has a pretty good explanation and a Ruby implementation for this Creational [...]]]></description>
			<content:encoded><![CDATA[<p>This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here&#8217;s a <a href="http://code.scrapcrap.org/dpr1">link</a> to the last article on the Template Design Pattern.</p>
<h3>The Factory Method Pattern</h3>
<p>I have to this say this, but Wikipedia has a pretty good explanation and a Ruby implementation for this Creational Pattern, so I&#8217;d be focusing mainly upon the general idea of why this pattern is similar to the Template Method pattern and explain some of its defined variants.</p>
<p><strong>What is it? </strong></p>
<p><strong><span style="font-weight: normal;">It is a Creational design pattern : defining how created objects should be mechanised as per the pattern as chances are there might be design problems with bad object control.</span></strong></p>
<p><strong>When is it needed? </strong></p>
<p><strong><span style="font-weight: normal;">It&#8217;s all about picking the right class. It&#8217;s pretty much like the Template Method pattern. In the Template Method pattern there was a generic portion which was stored in a base class and the other fill-in-the blanks were controlled by the subclasses and the Template method drove certain methods so that they needn&#8217;t be explicitly called. Here, with the Factory Method those subclasses determine what objects to be created. So the Factory Method is for creating objects as Template Method was for driving an algorithm.</span></strong></p>
<p><strong>How is it done?</strong></p>
<p><strong><span style="font-weight: normal;">Here&#8217;s my dummy implementation for the Factory Method pattern.</span></strong></p>
<pre class="brush:ruby">module Factory
  def draw
     raise NotImplementedError, "You need to call this method, brotha"
  end
end

class Circle
 include Factory
 def draw
   # Clear Screen
   # Draw Circle
 end
end

class Square
 include Factory
   def draw
     # Clear Screen
     # Draw Square
   end
end

class Tetrahedron
  include Factory
  def draw
    # Clear Screen
    # Draw Square
  end
end

class RandomShape
  include Factory
    def draw
      # Clear Screen
      # Draw any shape apart from the above three
    end
end

class CreateShape
  def self.CallShapes(shape)
    case(shape)
      when "Circle"
        Circle.new
      when "Square"
        Square.new
      when "Tetrahedron"
        Tetrahedron.new
    else
      RandomShape.new
    end
  end
end</pre>
<p>More precisely, the Shape module is for defining the Draw method which raises a predefined NotImplementedError exception object. Circle, Square and Tetrahedron are the subclasses which call the Shape module and are called by the Factory Method &#8211; CallShapes for creating objects out of them to be selected as per the user call.</p>
<p>This pattern is used when a class (the<em>Creator</em>) does not know beforehand all the subclasses that it will create. Instead, each subclass (the <em>Concrete Creator</em>) is left with the responsibility of creating the actual object instances.<br />
The example shown here is specifically a Parametrized Factory Method, that takes in certain parameters from the user and creates objects accordingly.</p>
<p>Abstract Factory Method can pretty much be understood by this UML diagram</p>
<p><img class=" alignnone" title="Factory Method UML" src="http://img111.imageshack.us/img111/307/dpr2.jpg" alt="Factory Method UML" width="536" height="354" /></p>
<p>(Courtesy : Design patterns in Ruby )</p>
<p>The basic idea behind Abstract Factory Methods are to form a group of factories that are compatible with each other. According to the diagram, there are Two Factories encapsulated by one single Abstract factory and each concrete factory produces its set of compatible products. And that&#8217;s pretty much what Abstract Factory Methods are.</p>
<p>Taking an example from the Book, the ActiveRecord library uses a form of this kind of pattern.<br />
ActiveRecord has an adapter class for each different kind of database that it uses like MySQL, Oracle. To set up the connection the user name, password, and a string containing the name of the adapter that ActiveRecord uses is supplied. So we enter &#8216;mysql&#8217; if we want to talk to a MySQL database and so on. To accomplish this a Base class is present that has no adapter related code.<br />
But there are Subclasses that modifying the Base code, that is, each adapter adds a method that creates its specific type of connection to<br />
the Base class.</p>
<pre class="brush:ruby">class Base
# Lots of non-adapter-related code removed...
end

class Base
  def self.mysql_connection(config)
 # Create and return a new MySQL connection, using
 # the user name, password, etc. stored in the
 # config hash...
  end
end

class Base
  def self.oracle_connection(config)
 # Create a new Oracle connection...
  end
end</pre>
<p>If a structured object creation method like the Factory Method in a class is not implemented, we might end up creating methods for each new object we want to create.</p>
<p><strong>References</strong></p>
<p><span style="color: #000000; text-decoration: none;">[1] <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Wikipedia</a></span></p>
<p>[2] <a href="http://www.programmersheaven.com/2/Tutorial-Design-Patterns-Factory-method"><span style="text-decoration: none;">Programmers Heaven</span></a></p>
<p><strong> </strong></p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/dpr2/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Design Patterns in Ruby : The Template Method</title>
		<link>http://code.scrapcrap.org/dpr1</link>
		<comments>http://code.scrapcrap.org/dpr1#comments</comments>
		<pubDate>Sun, 08 Mar 2009 19:58:20 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[ControlTier]]></category>
		<category><![CDATA[GoF]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Russ Olsen]]></category>
		<category><![CDATA[Template Method]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=231</guid>
		<description><![CDATA[Just before a month ago I was sweating out, playing away with my small little Ruby programs which were surely not pieces of code you&#8217;ll want to read and learn with. Now just after my fifteen day brawl with the Design Patterns, I find myself a totally revamped programmer.
This is my new article series which [...]]]></description>
			<content:encoded><![CDATA[<p>Just before a month ago I was sweating out, playing away with my small little Ruby programs which were surely not pieces of code you&#8217;ll want to read and learn with. Now just after my fifteen day brawl with the Design Patterns, I find myself a totally revamped programmer.<br />
This is my new article series which would cover a few of the popular programming Design Patterns in software engineering devised by the<a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)"> GoF</a>. I would be starting off with some basic Design Patterns and then move onto Ruby specific patterns based upon the book &#8220;<a href="http://www.amazon.com/Design-Patterns-Ruby-Addison-Wesley-Professional/dp/0321490452">Design Patterns In Ruby</a>&#8221; by Russ Olsen.</p>
<p><img class="alignnone" title="Design Patterns In Ruby" src="http://ecx.images-amazon.com/images/I/51NG5mF-SAL._SL500_AA240_.jpg" alt="" width="240" height="240" /></p>
<p>The Design Patterns that&#8217;ll be explained are :</p>
<p>1. The Template Method (explained here)<br />
2. <a href="http://code.scrapcrap.org/dpr2">The Factory Method</a></p>
<p>(They will be updated as the series expands)<br />
You can Subscribe to my Blog Feeds for constant updates on the articles or you can follow me on www.twitter.com/kitallis<br />
This is the base article for the series and you can always look back at this as an archive for others.</p>
<p>Prerequisites would be, a knowledge of Ruby&#8217;s Object Oriented features and a belief that this would actually help you get better.<br />
These articles would follow a simple pattern of explaining the design pattern, disadvantages without it and improving with it. If you don&#8217;t quite get what I&#8217;m talking about, you might want to take a look at this.</p>
<h3>The Template Method Pattern</h3>
<p><strong>When is it needed?</strong><br />
The Design patterns are a way of solving a problem in a particular way and is in no way related to reducing the complexity of the algorithm.<br />
The basic problem on which this DP is implemented upon is a varying piece of code mixed in with the part that remains static. So we would be separating the code that stays the same (probably the algorithm) with the piece of code that is dynamic (probably the processing data).</p>
<p><strong>How can we do it?</strong><br />
By separating and encapsulating the common entities into a subclass and the changing entities/behaviour into derived classes and thereby allowing the common behaviour to not repeat itself.<br />
More specifically, building an abstract base class with a skeletal method (template method) that&#8217;d control the part that needs to vary by making calls to the Abstract Method whose actual control is further provided by the subclasses.<br />
Even more strictly, this is an actual application of the Template Method Pattern in the <a href="http://open.controltier.org/manuals/3.1/platform.html">ControlTier</a> project which defines an application installation procedure<br />
(other details are unnecessary here)</p>
<p><img class="alignnone" title="ControlTier Template Method Implementation  " src="http://img9.imageshack.us/img9/1048/packageinstallpackage.png" alt="" width="393" height="288" /></p>
<p>(Courtesy : <a href="http://apps.sourceforge.net/mediawiki/controltier/index.php?title=Main_Page">ControlTier Wiki</a>)</p>
<p>The Template Methods residing in the Abstract class are &#8216;driving&#8217; certain Operations and the subclasses are actually implementing those Operations. So here, InstallPackage is the Template Method which defines all usable methods and zip is the concrete subclass which calls methods it requires.</p>
<p>So, the quick advantages we get are :</p>
<p>1. We can expand to more subclasses even if they require a varying algorithm for the methods defined</p>
<p>2. The algorithm is separated from the static definitions and initialisations</p>
<p>This is my dummy code for the pattern</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code4'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2314"><td class="code" id="p231code4"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Package  <span style="color:#008000; font-style:italic;"># this is the abstract base class</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> InstallPackage  <span style="color:#008000; font-style:italic;"># this is the template method</span>
&nbsp;
  create
  installDependencies
  prepare
  get
  extract
  finish
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> installDependencies
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> prepare
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> get
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> extract
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> finish
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Zip <span style="color:#006600; font-weight:bold;">&amp;</span>lt; Package  <span style="color:#008000; font-style:italic;"># this is the concrete subclass</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> create
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> extract
  <span style="color:#008000; font-style:italic;">#</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>And it might be called this way</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code5'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2315"><td class="code" id="p231code5"><pre class="ruby" style="font-family:monospace;">z = Zip.<span style="color:#9900CC;">new</span>
&nbsp;
z.<span style="color:#9900CC;">InstallPackage</span> <span style="color:#008000; font-style:italic;"># calling the template method from the subclass</span></pre></td></tr></table></div>

<p><strong>GOF describes a Hook Method</strong><br />
These are basically just virtual methods which may or may not have code inside them in base classes.<br />
They are a way of telling the concrete subclasses that &#8220;either use the default implementation in the abstract class or override it for some varying algorithm and do something different&#8221;</p>
<p>Implementations without this pattern could be</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p231code6'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2316"><td class="code" id="p231code6"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Package
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> get_method<span style="color:#006600; font-weight:bold;">&#40;</span>type<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span> 
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">if</span> type == <span style="color:#996600;">&quot;Zip&quot;</span> 
&nbsp;
  <span style="color:#008000; font-style:italic;"># create algorithm</span>
  <span style="color:#008000; font-style:italic;"># extract algorithm</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">elsif</span> <span style="color:#008000; font-style:italic;">#some other type</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>which could be amazingly hard to expand for large pieces of code.<br />
I&#8217;m obviously not that experienced a programmer to write hugely scalable projects but I find it a good habit to adopt patterns even while writing smaller snippets.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/dpr1/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Scoar!</title>
		<link>http://code.scrapcrap.org/scoar</link>
		<comments>http://code.scrapcrap.org/scoar#comments</comments>
		<pubDate>Mon, 16 Feb 2009 18:18:39 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[Other]]></category>
		<category><![CDATA[Atari]]></category>
		<category><![CDATA[Chip's Challenge]]></category>
		<category><![CDATA[James Bond]]></category>
		<category><![CDATA[Putt Putt]]></category>
		<category><![CDATA[Retro]]></category>
		<category><![CDATA[Sega]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=189</guid>
		<description><![CDATA[My first encounter with anything called a &#8216;Video Game&#8217; was with a Macintosh and a MacPlay CD-ROM of  &#8221;Putt Putt and Fatty Bear&#8217;s Activity Pack&#8220;.

It had an arcade style baloon bursting side-scroller, Fatty Bear templates on which we could color and lots of random fun stuff like card games and races which were amazingly intoxicating. [...]]]></description>
			<content:encoded><![CDATA[<p>My first encounter with anything called a &#8216;Video Game&#8217; was with a Macintosh and a <a href="http://en.wikipedia.org/wiki/Macplay">MacPlay</a> CD-ROM of  &#8221;<a href="http://en.wikipedia.org/wiki/Putt-Putt_(game_character)">Putt Putt and Fatty Bear&#8217;s Activity Pack</a>&#8220;.</p>
<p><img class="alignnone" title="Putt Putt and Fatty Bears Activity Pack" src="http://img261.imageshack.us/img261/8870/scummvm1818qt1.jpg" alt="" width="256" height="192" /></p>
<p>It had an arcade style baloon bursting side-scroller, Fatty Bear templates on which we could color and lots of random fun stuff like card games and races which were amazingly intoxicating. Infact, I played this about 2-3 hours everyday for 2 months on our vacation to my cousin&#8217;s. I was about 5 years old and apparently it was the first computer I ever touched, that too a Macintosh (unlike most other Indians)</p>
<p>Then there was <a href="http://en.wikipedia.org/wiki/Spaceship_Warlock">Spaceship Warlock</a>, a dark game with a really scary title music piece (really, it&#8217;s pretty scary, like a fearful enchant or something). The graphics were pretty nice for a game that old and with mostly dark environments in places not prominent. <a href="http://www.youtube.com/watch?v=C8UPbP8gwtw">Here&#8217;s a video</a>.</p>
<p><img class="alignnone" title="Spaceship Warlock" src="http://img261.imageshack.us/img261/8136/spaceshipwarlockax7.png" alt="" width="320" height="120" /></p>
<p>A few months later after my brawl with the Mac, my dad bought home an Atari 2600 console which wasnt exactly the real Atari it was just some chinese hack. One of the games I remember was <a href="http://en.wikipedia.org/wiki/Superman_(Atari_game)">Superman</a> in 4 bit colors. </p>
<p><img class="alignnone" title="Atari 2600" src="http://img183.imageshack.us/img183/2047/videogameatari2600xx5.jpg" alt="" width="320" height="238" /></p>
<p>It had a unique side scrolling environment where you could fly around different sets of areas connected in a circular loop (think circular array) so we could return to the first place after flying a set places (if I remember correctly). Telephone booths were strategically placed so we could change back to Clark Kent. The only thing I loved in that game was flying and flying all the time (Heroin Hero?).  </p>
<p>Three years later, my Dad bought home a 486. (there were better home machines available at that time in India but that was the best we could afford) It had a Monochrome monitor and a pirated copy of Windows 3.1 installed. There was this game I somehow managed to find in a floppy disk that came in with some IT magazine, I wasn&#8217;t really adept at Software Management and the Principles of Operating Systems, so my brother installed it for me and it popped up a gleeming splash screen saying &#8216;<a href="http://en.wikipedia.org/wiki/Chip's_Challenge">Chip&#8217;s Challenge</a>&#8216;.</p>
<p><img class="alignnone" title="Chips Challenge" src="http://img183.imageshack.us/img183/5215/chips4es6.gif" alt="" width="240" height="320" /></p>
<p>It remained my favourite game for quite a long time until it was impossible for me to get par a particular level (I always knew I wasn&#8217;t the best for the BitBuster club). It had that weird environment which hurted your eyes a little whenever you moved Chip around the pre-defined blocks, it isn&#8217;t annoying it is actually pretty engrossing to have your eyes glued to the screen that way.</p>
<p>Then came the 16bit Sega Mega Drive console, which was surely not a fake. And then there was <a href="http://en.wikipedia.org/wiki/James_Bond_007:_The_Duel">James Bond</a>. Another unique game with a fast gameplay merely because of the action filled background music and sound effects so quick that you&#8217;d probably laugh out while playing.</p>
<p><img class="alignnone" title="James Bond : The Duel" src="http://img183.imageshack.us/img183/2213/gamefabriquejamesbondthet3.jpg" alt="" width="350" height="262" /></p>
<p>These are probably the most uncommon and influencial games I&#8217;ve ever played and loved. Try them, if you ever find yourself stumbling upon old emulators or consoles.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/scoar/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I need Books that I can&#8217;t Buy, I drink Beer that I can&#8217;t Sip</title>
		<link>http://code.scrapcrap.org/books-beer</link>
		<comments>http://code.scrapcrap.org/books-beer#comments</comments>
		<pubDate>Sat, 24 Jan 2009 18:03:55 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Lame]]></category>
		<category><![CDATA[Beer]]></category>
		<category><![CDATA[CBSE]]></category>
		<category><![CDATA[E-Books]]></category>
		<category><![CDATA[India]]></category>
		<category><![CDATA[Let Us C]]></category>
		<category><![CDATA[LISP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sumita Arora]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=129</guid>
		<description><![CDATA[Probably, the most frustrating thing a programming hobbyist in India could find is the lack of availability of programming books. 
Most of the Universities and Schools here in India prescribe books written by Indian authors. It&#8217;s not that I&#8217;m against them in anyway, it&#8217;s just that there are better books around. 
Computer Science courses in High schools [...]]]></description>
			<content:encoded><![CDATA[<p>Probably, the most frustrating thing a programming hobbyist in India could find is the lack of availability of programming books. </p>
<p>Most of the Universities and Schools here in India prescribe books written by Indian authors. It&#8217;s not that I&#8217;m against them in anyway, it&#8217;s just that there are better books around. </p>
<p>Computer Science courses in High schools here have C++ as the programming language. <a href="http://books4u.in/book_detail.php?book_id=1748">The text book</a> prescribed IMHO is absolutely not ideal to start programming. This is a two part book which covers the language and a lot of theory on programming in general (which is amazingly crappy), networking and database management (and SQL) and not to forget the worst implementations of Data Structures ever.</p>
<p>Most of the colleges here have C as the primary programming language in the Introduction to Programming lectures (it&#8217;s stupid starting off programming with an incomplete version of C++ and then &#8216;going back&#8217; to C) and most too prescribe <em><a href="http://www.amazon.com/Let-Us-C-Yashavant-Kanetkar/dp/8176566217">Let Us </a></em><a href="http://www.amazon.com/Let-Us-C-Yashavant-Kanetkar/dp/8176566217">C</a> by Yashvant Kanetkar. It&#8217;s a way better book than the one by Sumita Arora.</p>
<p>But the most appalling thing I find in these books is the fake-ish ideology of programming they present. Someone who&#8217;s new to programming would still find things behind the scenes unclear after reading them. Random explanations for memory management, overemphasis on the smaller topics are common. Many here who know C/C++ still don&#8217;t know what&#8217;s Really going on and why they are doing it.</p>
<p>Only a few all time popular books are available like <a href="http://www.amazon.com/Introduction-Algorithms-Thomas-H-Cormen/dp/0262032937">Introduction to Algorithms</a>, due to the fact that they are prescribed by a considerable number of Universities. You&#8217;ll have a hard time searching for something that is not taught in the Computer Science courses.</p>
<p>I have a growing interest in the LISP language and the only book I could find here was <em><a href="http://www.amazon.com/gp/product/0201083191/ref=dp_proddesc_1?ie=UTF8&amp;n=283155">LISP </a> (CLOS, but not ANSI) </em>and that too only a single copy by accident. You won&#8217;t even find a trace for any of the other Functional Languages.</p>
<p>It&#8217;s a good thing that I can see a few Ruby titles around but I&#8217;m pretty sure that you can literally count the copies in the distributor&#8217;s warehouse in an hour.<br />
Although there are a lot of good free e-books around, it&#8217;s really difficult reading them, I can barely read a whole chapter (Wish I had a Kindle). </p>
<p>I made an <a href="https://www.amazon.com/gp/registry/wishlist/29MR2ARHJSCO9">Amazon Wish List</a> mostly containing titles not available here. Hope someone grants it!</p>
<p>It&#8217;s all messed up here, all the weird laws, systems, you can&#8217;t even drink a can of Beer properly after a hard unsuccessful day of searching programming books in the whole city because you are not 25 yet, although finding kids smoking <a href="http://en.wikipedia.org/wiki/Bhang"><em>Bhang</em></a> in corners. It&#8217;s perfectly legal.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/books-beer/feed</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Superpower India</title>
		<link>http://code.scrapcrap.org/it-boom</link>
		<comments>http://code.scrapcrap.org/it-boom#comments</comments>
		<pubDate>Tue, 20 Jan 2009 15:19:08 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Lame]]></category>
		<category><![CDATA[Colleges]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[India]]></category>
		<category><![CDATA[IT]]></category>
		<category><![CDATA[Life]]></category>
		<category><![CDATA[Superpower]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=116</guid>
		<description><![CDATA[This isn&#8217;t really it. It&#8217;s not just the professors who are inept with basic computer science knowledge.
The  Students who cleared exams for entering into the top Computer Science courses, they are actually the ones to laugh about.
Here&#8217;s a list of things I&#8217;ve heard from supposedly Intelligent kids :

&#8230; Hey! You know what? You can type [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.uncool.in/2009/01/19/computer-science-fail-higher-education-in-india/">This</a> isn&#8217;t really it. It&#8217;s not just the professors who are inept with basic computer science knowledge.</p>
<p>The  Students who cleared exams for entering into the top Computer Science courses, they are actually the ones to laugh about.</p>
<p>Here&#8217;s a list of things I&#8217;ve heard from supposedly Intelligent kids :</p>
<ul>
<li><em>&#8230; Hey! You know what? You can type your C code in notepad and then save it as .C and then run it in C++. (By C++ he meant the Borland C++ compiler)</em></li>
<li><em>From what Institute can I learn Hacking? I need to hack a website.</em></li>
<li><em>A : There&#8217;s an examination next week on C programming, have     you prepared?</em></li>
<li><em>B : Bah! I know the whole C, I&#8217;ve executed all the     code the professor gave us.</em></li>
<li><em>(me asking B) Why did you take up Software Engg. ?</em></li>
<li><em>(his reply) IT has a wide scope in India. </em></li>
<li><em>(asking me for a copy of the Borland IDE) Do you have TC? (I don&#8217;t know why they think that the blue screen in that cranky old Borland editor is THE programming language)</em></li>
<li><em>(while writing HTML in notepad) How do you insert the anchor tag for hyperlinks?</em></li>
<li><em>(reply) Look it up in the notepad Help Topics. </em></li>
</ul>
<p>Thankfully, my professors are a little better than <a href="http://blog.uncool.in/">Uncool&#8217;s</a>.  Although a few classics I&#8217;ve probably heard more than twice :</p>
<ul>
<li><em>&#8230; Oracle and SQL are the same things (before repeatedly pronouncing SQL as &#8216;Sequel&#8217;)</em></li>
<li><em>In the practical world, Linux is not used anymore.</em></li>
<li><em>It took me 5 years to understand the difference between Multitasking and Multiprogramming </em></li>
</ul>
<p>It&#8217;s not that I&#8217;m in the worst college, it&#8217;s just that people around me don&#8217;t seem to care about the stuff they learn in college, not even the things that are directly related to the course, their main objective is to score marks in exams and get jobs with lots of money.</p>
<p>Invariably, there are always talks on India being an IT superpower. An IT Superpower whose university&#8217;s conduct the so called &#8216;IT Quizzes&#8217; filled in with questions from Database management (Well, TCS is an exception) and those random kids giving me weird looks when I read Ruby books in the library or talk about Dynamic Programing and LISP.</p>
<p><em></em></p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/it-boom/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Implementing a Chat Server in Ruby</title>
		<link>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby</link>
		<comments>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby#comments</comments>
		<pubDate>Tue, 13 Jan 2009 19:26:17 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Howto]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Chat Server]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Sockets]]></category>
		<category><![CDATA[TCP]]></category>
		<category><![CDATA[Thin]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=87</guid>
		<description><![CDATA[Me and Uncool participated in a &#8216;Linux Challenge&#8217; recently in one of the IT Fest of the University of Delhi.
Although we just managed a Third Prize by some Python heroics in the end by Uncool, we were behind the First team only by a single problem of implementing a chat program using Unix Pipes. We [...]]]></description>
			<content:encoded><![CDATA[<p>Me and <a href="http://uncool.in/">Uncool</a> participated in a &#8216;Linux Challenge&#8217; recently in one of the IT Fest of the <a href="http://en.wikipedia.org/wiki/Nsit">University of Delhi</a>.<br />
Although we just managed a Third Prize by some Python heroics in the end by Uncool, we were behind the First team only by a single problem of implementing a chat program using Unix Pipes. We had little clue about UNIX Pipes so we thought about implementing it by using standard libraries from either Ruby or Python, as they (event organizers) said they would still consider it. Expectedly, they didn&#8217;t have any trace of Ruby on their machines which were running Fedora 9.<br />
Uncool was unsuccessful in implementing it in Python, the documentation was ugly enough.<br />
Reasonably angry, I decided to prove myself why we could have at least won the Second prize without even a drop of sweat.</p>
<p>TCPSocket and TCPServer classes in the Ruby Standard Library are braindead-simple to implement.<br />
<a href="http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177">The Ruby Programming Language</a> shows how (comments are self-explanatory) :</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code10'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8710"><td class="code" id="p87code10"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># A Multithreaded Server</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'socket'</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># This method expects a socket connected to a client.</span>
<span style="color:#008000; font-style:italic;"># It reads lines from the client, reverses them and sends them back.</span>
<span style="color:#008000; font-style:italic;"># Multiple threads may run this method at the same time.</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> handle_client<span style="color:#006600; font-weight:bold;">&#40;</span>c<span style="color:#006600; font-weight:bold;">&#41;</span>
 <span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#0000FF; font-weight:bold;">true</span>
   input = c.<span style="color:#CC0066; font-weight:bold;">gets</span>.<span style="color:#CC0066; font-weight:bold;">chop</span>                 <span style="color:#008000; font-style:italic;"># Read a line of input from the client</span>
   <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> !input                     <span style="color:#008000; font-style:italic;"># Exit if no more input</span>
   <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> input == <span style="color:#996600;">&quot;quit&quot;</span>            <span style="color:#008000; font-style:italic;"># or if the client asks to.</span>
   c.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>input.<span style="color:#9900CC;">reverse</span><span style="color:#006600; font-weight:bold;">&#41;</span>               <span style="color:#008000; font-style:italic;"># Otherwise, respond to client.</span>
   c.<span style="color:#9900CC;">flush</span>                             <span style="color:#008000; font-style:italic;"># Force our output out</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
 c.<span style="color:#9900CC;">close</span>                               <span style="color:#008000; font-style:italic;"># Close the client socket</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
server = TCPServer.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">2000</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># Listen on port 2000</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#0000FF; font-weight:bold;">true</span>                             <span style="color:#008000; font-style:italic;"># Servers loop forever</span>
 client = server.<span style="color:#9900CC;">accept</span>                <span style="color:#008000; font-style:italic;"># Wait for a client to connect</span>
 <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">start</span><span style="color:#006600; font-weight:bold;">&#40;</span>client<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>c<span style="color:#006600; font-weight:bold;">|</span>           <span style="color:#008000; font-style:italic;"># Start a new thread</span>
   handle_client<span style="color:#006600; font-weight:bold;">&#40;</span>c<span style="color:#006600; font-weight:bold;">&#41;</span>                    <span style="color:#008000; font-style:italic;"># And handle the client on that thread</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p><a href="http://ruby-doc.org/stdlib/libdoc/gserver/rdoc/classes/GServer.html#M000820">Gserver</a>, one of the better standard libraries in Ruby.</p>
<p>More flexible than the socket library, it can be used to implement application level servers, it has a few useful predefined methods like the number of connections, event logging and handles all threading problems by itself, that means multiple users can connect on a single server at once (Asynchronous Socket programming -  which is, where many clients connect to a single server and send input for processing concurrently, the server then handles all the connected clients asynchronously and process the data as and whenever it is available from any of them.)</p>
<p>This little toy Chat Program reads a single input from the client, <a href="http://code.scrapcrap.org/?p=44">shuffles</a> it and sends it back.</p>
<p><strong>CLIENT</strong></p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code11'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8711"><td class="code" id="p87code11"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'socket'</span>                           <span style="color:#008000; font-style:italic;"># Sockets are in standard library</span>
&nbsp;
sock = TCPSocket.<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;localhost&quot;</span>,<span style="color:#006666;">1234</span><span style="color:#006600; font-weight:bold;">&#41;</span>    <span style="color:#008000; font-style:italic;"># Socket to listen on port 1234</span>
&nbsp;
  l = STDIN.<span style="color:#CC0066; font-weight:bold;">gets</span>                           <span style="color:#008000; font-style:italic;"># Get a single input from console</span>
  sock.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>l<span style="color:#006600; font-weight:bold;">&#41;</span>                             <span style="color:#008000; font-style:italic;"># Send input to the server</span>
  sock.<span style="color:#9900CC;">flush</span>                               <span style="color:#008000; font-style:italic;"># Force input</span>
  line = sock.<span style="color:#9900CC;">readpartial</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4096</span><span style="color:#006600; font-weight:bold;">&#41;</span>            <span style="color:#008000; font-style:italic;"># Read server's response</span>
  <span style="color:#CC0066; font-weight:bold;">puts</span> line                                <span style="color:#008000; font-style:italic;"># Display the response to the user</span>
&nbsp;
sock.<span style="color:#9900CC;">close</span>                                 <span style="color:#008000; font-style:italic;"># Close the socket</span></pre></td></tr></table></div>

<p><strong>SERVER</strong></p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p87code12'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p8712"><td class="code" id="p87code12"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'gserver'</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Algorithm to shuffle a string</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> shuffle<span style="color:#006600; font-weight:bold;">&#40;</span>str<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
lenth = str.<span style="color:#9900CC;">length</span>
&nbsp;
index = <span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">while</span><span style="color:#006600; font-weight:bold;">&#40;</span>index <span style="color:#006600; font-weight:bold;">&amp;</span>gt;= <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
   random_number = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
   str<span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>, str<span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span> = str<span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span>, str<span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
   index = index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
str
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> Server <span style="color:#006600; font-weight:bold;">&amp;</span>lt; GServer                  <span style="color:#008000; font-style:italic;"># Server class derived from GServer super class</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>port=<span style="color:#006666;">1234</span>, <span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span>      <span style="color:#008000; font-style:italic;"># to use the initialize function</span>
      <span style="color:#9966CC; font-weight:bold;">super</span><span style="color:#006600; font-weight:bold;">&#40;</span>port, <span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> serve<span style="color:#006600; font-weight:bold;">&#40;</span>io<span style="color:#006600; font-weight:bold;">&#41;</span>                         <span style="color:#008000; font-style:italic;"># Serve method handles connections</span>
&nbsp;
      input = io.<span style="color:#CC0066; font-weight:bold;">gets</span>.<span style="color:#CC0066; font-weight:bold;">chop!</span>             <span style="color:#008000; font-style:italic;"># Get input from client console</span>
      io.<span style="color:#CC0066; font-weight:bold;">puts</span><span style="color:#006600; font-weight:bold;">&#40;</span>shuffle<span style="color:#006600; font-weight:bold;">&#40;</span>input<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>           <span style="color:#008000; font-style:italic;"># Return the shuffled input onto the client console</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> input                        <span style="color:#008000; font-style:italic;"># Print the client message </span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
server = Server.<span style="color:#9900CC;">new</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span> <span style="color:#006600; font-weight:bold;">&#40;</span>input = <span style="color:#CC0066; font-weight:bold;">gets</span><span style="color:#006600; font-weight:bold;">&#41;</span>                     <span style="color:#008000; font-style:italic;"># Loop server while user gives an input</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">if</span> input =~ <span style="color:#006600; font-weight:bold;">/</span>start<span style="color:#006600; font-weight:bold;">/</span>
   server.<span style="color:#9900CC;">start</span>                          <span style="color:#008000; font-style:italic;"># Start the server if the user types &quot;init&quot;</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">if</span> input =~ <span style="color:#006600; font-weight:bold;">/</span>shutdown<span style="color:#006600; font-weight:bold;">/</span>
   server.<span style="color:#9900CC;">shutdown</span>                       <span style="color:#008000; font-style:italic;"># Shut the server down if the user types &quot;shutdown&quot;</span>
&nbsp;
 <span style="color:#9966CC; font-weight:bold;">break</span>
 <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p><a href="http://code.macournoyer.com/thin/">Thin</a> provides a <a href="http://code.macournoyer.com/thin/doc/classes/Thin/Backends/TcpServer.html">TCPServer</a> Socket backend which can also be used for similar purposes. Its pretty much the same except that it uses the <a href="http://rubyeventmachine.com/">EventMachine</a> library for the Network I/O.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/implementing-a-chat-server-in-ruby/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Shuffling</title>
		<link>http://code.scrapcrap.org/shuffling</link>
		<comments>http://code.scrapcrap.org/shuffling#comments</comments>
		<pubDate>Sun, 11 Jan 2009 18:05:37 +0000</pubDate>
		<dc:creator>kitallis</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Fisher-Yates]]></category>
		<category><![CDATA[GUID]]></category>
		<category><![CDATA[Knuth]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Shuffle]]></category>

		<guid isPermaLink="false">http://code.scrapcrap.org/?p=44</guid>
		<description><![CDATA[
I was recently going through a set of commonly asked interview questions and I came across a problem requiring to shuffle a deck of 52 cards in random order. Initially, I found The Knuth or The Fisher Yates shuffle the easiest algorithm to implement.
The Knuth Shuffle makes use of a certain set  of random numbers for [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><img class="alignnone size-full wp-image-68" title="Set_0f_Cards" src="http://code.scrapcrap.org/wp-content/uploads/2009/01/cards01.jpg" alt="Set_0f_Cards" width="369" height="155" /></p>
<p style="text-align: left;">I was recently going through a set of commonly asked interview questions and I came across a problem requiring to shuffle a deck of 52 cards in random order. Initially, I found <a href="http://en.wikipedia.org/wiki/Knuth_shuffle">The Knuth or The Fisher Yates shuffle</a> the easiest algorithm to implement.</p>
<p style="text-align: left;">The Knuth Shuffle makes use of a certain set  of random numbers for creating randomness. Implementing it as Code, obviously required me to make use of the rand() function.</p>
<p style="text-align: left;">Here&#8217;s the actual description of the algorithm from The Art of Computer Programming, Volume 2: Seminumerical Algorithms, page:145. Third Edition. D.E. Knuth</p>
<blockquote><p>Let X1, X2, …, Xt be a set of t numbers to be shuffed.</p>
<p>P1. [Initialize.] Set j ← t.<br />
P2. [Generate U.] Generate a random number U, uniformly distributed between zero and one.<br />
P3. [Exchange.] Set k ← [jU] + 1. (Now k is a random integer, between 1 and j. Exchange Xk and Xj.<br />
P4. [Decrease j.] Decrease j by 1. If j &gt; 1, return to step P2.</p></blockquote>
<p>I used my favourite language Ruby to write the code and came up with this :</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p44code15'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4415"><td class="code" id="p44code15"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">array</span> = <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span>..52<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">to_a</span>
&nbsp;
lenth = <span style="color:#CC0066; font-weight:bold;">array</span>.<span style="color:#9900CC;">length</span>
&nbsp;
index = <span style="color:#006600; font-weight:bold;">&#40;</span>lenth<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">while</span><span style="color:#006600; font-weight:bold;">&#40;</span>index <span style="color:#006600; font-weight:bold;">&amp;</span>gt;= <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
  random_number = <span style="color:#CC0066; font-weight:bold;">rand</span><span style="color:#006600; font-weight:bold;">&#40;</span>index<span style="color:#006600; font-weight:bold;">+</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>index<span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>random_number<span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
  index = index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#CC0066; font-weight:bold;">array</span></pre></td></tr></table></div>

<p>One of the problem I found was the use of the rand() function.<br />
The use of a randomize function in real life situation is not ideal, say, in a game of Poker(online). One can easily sync the time of our clock to that of the server, If the randomize function is seeded with the number of milliseconds from the system clock as was in the case of the ASF Software&#8217;s Poker product.</p>
<p>A Modulus operator is used for restricting the numbers in a particular range. Like in the GNU C Library&#8217;s (GlibC) <a href="http://www.google.com/codesearch/p?hl=en#WbTnQ5DcqbM/glibc-2.1.3/string/strfry.c&amp;q=strfry">strfry()</a> which can be used for randomizing strings. </p>
<p>From Wikipedia :</p>
<blockquote><p>Doing a Fisher-Yates shuffle involves picking uniformly distributed random integers from various ranges. Most random number generators, however—whether true or pseudorandom—will only directly provide numbers in some fixed range, such as, say, from 0 to 232−1. A simple and commonly used way to force such numbers into a desired smaller range is to apply the modulo operator; that is, to divide them by the size of the range and take the remainder. However, the need, in a Fisher-Yates shuffle, to generate random numbers in every range from 0–1 to 0–N pretty much guarantees that some of these ranges will not evenly divide the natural range of the random number generator. Thus, the remainders will not always be evenly distributed and, worse yet, the bias will be systematically in favor of small remainders.</p></blockquote>
<p>Googling around turned out that sorting it by using <a href="http://en.wikipedia.org/wiki/UUID">UUID&#8217;s</a> as a source of random numbers was more easier to implement.<br />
Ruby offers a <a href="http://raa.ruby-lang.org/project/ruby-guid/">library</a> for generating UUID&#8217;s which uses /dev/urandom on *nix types systems to generate random numbers.<br />
A GUID can be created by these two lines.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p44code16'); return false;">View Code</a> RUBY</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p4416"><td class="code" id="p44code16"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'guid'</span> 
&nbsp;
g2 = Guid.<span style="color:#9900CC;">new</span>  <span style="color:#008000; font-style:italic;">#a unique GUID every time</span></pre></td></tr></table></div>

<p>It&#8217;s typically not faster, as sorting would be O(n log n) compared to the O(n) (linear time) for the Knuth Shuffle.</p>
<p><a href="http://mathworld.wolfram.com/Shuffle.html">Wolfram MathWorld</a> has a few mathematical shuffling algorithms and randomization techniques for further mathematical reference.</p>
]]></content:encoded>
			<wfw:commentRss>http://code.scrapcrap.org/shuffling/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
