Tech-o-rama Technology, web development and more!

26Jul/090

First Taste of Erlang/OTP

Of late, I have been hearing a lot about distributed/multicore/parallel computing and how it is going to be the future. Among various technologies which enable such large-scale processing, Erlang is quite like the silent killer: it has been around for years, it has been powering industrial scale systems for decades with excellent reliability, and is years ahead of its sequential competition in terms of sheer coolness. This post is about my first foray into the language, and a small chat system that I wrote as I have been learning the language.

Erlang/OTP was created by Ericsson long ago, to power its telephone exchanges, with support for hot code swapping and distributed computing. It was, from conception, rooted in functional concepts and oriented towards providing fault-tolerance. In fact, in the words of Joe Armstrong, one of the creators of Erlang,

Erlang is built on the ideas of:

* Share nothing. (Process cannot share data in any way. Actually, this is not 100% true; there are some small exceptions.)
* Pure message passing. (Copy all data you need in the messages, no dangling pointers.)
* Crash detection and recovery. (Things will crash, so the best thing to do is let them crash and recover afterwards.)

OTP stands for "Open Telecom Platform", which refers to the set of libraries that go with the default Erlang distribution. Erlang processes are more lightweight than threads, and Erlang supports hundreds of thousands of processes; no wonder Facebook uses Erlang to handle its chat system. Not only Facebook but also Goldman Sachs; the recently stolen source code belonging to Goldman Sachs used to perform High Frequency Trading (ie. trading within milliseconds) was written in Erlang. These were reason enough for me to personally go ahead and learn the language as a personal endeavor. And sure enough, it was rewarding.

The canon book for Erlang, written by the authors of the language itself, is "Concurrent Programming in ERLANG". The book follows a tutorial approach as opposed to a text-book style, which suited my temperament as an experienced programmer who wanted to get to the meat real quick. The documentation present in the online portal, erlang.org also proved helpful; the following chat script has borrowed heavily from the example provided in the online documentation. Anyway, to my great surprise, none of the pedantic arsery of functional programming purists (monads? Gonads!) was present in the book. Maybe all those functional concepts are present as a part of the language; even if they were, they must be pretty well hidden.
At any rate, the following code was the result of me parsing halfway through the book. It speaks volumes about how programmer-friendly the language is if I can write a client-server chat system in less than 150 lines, including error messages etc. So without further ado, I first present the code, followed by instructions to run/use the code. Note that <PIPE> and <SEMI> need to be replaced by `|` and `;` wherever they appear. I have given up on this problem; it seems to arise from the GeSHi syntax highlighter I am using here.

-module(chatsystem).
-export([start_server/0, start_client/2, client_login/0, 
	 client_logout/0, client_send_message/2, stop_server/0, 
	 stop_client/0,server/1, client/2]).
 
% Emulates a server. Supports login, logout, message passing and kill.
server(UsersList) ->
	io:format("Currently online: ~n ~p ~n",[UsersList]),
	receive
		{ Client, Username, login } ->
			% Check if user is logged in from elsewhere
			case lists:keymember(Client,1,UsersList) of
				true ->
					% Send a message to the Client about 
					% login error
					Client ! { login_error },
					% Simply restart the server.
					server(UsersList);
				false ->
					% Send a message to the Client
					Client ! { logged_in },
					% Show a message on the server window
					io:format("INFORMATION: ~p logged in. ~n",[Client]),
					% Add the user to UsersList and 
					% Restart the server
					server([{Client,Username}|UsersList])
			end;
 
		{ Client, logout } ->
			% Remove the client pid from the UsersList
			case lists:keymember(Client,1,UsersList) of
				true ->
					% Send a message to the Client about
					% being logged out
					Client ! { logged_out },
					% Show a message on the server window
					io:format("INFORMATION: ~p logged out. ~n",[Client]),
					% Delete entry and restart
					server(lists:keydelete(Client,1,UsersList));
				false ->
					Client ! { logout_error },
					% Restart the server.
					server(UsersList)
			end;
 
		{ From, To, Message, send_message } ->
			% Send Message to Pid at To depending 
			% whether To exists or not.
			case lists:keysearch(To,2,UsersList) of
				{ value, {ToPid, To } } ->
					% Send a message to To
					ToPid ! { From, Message, receive_message },
					% Send a confirmation to From
					From ! { message_sent },
					% Simply restart the server.
					server(UsersList);
				false ->
					% Send a message to the Client that 
					% the intended receipient was not found.
					From ! { recipient_not_found },
					% Restart the server
					server(UsersList)
			end;
 
		{ die } ->
			true
	end.
 
 
