Internet Relay Story – I

0
Categories: IRC, Lame
Posted on: 7th February 2010 by: kitallis
EVENTS OCCUR IN REAL-TIME.

09:56 [Users #kit-room]
09:56 [@ChanServ] [ kitalis_] [ kitallis]
09:56 --> #kit-room: Total of 2 nicks (1 ops, 0 halfops, 0 voices, 1 normal)
09:57 --> 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 : <_<
10:17  ! kitallis drops the empty can in his hands
10:18         ChanServ : *DHUGH DHUG.
10:18         kitallis : ...
10:18         kitallis : ...
10:18             sid0 : <_<
10:18         kitallis : ...
10:19             sid0 : <_<
10:19         kitallis : ...
10:19  ! kitallis quietly goes around him and leaves the room
10:20         kitallis : ...
10:19             sid0 : <_<
10:19         kitallis : ...
10:19             sid0 : @_@
10:19         kitallis : ...
10:20             sid0 : >_>
10:20 --> 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 --> #m1k3y-room: Total of 2 nicks (1 ops, 0 halfops, 0 voices, 1 normal)
10:29 --> 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 : >_>
10:40  ! kitallis wiggles his head
10:40         ChanServ : *DHUGH DHUG CHAGHK* ; *DHUGH DHUG CHAGHK*
10:41             sid0 : >_>
10:41         kitallis : ...
10:41             sid0 : >_>
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 : >_>
10:43  ! kitallis storms out of the room
10:43            m1k3y : kitallis: wut happened?
10:43 --> 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 : <_<

Obligatory blog post. An intended mockery on the deeds of the great sid0. He’s watching.

Design Patterns in Ruby : The Factory Method

2
Categories: Design Patterns
Posted on: 26th April 2009 by: kitallis

This is an article series on implementing programming Design Patterns in Ruby. This is the second part of the series and here’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 Pattern, so I’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.

What is it?

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.

When is it needed?

It’s all about picking the right class. It’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’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.

How is it done?

Here’s my dummy implementation for the Factory Method pattern.

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

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 – CallShapes for creating objects out of them to be selected as per the user call.

This pattern is used when a class (theCreator) does not know beforehand all the subclasses that it will create. Instead, each subclass (the Concrete Creator) is left with the responsibility of creating the actual object instances.
The example shown here is specifically a Parametrized Factory Method, that takes in certain parameters from the user and creates objects accordingly.

Abstract Factory Method can pretty much be understood by this UML diagram

Factory Method UML

(Courtesy : Design patterns in Ruby )

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’s pretty much what Abstract Factory Methods are.

Taking an example from the Book, the ActiveRecord library uses a form of this kind of pattern.
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 ‘mysql’ 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.
But there are Subclasses that modifying the Base code, that is, each adapter adds a method that creates its specific type of connection to
the Base class.

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

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.

References

[1] Wikipedia

[2] Programmers Heaven

Design Patterns in Ruby : The Template Method

4
Categories: Design Patterns
Posted on: 8th March 2009 by: kitallis

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’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 would cover a few of the popular programming Design Patterns in software engineering devised by the GoF. I would be starting off with some basic Design Patterns and then move onto Ruby specific patterns based upon the book “Design Patterns In Ruby” by Russ Olsen.

The Design Patterns that’ll be explained are :

1. The Template Method (explained here)
2. The Factory Method

(They will be updated as the series expands)
You can Subscribe to my Blog Feeds for constant updates on the articles or you can follow me on www.twitter.com/kitallis
This is the base article for the series and you can always look back at this as an archive for others.

Prerequisites would be, a knowledge of Ruby’s Object Oriented features and a belief that this would actually help you get better.
These articles would follow a simple pattern of explaining the design pattern, disadvantages without it and improving with it. If you don’t quite get what I’m talking about, you might want to take a look at this.

The Template Method Pattern

When is it needed?
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.
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).

How can we do it?
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.
More specifically, building an abstract base class with a skeletal method (template method) that’d control the part that needs to vary by making calls to the Abstract Method whose actual control is further provided by the subclasses.
Even more strictly, this is an actual application of the Template Method Pattern in the ControlTier project which defines an application installation procedure
(other details are unnecessary here)

(Courtesy : ControlTier Wiki)

The Template Methods residing in the Abstract class are ‘driving’ 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.

So, the quick advantages we get are :

1. We can expand to more subclasses even if they require a varying algorithm for the methods defined

2. The algorithm is separated from the static definitions and initialisations

This is my dummy code for the pattern

class Package  # this is the abstract base class
 
  def initialize
  #
  end
 
  def InstallPackage  # this is the template method
 
  create
  installDependencies
  prepare
  get
  extract
  finish
 
  end
 
  def installDependencies
  #
  end
 
  def prepare
  #
  end
 
  def get
  #
  end
 
  def extract
  #
  end
 
  def finish
  #
  end
 
  end
 
