Friday, April 16, 2004

Yesterday Sajith mailed me a this. It is a flash version of the old Prince of Persia game - ver 1.0.
Try it, its fun.

Which reminded me of the version I had done:
http://www.thinkingms.com/pensieve/homepage/old_work/prince_of_persia.htm

There were a couple of neat things my Price did such as have steps, complex net like patterns that the prince could run behind (the original prince could never be covered by any complex surface). I have a couple of screenshots to prove my point.

 

Friday, April 16, 2004 4:54:16 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

In the past article Iterators in Ruby (Part - 1) I talked about the concept of iterators and how iterators are available in Ruby. In this part I will dwell on how iterators are used, so that the concept grows on you.

 

For someone used to the C/C++ world, the constructs provided by those languages suffice to express any idea of their choosing. While that is true, programming in a C-like language causes us to close our minds to other styles of programming and other constructs that might exist. Programming in C after a point is about writing the next big program optimized with lots of data-structure usage and trying to tie a new algorithm down into C. Sometimes the joy of programming, where the language lets you do your job - express ideas as code, is lost. Sometimes we spend our time servicing our language syntax and spoon-feeding our compilers. The fact that languages might actually evolve so that you can get on with your job, was alien for a long time to me.

 

If you have read the first part you might be wondering how iterators are used in Ruby. Admittedly, the idea would seem a little complex and maybe contrived to the uninitiated.

 

In Ruby, iterators are used pervasively. Its there all over the place and once you get started on Ruby, you will probably end up using an iterator without realizing that you are using one. The Ruby libraries are rich with iterators of various sorts.

 

Simple Loops

When you start of on Ruby code, you might see loops of the sort:

 

10.times {

      print “hello world”

}

 

This, as you might expect, prints ‘hello world’ 10 times.

 

How does this work? Ruby is a pure object oriented language. The number 10 is an integer, and the integer class exposes a method called ‘times’. The times method is an iterators that yields values from 0 to its value -1.

 

Since it yields values, can we catch them ? Yes.

 

10.times {|n|

      print n

}

 

And this prints all the values from 0 to n-1.
'times' is an iterator.

 

File Handling

Let’s look at some file handling in Ruby. The following code will open a file and read each line of the file and print the line among with its line number.

 

file = File.new(“filename.txt”)

c = 0
file.each_line {|line|

      c = c + 1

      print “#{c}: #{line}”

}

 

The code is simple. I open a file and create a file object. I ask the object to yield each line to me. As I get each line I print it out along with the line number. This is as logically expressive as I have seen in any language that I have used. All the mess stays out of your way and you get to focus on the job at hand.

 

The each_line is a method of the File class and it yields each line in the file. The variable ‘line’ will hold the value of each line. Slick?

 