% Emulates a chat client. 
client(UserName,Server) ->
	receive
		% Processing messages.
		{ Sender, Message, receive_message } ->
			% Print the sender and the message.
			io:format("~p says: ~p~n",[Sender,Message]),
			% Restart client
			client(UserName,Server);
 
		{ login } ->
			{ chatserver, Server } ! { self(), UserName, login },
			client(UserName,Server);
 
		{ logout } ->
			{ chatserver, Server } ! { self(), logout },
			client(UserName,Server);
 
		{ To, Message, send_message } ->
			{ chatserver, Server } ! { self(), To, Message, send_message },
			client(UserName,Server);
 
		% Error messages.
		{ login_error } ->
			% Print the error message
			io:format("A login error occured. ~n",[]),
			client(UserName,Server);
 
		{ logout_error } ->
			% Print the error message
			io:format("A logout error occured. ~n",[]),
			client(UserName,Server);
 
		{ logged_in } ->
			% Print the error message
			io:format("~p has logged in. ~n",[UserName]),
			client(UserName,Server);
 
		{ logged_out } ->
			% Print the error message
			io:format("~p has logged out. ~n",[UserName]),
			client(UserName,Server);
 
		{ message_sent } ->
			% Print the error message
			io:format("The message has been sent. ~n",[]),
			client(UserName,Server);
 
		{ recipient_not_found } ->
			% Print the error message
			io:format("A recipient was not found. ~n",[]),
			client(UserName,Server);
 
		{ die } ->
			true
	end.
 
% Interface functions.
 
% Starts the server.
start_server() ->
	register(chatserver,spawn(chatsystem,server,[[]])).
 
% Starts the client.
start_client(UserName,Server) ->
	register(chatclient,spawn(chatsystem,client,[UserName,Server])).
 
% Login the client.
client_login() ->
	chatclient ! { login }.
 
% Logout the client.
client_logout() ->
	chatclient ! { logout }.
 
% Send a message to the reciepient To.
client_send_message(To, Message) ->
	chatclient ! { To, Message, send_message }.
 
% Kill the client.
stop_client() ->
	chatclient ! { die }.
 
% Kill the server.
stop_server() ->
	chatserver ! { die }.

So what does this code do?

This code creates a server, capable of responding to requests from a number of clients and which can keep track of who is online and who is not. The code also creates a client, which is capable of sending requests out to the server. In order to use this, let us assume we have three Linux machines (proton, pupil and phoenix) with Erlang/OTP installed, and that proton is going to be the server, and pupil and phoenix are going to be clients. Note that all the machines should have a file .erlang.cookie in your home folder in each machine containing the same content. This is used as a basic method of ensuring security. Also, assume that the above code is stored in a file called chatsystem.erl (The filename has to be same as the module name). Then the entire system setup would be as follows:

  • Start the Erlang shell on proton.

    ~$ /usr/bin/erl -sname server
  • Compile the chatsystem module.

    server@proton1>c(chatsystem).
  • Start the server.

    server@proton2>chatsystem:start_server().

Now open up the other two machines, load up Erlang and compile as in the server. However, instead of starting the server, we start the clients instead:
On phoenix:
phoenix@phoenix2>chatsystem:start_client('phoenix',server@proton).

On pupil:
pupil@pupil2>chatsystem:start_client('pupil',server@proton).

Now things become really simple. To login to the server (there are no passwords :) use
phoenix@phoenix3> chatsystem:client_login().

To logout, use
phoenix@phoenix3> chatsystem:client_logout().

To send a message to the user 'pupil' from 'phoenix', use
server@phoenix3> chatsystem:client_send_message('pupil','Howdy Ho!').

and voila, it works!