class Zip &lt; Package  # this is the concrete subclass
 
  def create
  #
  end
 
  def extract
  #
  end
 
end

And it might be called this way

z = Zip.new
 
z.InstallPackage # calling the template method from the subclass

GOF describes a Hook Method
These are basically just virtual methods which may or may not have code inside them in base classes.
They are a way of telling the concrete subclasses that “either use the default implementation in the abstract class or override it for some varying algorithm and do something different”

Implementations without this pattern could be

class Package
 
  def initialize
  end
 
  def get_method(type)
  end 
 
  if type == "Zip" 
 
  # create algorithm
  # extract algorithm
 
  elsif #some other type
 
  end
 
end

which could be amazingly hard to expand for large pieces of code.
I’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.

Scoar!

2
Categories: Games, Other
Posted on: 16th February 2009 by: kitallis

My first encounter with anything called a ‘Video Game’ was with a Macintosh and a MacPlay CD-ROM of  ”Putt Putt and Fatty Bear’s Activity Pack“.

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’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)

Then there was Spaceship Warlock, a dark game with a really scary title music piece (really, it’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. Here’s a video.

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 Superman in 4 bit colors. 

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?).  

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’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 ‘Chip’s Challenge‘.

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’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’t annoying it is actually pretty engrossing to have your eyes glued to the screen that way.

Then came the 16bit Sega Mega Drive console, which was surely not a fake. And then there was James Bond. Another unique game with a fast gameplay merely because of the action filled background music and sound effects so quick that you’d probably laugh out while playing.

These are probably the most uncommon and influencial games I’ve ever played and loved. Try them, if you ever find yourself stumbling upon old emulators or consoles.

I need Books that I can’t Buy, I drink Beer that I can’t Sip

Categories: Lame
Posted on: 24th January 2009 by: kitallis

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’s not that I’m against them in anyway, it’s just that there are better books around. 

Computer Science courses in High schools here have C++ as the programming language. The text book 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.

Most of the colleges here have C as the primary programming language in the Introduction to Programming lectures (it’s stupid starting off programming with an incomplete version of C++ and then ‘going back’ to C) and most too prescribe Let Us C by Yashvant Kanetkar. It’s a way better book than the one by Sumita Arora.

But the most appalling thing I find in these books is the fake-ish ideology of programming they present. Someone who’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’t know what’s Really going on and why they are doing it.

Only a few all time popular books are available like Introduction to Algorithms, due to the fact that they are prescribed by a considerable number of Universities. You’ll have a hard time searching for something that is not taught in the Computer Science courses.

I have a growing interest in the LISP language and the only book I could find here was LISP  (CLOS, but not ANSI) and that too only a single copy by accident. You won’t even find a trace for any of the other Functional Languages.

It’s a good thing that I can see a few Ruby titles around but I’m pretty sure that you can literally count the copies in the distributor’s warehouse in an hour.
Although there are a lot of good free e-books around, it’s really difficult reading them, I can barely read a whole chapter (Wish I had a Kindle).

I made an Amazon Wish List mostly containing titles not available here. Hope someone grants it!

It’s all messed up here, all the weird laws, systems, you can’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 Bhang in corners. It’s perfectly legal.

Superpower India

Categories: Lame
Posted on: 20th January 2009 by: kitallis

This isn’t really it. It’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’s a list of things I’ve heard from supposedly Intelligent kids :

  • … 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)
  • From what Institute can I learn Hacking? I need to hack a website.
  • A : There’s an examination next week on C programming, have you prepared?
  • B : Bah! I know the whole C, I’ve executed all the code the professor gave us.
  • (me asking B) Why did you take up Software Engg. ?
  • (his reply) IT has a wide scope in India. 
  • (asking me for a copy of the Borland IDE) Do you have TC? (I don’t know why they think that the blue screen in that cranky old Borland editor is THE programming language)
  • (while writing HTML in notepad) How do you insert the anchor tag for hyperlinks?
  • (reply) Look it up in the notepad Help Topics. 

Thankfully, my professors are a little better than Uncool’s.  Although a few classics I’ve probably heard more than twice :

  • … Oracle and SQL are the same things (before repeatedly pronouncing SQL as ‘Sequel’)
  • In the practical world, Linux is not used anymore.
  • It took me 5 years to understand the difference between Multitasking and Multiprogramming

It’s not that I’m in the worst college, it’s just that people around me don’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.

Invariably, there are always talks on India being an IT superpower. An IT Superpower whose university’s conduct the so called ‘IT Quizzes’ 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.

Implementing a Chat Server in Ruby

5
Categories: Howto, Programming
Posted on: 13th January 2009 by: kitallis