(I you are wondering what “#{c}: #{line}” means – in a string #{ } is a substitution. You can write any expression into the curly braces. Here the values of c and line get substituted into the string)

 

Arrays / Collections

Similarly collection types expose an “each” method which yields every member of the collection. So if I had to iterate over an array I would write:

 

array = [1,2,3,4]

array.each {|m| puts m }

 

The above code creates an array of 4 elements and accesses each element using the iterator “each”.

 

In similar fashion, a lot of the Ruby library exposes functionality as iterators. So much so, that I rarely write for loops in Ruby.

 

Recursive Directory Enumeration

Now let us try and write code of our own. Something you may all have written is code that will find all the text files in a folder and is sub folders. The usual approach is to write a recursive function.

 

The function will try and remember a list of text files, in the current directory and the list of sub directories it has. It will then recursively call each of the subdirectories, each of which will do the same task. The problem is that if every time a text file is to be found, some processing is to be done, things get very complicated. The usual approach is to find all the text files and create a big list of filenames, which is then processed later.

 

Here is an approach with iterators. Try and implement this in your favorite language that does not have iterators and see how it looks.

 

def textfiles(dir)

        Dir.chdir(dir)

        Dir["*"].each do |entry|

                yield dir+"\\"+entry if /^.*\.txt$/ =~ entry

                if FileTest.directory?(entry)

                        textfiles(entry){|file| yield dir+"\\"+file}

                end

        end

        Dir.chdir("..")

end

 

textfiles(“c:\\”){|file|

        puts file

}

 

What the above code does is simple. I have defined a method called textfiles() that takes a directory name as a parameter.

 

The code looks exactly like you would explain it algorithmically.

  1. Go to the folder (chdir)
  2. Take a look at the contents (Dir[“*”])
  3. See is an entry is a text file, if so yield it (yield dir+"\\"+entry if /^.*\.txt$/ =~ entry)
  4. See is an entry is a directory, if so, recurse into it
    (
    if FileTest.directory?(entry)
       textfiles(entry){|file| yield dir+"\\"+file}
    end)

 

Simple?  Notice that the beauty of code is that the yield actually sends the value of a filename down a recursive hierarchy.

 

As a disclaimer, if you are using Ruby, then you might a well finish off in one line by saying:


Dir[“**/*.txt”].each{|file| puts file }

 

 

Friday, April 16, 2004 3:28:18 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  | 

After smoothing a out a few issues that dasBlog has, this blog is now functional. dasBlog requires that the user under whose permissions ASP.Net is running was write permissions to the folders - content, logs and siteconfig. On a win 2003 box ASP.Net runs as \NETWORK SERVICE.

So what you need to do, if you are setting up dasBlog, is to allow wirte permissions to our 3 folders.

This is also fine time to roll out some links:

Channel 9
Some folk at MS have dished out Channel 9. Channel 9 is where you can see into the big borg entity of MS and maybe come away with the feeling that they are not a big borg entity at all.
http://channel9.msdn.com/

IronPython: Python is being shifted to .Net by Jim Hugunin.
He is the same person who developed Jython, the Java implementation of python. .Net has been for sometime considered a difficult platform to shift to for dynamic languages such as Python and Ruby. Ruby might be a tad bit more difficult beacuse of all the tricks it does with continuations, closures, iterators and such.

http://www.hole.fi/jajvirta/weblog/20031210T0901.html
I'd guess that anyone who reads this weblog also reads Jeremy Hylton's weblog (which is in my opinion currently perhaps the best technical Python related weblog), but I still thought it was worthwhile to mention that the great Jim Hugunin has a new project, named IronPython, which is an implementation of Python for the Microsoft Common Language Runtime environment. The remarkable thing is that IronPython runs faster than the Python implementation in C according to the pystone benchmark. (See Hugunin's original message for full details.)

Miguel de Icaza, lead developer of the Mono framework, also comments on Hugunin's remark with delight and says that this might "stop the meme of '.NET is slow for scripting languages'".

Hugunin himself is busy for the whole January, but hopes to continue the development of IronPython after that.
Written by Jarno Virtanen at 2003-12-10 09:39

Miguel De Icaza and Nat Friedman go dancing(!) with Microsoft's CTO
http://primates.ximian.com/~miguel/archive/2004/Apr-12.html
This is a must see.

Electronic Intifada
I found this on Miguel's site and I wish more people cared.
http://electronicintifada.net/new.shtml
The Electronic Intifada (EI), found at electronicIntifada.net, publishes news, commentary, analysis, and reference materials about the Israeli-Palestinian Conflict from a Palestinian perspective. EI is the leading Palestinian portal for information about the Israeli-Palestinian conflict and its depiction in the media.

The Phoenix Research and Development Kit from MSR
This is one of the things, where, I feel, the future is brewing. The Phoenix RDK is a language/compiler/runtime generation and research framework comparable in scale (with the little that I know) to the National Compiler Infrastructure (NCI) project.
The Phoenix RDK homepage: http://research.microsoft.com/phoenix/

Friday, April 16, 2004 12:02:50 AM (Eastern Standard Time, UTC-05:00)  #    Comments [3]  | 
 Thursday, April 15, 2004

Very soon I should have a blogging engine of my own up and working. I got a copy of DasBlog and with a bit of tweaking it seems to suits me rather fine. I would however like to see

·         Hierarchical comments

·         Ability to delete comments without getting into XMLs

·         Enabling description views only on certain aggregate views.

·         Where is the archives feature?

 

The blog should be going up on www.thinkingms.com, a site that is run by Pandu. The only problem is that I don’t seem to be thinking MS all the time :-)

 

Until the blog is formally up I guess you will see me manually predate entries at the end of each entry.

 

(To the tune of Jingle Bells)

blogging site blogging site

blogging all the way,

oh what fun it is to send

an entry on its way ... hey !

Apr 15 2004 Thursday 12-23PM

Thursday, April 15, 2004 1:55:29 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

I finally got copies of my first article published about the DDL. The article was published in the .Net Developer Journal.
http://www.sys-con.com/dotnet/

 

The DDL was a language that my team developed during our final year college project. At that time, we believed that it was a one of a kind language. Of late we have come across similar work done by Professor Godmar Back of Stanford University.

 

The DDL language basically lets one specify binary data formats and the language interpreter provides services to interact with data of that format. Read more about the DDL at the project homepage:

http://ddl.sscli.net/

 

Professor Godmar Back’s DataScript language is described here:

http://datascript.sourceforge.net/

Apr 14 2004 Wednesday 01-24PM

Thursday, April 15, 2004 1:35:38 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

Following Sean Anderson’s approach to bit counting for 64 bit machines on his bit twiddling hacks page here: http://graphics.stanford.edu/~seander/bithacks.html

 

I wrote my own:

A Modulo Based Bit Counting Approach For 64 Bit Systems

http://www.thinkingms.com/pensieve/homepage/articles/tech/bitcounter64/bitcounter_64bit.htm

http://www.thinkingms.com/pensieve/homepage/articles/tech/bitcounter64/bitcounter_64bit_2.htm

 

Sean has graciously linked to me now and that makes this the first time my name exists under the great stanford.edu. Neat uh?

Thanks Sean.

Apr 13 2004 Tuesday 12-06PM

Thursday, April 15, 2004 1:34:35 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  | 

One of the things that’s rather high on my mind’s sort order these days is Ruby programming. I have been thinking about what makes ruby so neat a language to use, simply by virtue of what the language lets me do.

 

One of the early things that got me hooked to Ruby, was its support for iterators. If you have been spoiled by many years of C programming, like me, then its time to wake up and take a look at a few things that C can’t pull off, at least not very easily.

 

What is an iterator?

Let’s take a look at code like this, where there is a piece of code that produces value and a piece of code that consumes values.

 

void produce()
{

for (int i=0;i<100;i++)
            if( i%5 == 0)
                  consumer(i);

}

 

void consumer(int v)
{

printf(“%d”,v);
}

 

All things considered this code is fine, except that the producer invokes the consumer. And simply because of that the consumer cannot maintain state. The only way the consumer can maintain state, ie remember something between two calls is to save variables into either static variables, or globals or into some object.

 

The would be the argument if the consumer function tried invoking the producer, where the producer will have to have a very contrived piece of code to remember variable values between calls.

 

From a perspective, an iterator solves exactly this problem. This is a ruby code:

 

def producer

      for i in 0..99

            if (i%5 == 0)

                  yield i

            end  

      end

end

 

def consumer

      producer() do |v|

            print v

      end

end

 

The ‘def’ keyword starts a function/method declaration. The code above for the producer should be rather easy to understand, except for the yield statement.

 

What does the yield do? The yield causes the function producer() to exit with the return value of the function as the parameter of the yield, in this case ‘i’.

 

The difference between yielding a value and actually doing a return is that the function can continue execution from the point of the yield statement.

 

The consumer function then simply invokes the producer() function and catches each of the yielded values. That is why these is a ‘do’ statement and a corresponding ‘end’ statement in the consumer code. The parameter for the do-end block is the ‘v’ that is enclosed in ||. Every time the producer yields a value, the value is available in ‘v’ and the do-end block is executed. When the block finishes the producer continues after the point of the yield.

 

So if you want to, say calculate the sum of all the values that the producer yields, then you can

 

def consumer

      sum = 0

      producer() do |v|

            sum = sum + v

      end

      print sum

end

 

 

Now that you have been introduced to the idea of iterators, I suggest you do some thinking about, especially if you have done a fair bit of C programming. Imagine how these functions would have to maintain state, what their call stacks will look like and such.

 

Now let me clean up on a few things. In ruby all functions are called methods, formally. So let’s start calling them methods. Secondly a lot of the Ruby libraries are built to support iterators so you will see the idea being used a lot. Thirdly, the do-end block can also be written as { } curly braces.

 

The methods that I have written have been written in a drawn out C-like style, so that the ideas are clear despite the slight difference in syntax. So lets just rewrite the two methods slightly more ruby-ishly and close this blog entry.

 

def producer

      100.times{|i| yield i if i%5 == 0}

end

 

def consumer

      sum = 0

      producer {|v| sum = sum + v}

      print sum

end

 

You can get Ruby from here, for your windows box:

http://rubyinstaller.sourceforge.net

Apr 13 2004 Tuesday 11-05AM

Thursday, April 15, 2004 1:31:50 AM (Eastern Standard Time, UTC-05:00)  #    Comments [3]  | 

I started out by saving my blog files on my hard disk. Here is a little Ruby hack that I have to help manage by blog entries on my local disk. Presently I just write blog entries as small word doc files and save the files with the title of the blog as the filename. Then I figured that it would be more useful if, for sorting purposes I could name the files also by date and time.

 

A naming like this would be convenient:
Apr 13 2004 Tuesday 01-18AM - First Blog Entry.doc

 

Now I would not want to type in a name like this by hand, I’d just like to save the file and then have some little proggie do the rename for me. Here is a ruby script to do just that.

 

dater.rb

$format = '%b %d %Y %A %I-%M%p '

$format_pattern =       /^\w+\s\d+\s200\d\s\w+\s\d\d-\d\d(A|P)M\s.*/

 

def rename file,count=1

      $filename = Time.now.strftime($format) + "- " + file

      $alternate_filename = Time.now.strftime($format) + "[#{count}] - " + file

      if count == 1

            File.rename(file,$filename)

      else

            File.rename(file,$alternate_filename)

      end

end

 

if ARGV.length == 1

      rename ARGV[0]

else

      #~ Lets try anbd find the file to rename

      count = 1

      Dir["*.doc"].each do |file|

            puts file

            #~ See if this file needs renaming

            unless $format_pattern =~ file

                  puts "Renaming : " + file

                  if count == 1

                        rename file

                  elsif count == 2

                        #~ More than one file, so shift to "[count]" syntax

                        File.rename($filename,$alternate_filename)

                        rename file,count

                  else

                        rename file,count

                  end

                  count = count + 1

            end

      end

end

 

This snippet does the following

-          if a filename is given as an argument it simply renames the file.

-          if no file name is given it does search and rename in the current folder.

It basically looks for all doc files and sees which ones seem to be already renamed appropriately and skips those. Then it renames any file that it finds by prefixing the date time.

 

As an addition it also sees if there are multiple files to be renamed, in which case it puts a special count prefix also which is enclosed in []. Now all I need to do is to double click on my ruby script every time I save a blog entry into my entries folder.

 

That’s just what I am going to do with this one. :)

 

There is a Peter and Gordon West singing Hundred Miles in the background. Now the music has changed to Iris – Goo Goo dolls. I am feeling wishful. I also think I need to sleep now.

 

And I don’t want the world to see me

‘cause I don’t think that they’d understand

When everything’s made to be broken

I just want you to know who I am

- Iris, Goo Goo dolls

Apr 13 2004 Tuesday 03-25AM

Thursday, April 15, 2004 1:30:56 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]  |