To kill the server and the clients, use
proton@proton3> chatsystem:stop_server().

phoenix@phoenix3> chatsystem:stop_client().

pupil@pupil3> chatsystem:stop_client().

Caveats

The usual caveats apply here. For one, this is not the most incredibly awesomely efficient implementation of a chat system ever. Neither it is the most secure (hell, there are no passwords!). But this can definitely be a starting point for a full blown chat system. Oh wait... Guess ejabberd has already done it. Crap.

Anyway that's it for my Erlang experience so far. I will post more about this in the future.

Filed under: Uncategorized No Comments
8Apr/09Off

Graphics Programming in C#: A Raytracer – Vector and Object

Since the math is boring anyway, I am presenting the code first, before putting in a word about the math. I will bring in the math involved when I come to the relevant sections of the code.

Vector

In order to reduce the effort of writing code for performing various vector-based operations that are required as a part of ray tracing( like vector addition, subtraction, scalar/vector multiplication, dot product, normalization and magnitude computation), I ended up writing my own Vector class. It is not the best of implementations, and the implementation of operations especially leaves a lot to be desired. However, it serves well to illustrate the concepts involved. Hence, here is the implementation of the Vector class where you can download it. I am not listing the source on the blog to save space.

Object

The objects in our world are assumed to be spheres (in this example). A sphere has a center and a radius. Furthermore, our objects have a color. Hence, a skeletal implementation would be as follows:

namespace RayTracer
{
    class Object
    {
        //As of now, we are saying that our object is just spheres.
        private Vector center;
        private Vector color;
        private double radius;
 
        public Object(Vector c, Vector col, double r)
        {
            center = c; color = col;  radius = r;
        }
 
        public Vector getCenter()
        {
            return center;
        }
 
		public Vector getColor()
        {
            return color;
        }
    }
}

Now, in the course of the raytracing process, we would have to check if a ray intersects with an object. Hence, it makes sense to put the intersection test as a part of the object itself. Since a ray is defined based on two Vectors, these vectors are provided to the function as arguments.

The expression for the intersection of a ray with a sphere is given as follows:
Let p be any point on the sphere, r, the sphere radius, and c the center of the sphere.
The equation for a sphere centered at the origin is given by:

(p-c).(p-c) - r2 = 0

The ray is given by two vectors r0 and r1. Then the expression for the ray is given by:

r = r0 + t * d where d = r1 - r0

Plugging the ray equation into the sphere equation, we get

(t d + r0 - c) . (t d + r0 - c) - r2 = 0

This is in a quadratic form. Hence, it can be solved in the standard quadratic method. Specifically, a, b and c in the quadratic equation are given by

a = d . d

b = 2 d . (r0 - c)

c = (r0 - c) . (r0 - c)- r2

Note that if the determinant is >0, we have two intersections - one before and one behind. If the determinant is 0, the ray just grazes the sphere at a single point, and if the determinant is <0, there is no intersection. Keeping this in mind, we include the following intersection code into the object class:

public bool intersects(Vector r0, Vector r1, ref Vector intersection)
{
	Vector d = r1.sub(r0);
	Vector r0centerDiff = r0.sub(center);
	double a = d.dot(d),
		   b = 2 * d.dot(r0centerDiff),
		   c = r0centerDiff.dot(r0centerDiff) - radius * radius;
	double discriminant = b * b - 4 * a * c;
	if (discriminant < 0.0)
	{
		intersection.set(0.0,0.0,0.0);
		return false;
	}
	else
	{
		if(discriminant==0.0)
		{
			double t=-0.5*b/a;
			intersection=r0.add(r1.sub(r0).mult(t));
			return true;
		}
		else
		{
			discriminant = Math.Sqrt(discriminant);
			double t1=-0.5*(b-discriminant)/a;
			double t2=-0.5*(b+discriminant)/a;
			Vector i1=r0.add(r1.sub(r0).mult(t1)), 
				   i2=r0.add(r1.sub(r0).mult(t2));
			double d1=i1.sub(r0).magnitude(),
				   d2=i2.sub(r0).magnitude();
			if(d1>d2)
				intersection=i2;
			else
				intersection=i1;
			return true;
		}
	}
}