Me and Uncool participated in a ‘Linux Challenge’ 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 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’t have any trace of Ruby on their machines which were running Fedora 9.
Uncool was unsuccessful in implementing it in Python, the documentation was ugly enough.
Reasonably angry, I decided to prove myself why we could have at least won the Second prize without even a drop of sweat.

TCPSocket and TCPServer classes in the Ruby Standard Library are braindead-simple to implement.
The Ruby Programming Language shows how (comments are self-explanatory) :

# A Multithreaded Server
 
require 'socket'
 
# This method expects a socket connected to a client.
# It reads lines from the client, reverses them and sends them back.
# Multiple threads may run this method at the same time.
 
def handle_client(c)
 while true
   input = c.gets.chop                 # Read a line of input from the client
   break if !input                     # Exit if no more input
   break if input == "quit"            # or if the client asks to.
   c.puts(input.reverse)               # Otherwise, respond to client.
   c.flush                             # Force our output out
 end
 c.close                               # Close the client socket
end
 
server = TCPServer.open(2000) # Listen on port 2000
 
while true                             # Servers loop forever
 client = server.accept                # Wait for a client to connect
 Thread.start(client) do |c|           # Start a new thread
   handle_client(c)                    # And handle the client on that thread
 end
end

Gserver, one of the better standard libraries in Ruby.

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.)

This little toy Chat Program reads a single input from the client, shuffles it and sends it back.

CLIENT

require 'socket'                           # Sockets are in standard library
 
sock = TCPSocket.open("localhost",1234)    # Socket to listen on port 1234
 
  l = STDIN.gets                           # Get a single input from console
  sock.puts(l)                             # Send input to the server
  sock.flush                               # Force input
  line = sock.readpartial(4096)            # Read server's response
  puts line                                # Display the response to the user
 
sock.close                                 # Close the socket

SERVER

require 'gserver'
 
# Algorithm to shuffle a string
 
def shuffle(str)
 
lenth = str.length
 
index = (lenth-1)
 
  while(index &gt;= 0) do
 
   random_number = rand(lenth)
 
   str[random_number], str[index] = str[index], str[random_number]
 
   index = index - 1
 
  end
 
str
end
 
class Server &lt; GServer                  # Server class derived from GServer super class
  def initialize(port=1234, *args)      # to use the initialize function
      super(port, *args)
  end
 
  def serve(io)                         # Serve method handles connections
 
      input = io.gets.chop!             # Get input from client console
      io.puts(shuffle(input))           # Return the shuffled input onto the client console
      puts input                        # Print the client message 
 
  end
 
end
 
server = Server.new
 
while (input = gets)                     # Loop server while user gives an input
 
 if input =~ /start/
   server.start                          # Start the server if the user types "init"
 
 end
 
 if input =~ /shutdown/
   server.shutdown                       # Shut the server down if the user types "shutdown"
 
 break
 end
 
end

Thin provides a TCPServer Socket backend which can also be used for similar purposes. Its pretty much the same except that it uses the EventMachine library for the Network I/O.

Shuffling

6
Categories: Algorithms
Posted on: 11th January 2009 by: kitallis

Set_0f_Cards

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 creating randomness. Implementing it as Code, obviously required me to make use of the rand() function.

Here’s the actual description of the algorithm from The Art of Computer Programming, Volume 2: Seminumerical Algorithms, page:145. Third Edition. D.E. Knuth

Let X1, X2, …, Xt be a set of t numbers to be shuffed.

P1. [Initialize.] Set j ← t.
P2. [Generate U.] Generate a random number U, uniformly distributed between zero and one.
P3. [Exchange.] Set k ← [jU] + 1. (Now k is a random integer, between 1 and j. Exchange Xk and Xj.
P4. [Decrease j.] Decrease j by 1. If j > 1, return to step P2.

I used my favourite language Ruby to write the code and came up with this :

array = (1..52).to_a
 
lenth = array.length
 
index = (lenth-1)
 
while(index &gt;= 0) do
 
  random_number = rand(index+1)
 
  array[random_number], array[index] = array[index], array[random_number]
 
  index = index - 1
 
end
 
puts array

One of the problem I found was the use of the rand() function.
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’s Poker product.

A Modulus operator is used for restricting the numbers in a particular range. Like in the GNU C Library’s (GlibC) strfry() which can be used for randomizing strings. 

From Wikipedia :

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.

Googling around turned out that sorting it by using UUID’s as a source of random numbers was more easier to implement.
Ruby offers a library for generating UUID’s which uses /dev/urandom on *nix types systems to generate random numbers.
A GUID can be created by these two lines.

require 'guid' 
 
g2 = Guid.new  #a unique GUID every time

It’s typically not faster, as sorting would be O(n log n) compared to the O(n) (linear time) for the Knuth Shuffle.

Wolfram MathWorld has a few mathematical shuffling algorithms and randomization techniques for further mathematical reference.