The Object class forms the basis to most of the raytracing that I have done. I will describe the construction of the Light, Camera and Scene classes in the next post.

Filed under: Uncategorized Comments Off
6Apr/094

More Python coolness: Nested List Comprehensions and Map

I surprised myself today by being able to construct the following succint piece of code, the n00b at python coding that I was:

def getNeighbors(numverts,faces):
    neighbors=[]
 
    for i in range(numverts):
        n=set([])
        temp=[ [j for j in f if j!=i] for f in faces if i in f]
        [ map(n.add,j) for j in temp]
    neighbors.append(list(n))
    return neighbors

The above code was written for finding the neighbors of every vertex (numbered from 0 till numverts-1). Logically this is achieved by going through the entire list of faces for a given vertex i, picking all the vertices of the faces in which vertex i is present and returning a unique list of neighboring vertices for this vertex. Ideally the python code, using traditional for loops, would have looked like this:

def getNeighbors(numverts,faces):
    neighbors=[]
 
    for i in range(numverts):
        n=set([])
        for f in faces:
            if i in f:
                for j in f:
                    if j!=i:
                        n.add(j)
        neighbors.append(list(n))
    return neighbors

However, the first code listing is far too succint, and way more efficient. Also, the last two lines might seem like some vaguely corrupted form of English, but they are the proof of python's expressive power. Before I go into the details of this code, here's the background: I am using two concepts in programming with python, called list comprehensions and map(). These are functional programming tools available in python, and I am using them to kind of do pseudo-functional programming since I am using them in a predominantly imperative code.

List comprehensions are a way of generating a list of items by iterating through another list of items. Consider

items=[1,2,3,4]
newitems=[]
for i in items:
    newitems.append(i+1)

This uses an explicit for loop, which involves an overhead since it is handled by the interpreter. On the other hand, a list comprehension method of producing the same result is as follows:

items=[1,2,3,4]
newitems=[ i+1 for i in items]

The advantage is that the loop is now implicit ie. it is implemented in the underlying C code, and hence is much faster.*

In general, the syntax for loop comprehensions is :

newlist = [ update_expression(item) for item in items | if condition(item) | ]

Note that I am using | <> | instead of the usual [] to denote an optional syntactical item since [] has a special meaning in python.

Now think about it: what if the update_expression(item) itself is another list comprehension? Then you have nested list comprehensions :) Which is cool, in a way, and twisted, in another. In general, to understand a list comprehension follow two rules:

  • Go from the outermost list comprehension to the innermost.
  • Read the for first, followed by the if, and finally the update expression.

If this method of reading is done to the nested list comprehension in the first code listing, one can see that it easily expands into the 'for' structure in the second listing.

All right then, what is the second line with the map() function doing? The map function takes in a single-argument function as its first argument, and a list as its second argument, applies the function to every element in the list, and returns a new list - very much like the list comprehension. List comprehensions cannot be used if the construction rule for the list is too complicated, or can change during run-time; map() saves the day in such a situation. However, in this case, map() is used for illustration.

Note that the first nested list comprehension has a unwanted side effect: it produces a nested set of lists like [ [ 1, 2, 3 ] , [ 3, 4, 5 ] ]. We want to combine these into a single unique list. The list comprehension involving the map() does exactly this: doing the read-for-then-update, we find that for every list 'j' in temp, we run the map, which does nothing but applying n.add to the list j, effectively populating the set n with unique values. Voila!

Why do we want to use map() and list comprehensions? For speed. Simple for loops implemented in python are handled by the interpreter, and are slow. List comprehensions and map() have a in-built, fast, internal C implementation which does away with the overhead of the for loop. So, performance of the code also improves. Also, since every list item is updated independent of every other list item, these operations can be parallelized; this is one of the advantages of functional programming over imperative programming since the parallelism is plainly obvious.

All said and done, however, LLVM based unladen-swallow might change the game... Let us see :)

* - I'm not speaking out of my posterior here - this is a well know performance issue. Read http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops

Filed under: Uncategorized 4 Comments
5Apr/097

Graphics Programming in C#: A Raytracer – Humble Beginnings

Imagine summer vacations:
Little Boy: Mommy, I'm bored. What shall I do?
Mom (after a little thought): Go write a raytracer.
Little Boy: Wheee!

Ok, after that piece of nonsense, I'm sure anyone would choose to do one of two things:

  • You decide I've finally thrown in the towel and gone nuts.
  • You have the patience to read the rest of the post, for you are the patient, unfazed reader. This post is for you.

Motivation

Lets' have some motivation, shall we? Stare at this picture for a while, and you'll understand what got me started on raytracing.

Look at that thing of beauty

Look at that thing of beauty - created by Gilles Tran

Sufficiently motivated? Let's move on :)

The Basics

Raytracing is exactly what it suggests: you trace rays. But then, that tells nothing about how it is done in reality, so a few definitions are in order.

Different Objects in a scene

Different Objects in a scene

Camera

A camera is an abstraction of a real life, pin hole camera. It is assumed to have a single point, where the "eye" of the observer is present, and a rectangular plane(can be any shape, but rectangular is usually the case) representing the screen. This rectangular regions is discretized and divided up into pixels, and these are the pixels that produce the image.

Light

A light is a point source which provides illumination. It has an origin and a color (although, for now, I am going to assume all lights shine white).

Object

Object is an entity that is present in the world. It is built up from a bunch of shapes (triangles, cuboids, spheres, planes) and possess an origin and a rotation/scale parameter (although these are, once again, ignored in this naive implementation)

Scene

A scene is the world you would see in a raytraced image. It is a collection of Objects, Lights and a Camera; multiple cameras usually do not make sense.

But, how does it work?

Well, in order to compute the color of a pixel on the screen, we trace the rays backward from the eye to the source. Hence, the following algorithm applies:

1. Compute screen_coordinates from x,y location in image.
2. Compute ray cam_ray from eye via screen_coordinates
3. See if this ray hits any object in the scene.
4. If it hits an object in the scene,
    i. Shoot a ray light_ray to the light sources in the scene
       and see if light_ray is occluded by any object
    ii. If it is not occluded,
        a. Shoot a reflected ray into the scene and get back
            the computed color from the reflected ray.
        b. Shoot a refracted ray into the scene and get back
            the computed color from the refraced ray.
        c. Compute the local color by combining object color,
            reflected ray color and refracted ray color according
            to the laws of physics.
    iii. Return the color as the color of the pixel.
5. Otherwise, return the background color of the scene as
    the color of the pixel.

It's that simple. In order to handle reflections/refractions, we just recurse through the color computing function and combine colors as required.

Neat! What's next?

The next post will be on the math behind doing some of the magic here. So watch this space for more! :)

Filed under: Uncategorized 7 Comments
2Apr/09Off

Artificial Intelligence with Python: Beauty in code

Although I have just begun learning and programming in python, I do know that python has a few tools which make written code look like a thing of beauty: pithy in execution, elegant in structure and an absolute joy to understand. However, I had not come across such an example which moved me so, until I came by this today:

from itertools import permutations
 
n = 8
cols = range(n)
for vec in permutations(cols):
    if (n == len(set(vec[i]+i for i in cols))
          == len(set(vec[i]-i for i in cols))):
        print vec

What does this code do? Solve the eight-queens problem. In six lines.

I will give you, dear reader, a moment to lift your jaw up from the floor, roll up your tongue, push your eyeballs back into the socket and take a breather before I continue :)

OK, how does this work? permutations(cols) produces a permutation of the numbers from 0...(cols-1) and so, this prevents the necessity of checking for cuts in the vertical direction. Also, since each index is unique (cols is a list), we are guaranteed that there is no overlap on the horizontal direction either. Hence the only possible checks that need to be made are in the two diagonals.

The beauty of this program lies here: In order to check for the left diagonal overlap, all you need to do is to see, after subtracting the index from the position for each of the queens, whether there are any repeats in the positions vector. This makes sense if you look at the extreme case: the positions of each queen is given by [0,1,2,3,4,5,6,7] and you move every queen back to the first column, thereby indicating that there is a conflict. A similar logic exists for the right diagonal.

Now, to check if the length of the unique shifted position vectors is the same as the number of queens, we make use of the set object which maintains a unique list of elements; the (vec[i]+i for i in len(cols)) is known as a list comprehension and is one of those little things that python excels at. We just put all these together to produce this beautiful piece of code.

What's the catch? Note the line

 for vec in permutations(cols):

. For large enough cols, the number of unique permutations can get out of hand, and we would have to resort to the usual back-tracking algorithm. But otherwise, this is a very good example showing what python is capable of.

For more such tiny gems go to: PyCon presentation - Easy AI with Python. This example was taken from the presentation given in the site.

Filed under: Uncategorized Comments Off
31Mar/09Off

Python Programming Goodness: A Geometry class

This is my first post on the Python language. I am currently learning how to program in python, and my code may not be the best possible; however, it would do well to illustrate different concepts used if the code is simple. Also, I am publishing this code under the GPL; so anyone is free to use and make this implementation better.

Some Background

So, what is a geometry? I define a geometry as follows:

A geometry is a set of indexed vertices and tuples built using the indices that describes a decomposition of a given domain.

What this means is that, we have a set of vertices ( and possibly related information apart from the x,y and z coordinates) along with the relationship between various vertices resulting in the formation of elements. We keep the terminology as general as possible since this way, we can generalize to different kinds of elements and different dimensions (including mixed elements and 4D meshes, for example).

All Right, Where's the Python code?

Patience! So lets see what challenges face us here: We need a unique set of vertices, and a unique set of elements. Additionally, we need to have methods to add, remove and enquire about vertices and elements. This requires that we keep track of what vertices we have already stored, and what elements we have already stored, and searching through them when adding a new vertex/element if the vertex is already present in our geometry. Oops! That's an O(n^2) for the simplest case!

Instead, here's where the magic of the python language comes in; it makes life easy to the point that it is ridiculous. We can, for instance use a dictionary which stores the tuples forming the vertices as a key, with the index as the value. This way, if we need to check if a vertex is present in our original list, we can check in the dictionary in O(log n) time and be done with it!

Although the vertex case is easier, the element case requires us to be more careful. For one, an element may be added multiple times, with the only different being that the vertices may be cycled. In order to maintain a unique list of element tuples, we can sort the element tuple first before storing it in a dictionary; this way, no matter how cyclically different the element tuple is, we are guaranteed that we are looking at the same element.

Now that we've got our basic data structures out of the way, let us get into some python code:

class RawGeometry:
	vertex_dictionary={}
	element_dictionary={}
	num_vertices=0
	num_elements=0
	vertices=[]
	elements=[]
 
	def addVertex(self,vertex):
		retVal=0
 
		# Sanity check
		if len(vertex)!=3:
			return -1
 
		if vertex not in self.vertex_dictionary:
			self.vertex_dictionary[vertex]=self.num_vertices
			self.vertices.append(vertex)
			retVal=self.num_vertices
			self.num_vertices=self.num_vertices+1
		else:
			retVal=self.vertex_dictionary[vertex]
		return retVal
 
	def getVertexIndex(self,vertex):
		if vertex in self.vertex_dictionary:
			return self.vertex_dictionary[vertex]
		else:
			return -1
 
	def addElement(self,element):
		retVal=0
		elem_list=list(element)
		elem_list.sort()
		elem_tuple=tuple(elem_list)
		if elem_tuple not in self.element_dictionary:
			self.element_dictionary[elem_tuple]=self.num_elements
			self.elements.append(element)
			retVal=self.num_elements
			self.num_elements=self.num_elements+1
		else:
			retVal=self.element_dictionary[elem_tuple]
		return retVal

Cool! We've implemented a unique geometry which automatically takes care of duplicate vertices in ~40 lines of code!

Pythons ssslither: Watch out!

Well, not so fast, friend. We still have not implemented the vertex/element removal. And that turns out to be more hairy than you can imagine.

It is not difficult to see why it is so. When you remove a vertex, you are effectively removing an index not only from the vertex list, but also from the element list. Since we are using additional data structures for book keeping, the number of changes you need to implement for a single vertex deletion goes up. Let us list out the changes one needs to make for such a vertex deletion:

  • Remove the vertex from the vertex list
  • Remove all elements from element list which have the vertex given
  • Reduce the value of all the indices in all the remaining elements where the indices are greater than the index of the vertex deleted (whew! Read it again to understand :) )
  • Remove the entry of that vertex itself from the vertex dictionary.
  • Reduce the indices of all the vertices in the vertex dictionary whose index is greater than the index of the vertex deleted (Once again, read through carefully!)

Lets see an implementation of this deletion mechanism:

	def removeVertex(self,vertex_index):
		if vertex_index <0 or vertex_index >=self.num_vertices:
			return -1
		else:
			curr_vertex=self.vertices[vertex_index]
			del self.vertex_dictionary[curr_vertex]
			del self.vertices[vertex_index]
			self.num_vertices=self.num_vertices-1
 
			elemcount=0
			delkeys=[]
			for k,v in self.element_dictionary.iteritems():
				if vertex_index in k:
					elem_index=v
					del self.elements[elem_index]
					delkeys.append(k)
					elemcount=elemcount+1
 
			for i in delkeys:
				del self.element_dictionary[i]
			self.num_elements=self.num_elements-elemcount
 
			for i in range(self.num_elements):
				elem=list(self.elements[i])
				for j in range(len(elem)):
					if elem[j]>vertex_index:
						elem[j]=elem[j]-1
				self.elements[i]=tuple(elem)
 
			# Rebuild dictionary - bad hack
			self.element_dictionary={}
			for i in range(self.num_elements):
				elem=list(self.elements[i])
				elem.sort()
				self.element_dictionary[tuple(elem)]=i
 
			# Clean up the vertices dictionary - this is simple.
			for k,v in self.vertex_dictionary.iteritems():
				if v>vertex_index:
					v=v-1
 
			return elemcount

Notice the comment saying bad hack? This is a shortcut. Basically since we would have to traverse through the entire dictionary once again checking for elements which need to be changed, it is much more straightforward to recreate the entire dictionary since it is going to take around the same time.

The obligatory removeElement() is not described here since it is not much of a challenge to write; it simply requires deletion of the element form the element list and the dictionary. It is a two line function which I suppose, the gentle reader can very easily write :)

So that's it. A simple, straightforward Geometry/Mesh class in python.

Filed under: Uncategorized Comments Off
8Feb/09Off

Website development with Javascript and JQuery: Tutorial

One of the leading Javascript libraries available out in the web for free is jQuery. Created by John Resig, it lends a level of professional gloss to websites using it while making life easier for web developers to create extensive effects and features with its ease of coding. Indeed, it is testament to jQuery's contribution to web development that it sees growing usage in a large number of websites. In this tutorial, I go over the basics of jQuery, providing just enough information for creating the news ticker that we will take up as an example in the next sections.

jQuery provides a wrapper around the DOM so that all the nasty manipulation that developers using Javascript had to deal with are abstracted away. In addition to this, it provides a rich set of functions which allow the developer to work on any part of a HTML document using Javascript without too many hassles. Finally, it also provides a rich set of querying methods, after its name. Lets see each of these features one by one.

jQuery's main wrapper object is called jQuery. In order to make calls to the objects member functions and querying functions easier, the object is also mapped to the alias, $. This object can wrap around different kinds of DOM objects, and the functions that are available depend upon the object. Furthermore, the return value for every such function is the $ object itself. As a result, it is possible to chain different jQuery function calls in a single line, making the code concise and easy to read and understand. For example, we could wrap a piece of HTML, and append it to some div:

$("<strong>This is some bold text</strong>").appendTo("div")

The second usage is that of querying for ids, tags, classes and XPaths. This is used to select existing objects on the document for further manipulation:

$("#id") //Selects an object based on id
$(".class") // Selects based on class
$("tag") // Selects based on tag

Finally, if a DOM object is directly passed to $, that object is wrapped around and the functions provided by jQuery are applied to it; for instance,

$(document).ready(function);

is such a usage, and is used for providing a function to be called when the page has finished loading, providing a safer alternative to the onLoad function.

All right, lets move on to the things we need for our news ticker!

First off, we need some way of getting the data from our server. jQuery provides a number of functions for pulling data from your server using AJAX, all of which can be found here. However, for now, we will concentrate on the function:

jQuery.post( url, [data], [callback], [type] )

Simple, isnt it? The url argument is mandatory, and is a URL in your own domain; cross domain requests will fail, by design. The data variable is optional, and is used to send data to the server via POST. The callback argument is the name of a function which would be called once the data is received in its entirety; the type argument is used to indicate to jQuery how to handle the returned information from the server - as text, html, xml or json. The first argument of the callback function contains the data and the second contains information about the transaction. For example:

jQuery.post("http://www.example.com/info.php",
            { productId: "EF123a04W", category: "Cars" },
            displayInfo, "html");
 
function displayInfo(data, textStatus)
{
     $(data).appendTo("#infobox");
}

This would get the data from the above URL after passing the parameters and display the returned information as html in an element with id infobox. Whew!

Anyway, thats the major tool we would be needing for now, to get the data out of the server. In the next post, I will show how to get and process this data before displaying it as a news ticker.

Filed under: Uncategorized Comments Off
7Feb/09Off

Set up Wordpress on a web hosting server: Part 1 – Hosting and Upload

So, you have decided to start blogging. And, being the web developer that you are, you dont want to be limited by the free blogging services out there like Blogger or Wordpress; you want to have more control over what you can do with your blog - right from the design to the little plugins and widgets that go into making up your blog. Whatever be the case, this tutorial would explain how to go about installing Wordpress on a free hosting server.

Obviously, one of the first things you would need to set up is a free hosting service. Many such hosting services are available on the web today. However, when you choose one, pick one with enough bandwidth and storage, and one that supports PHP and MySQL, since Wordpress needs them. Some popular hosting services are xtreemhost and 000webhost ; both of them provide good services for people who want to start off with their own site, do not mind their website being a subdomain of the main domain and do not want to pay for web hosting.

Once your free web hosting is set up, it is time to get Wordpress on your website. Some web hosting services provide an automated installer which installs different blogs, CMS and other interesting stuff on your site so that you do not have to go around mucking with the installation in the background. However, that isnt exactly what we want, is it? So go ahead and download the latest version of Wordpress from the Wordpress download site and extract it into a folder on your computer.

Although most free hosting sites offer a web based file upload interface, it is usually too clunky and too alien for people who are used to the native interface of their operating systems. Hence, these sites also offer FTP upload/download so that the hassles of uploading/downloading files is minimized. One of the better standalone FTP clients is FileZilla and that is what I will be using to explain the process of uploading the Wordpress files on to the web host.

After installing FileZilla, log in to the hosting server using the username and password that would have been given to you when you signed up for hosting. Ideally, the login process would look like this:

Login using FileZilla by providing the host, username and password

Login using FileZilla by providing the host, username and password

The contents of the web hosting space would be similar to the screenshot shown; ideally, there would be a file that would say DO NOT UPLOAD ANYTHING HERE and a folder called public_html, public or something equivalent. At any rate, you should not upload your files into this root folder; so navigate into public_html. Let us assume that we want our blog to be present at say, http://example.comyr.com/ . In this case, we want the contents of the Wordpress folder to be present completely in the public_html folder. In order to do this, select the entire contents of the Wordpress folder that you extracted out from the archive downloaded from the Wordpress download page, and drag it over to the public_html folder.

Now, FileZilla would copy your files to the hosting server. After the copy is complete, you would want to set up permissions for the public_html folder so that installation can be performed. In order to do so, go up one level, select the public_html folder, right click on the folder name and select "File Attributes..." This would allow you to set up the file attributes for the entire folder and the subfolders and files underneath it. You will receive the following dialog:

File Attributes

File Attributes

File Attributes Dialog

File Attributes Dialog

Select all of the checkboxes as shown in the picture, and the checkbox that says Recurse into subdirectories so that the changes are applied to all the subdirectories and files. Note that this setting is dangerous and allows read/write access to anyone who visits the site, and hence must be enabled only for the installation of Wordpress and should be changed to restrict access using the same dialog after installation is complete.

The actual installation process of Wordpress is extremely simple and will be covered in the second part of this post.

Filed under: Uncategorized Comments Off