Extracting url parameters in JavaScript

October 27, 2009 by abhirama

A simple JavaScript function which parses the url and returns an object(map) with keys being the parameter names and values being parameter values.

function getUrlParameters() {
	var url = document.location.href;
	var parameters = url.substring(url.indexOf("?") + 1);
	parameters = parameters.split("&");
	var parametersObj = {};
	for (var key in parameters) {
		var parameterString = parameters[key];
		parameter = parameterString.split("=");
		parametersObj[parameter[0]] = parameter[1];
	}
	return parametersObj;
}

If there are multiple parameters in the url with the same name, only the last one will be present in the returned object.

SQL and case insensitiveness

October 13, 2009 by abhirama

Can you figure out the flaw in the below code snippet(hint:take a look at the title again)?

my $sql = "select count(*) as noOfUsers from users";
my $sth = $dbh->prepare($sql);
$sth->execute();
my $ref = $sth->fetchrow_hashref();
print $$ref{"noOfUsers"};

Answer:
Sql is case insensitive. So, even though the alias noOfUsers is in camel case, when the database query results are returned, it will be in lower case. Hence print $$ref{“noofpeople“} solves the problem, but a good practise would be to lower case the alias in the query itself.

Somnathpura and Triveni Sangama

October 13, 2009 by abhirama

Summary:
One day trip of Somnathpura and Triveni Sangama with Pavitra, in my first generation, three year old TVS Apache. Clocked 331 kilometres.

The plan was to leave on Saturday at 6:30 in the morning. Pavitra had damaged her legs due to her over zealous involvement in aerobics and she gave up saying she will not be able to walk. So we postponed it to Sunday. Sunday, I was a bit hesitant to go ahead keeping in mind Pavitra’s condition, so did not wake up when the alarm rang at 6:30 in the morning. At 11 while having breakfast (yeah on Sundays we have breakfast at 11), we suddenly decided to go ahead.

By 11:30 we left Indiranagar to take Bangalore Mysore state highway. Reached the outskirts of Bangalore an hour later, being stuck in traffic most of the time. What more can you expect if you start at 11:30 in the morning? Somnathpura does not seem to be as famous as Talkad, as a couple of people on the way we enquired gave us blank faces when we enquired the route to Somnathpura. By the time we reached Maddur we were apprehensive as Somnathpura was missing from the Karnataka tourism direction boards on the way. Suddenly it showed up in the direction board at the intersection of Bangalore Mysore state highway and the road to Malavalli. A tip for would be travellers to Somnathpura – Keep going on the highway, do not enter Maddur town, go past the road going into Maddur town, a few minutes later you will reach an intersection which has a huge Karnataka tourism direction board. Here, take a left which is the road that goes to Malavalli. Once you are on the Malavalli road, Somnathpura shows up on all tourism boards that you see en route.

From the intersection it is approximately 53 kilometres to Somnathpura. We passed Malavalli town and Somnathpura suddenly disappeared from the tourism direction boards. So, we asked the villagers regarding the route to Somnathpura, they informed us that we had to take a right at Malvalli, towards Bannur and from Bannur it is 10 kilometres. After cursing Karnataka tourism department for not putting the direction board at the most important place where it is required, we turned back towards Malavalli. The road till Bannur is manageable but once you cross Bannur, the road does a disappearing act. From Bannur till Somnathpura, the road is not tarred as it is under renovation. So for 10 kilometres we had a roller coaster ride which both of us thoroughly enjoyed but I pity the people who have to traverse on this road on a daily basis.

En route

En route

Keshava Temple, Somnathpura

Keshava Temple, Somnathpura

Entering Somnathpura temple premises was dejavu for us, as we had been to Belur Halebidu recently. The Keshava temple at Somnathpura was built in 13th century AD during the reign of Hoysala king Narasimha the third. A Hoysala tax collector by the name Somnatha sanctioned the building of the temple. The name Somnathpura owes it’s origin to this guy. As with most of the other historical temples in India, this one was also plundered by marauding barbaric Islamic invaders. As per Hindu traditions worship cannot take place in a temple that has been desecrated, so the deity here is not worshipped. 500 artists toiled for 58 years to build this wonder of the world. The main among them being Mallitamma, Masanatamma, Bamayya, Chamayya, Chowdaiah. Their signatures can be seen in various places in the temple premises.

Erotic carvings on the temple wall

Erotic carvings on the temple wall

There are 3 sanctums(garbhagudis) dedicated to Keshava, Janardhana and Venugopala. Due to this, this temple is also famous as trikutachala(3 sanctums) devalaya(temple). As with other Hoysala temples, this one is also built in the shape of a star. The main difference between this and the Belur, Halebidu temple is, this one has shikharas(towers) over the sanctums where as the Belur, Halebidu ones are flat roofed. The dance floor in front of the sanctums is square in shape and is not as big as the one in Belur, Halebidu as, here only Devadasis used to dance and offer their prayers to God, whereas in Belur, Halebidu the queen Shanthaladevi herself used to dance showing her devotion to God.

IMG_0078

IMG_0073

The same intricate details can be seen in the carvings as seen in Belur, Halebidu. The temple is built using soap stone(balapa kallu) and the stone was sourced from a place near Tumkur. Soap stone is supple when inside the ground but hardens up once exposed to atmosphere. All these facts were told to us by the guide whom we hired for 150 rupees. But actually, if you have been to Belur, Halebidu hiring a guide here is not needed as the sculptures bear a striking resemblance to the ones found in Belur, Halebidu.

After spending almost an hour examining the intricate carvings, we headed toward Triveni Sangama, the confluence point of Kaveri, Kapila and Gupthagamini Spatika sarovara, Gupthagamini Spatika sarovara being a river that flows under the ground. We went on a coracle ride in the river and the oarsman took us to the confluence point, which is marked by a pillar bearing a Nandi(bull) on top. This is the top of a submerged temple. Also he showed us a submerged place, where Agasthya the monk had carried out his penance.

Nandi at the point of confluence

Nandi at the point of confluence

The river is very broad but not deep at any point, the maximum being 6 feet. Also it is devoid of any whirlpools as the river base is not rocky. So, if you are heading there take your swimming gear with you, you can have a ball of a time. The river bed is an ideal place for a family picnic. The calm river water, the twilight and the peaceful atmosphere made the boat ride a very soothing experience. The oarsman had demanded 50 rupees per head, but Pavitra bargained with him and reduced it to 50 rupees for both of us. We handed him 10 rupees extra as he was a jovial and friendly person. We had a good chat with him about the area and the river during our ride. There are no sign board indicating this place, so keep asking for directions throughout the way, as it is easy to get lost. Triveni Sangama is at a distance of approximately 10 kilometres from Somnathpura and the road is extremely bad, but by this time you would have got used to bad roads ;) .

IMG_0171

On our way to Triveni Sangama we had seen orange flowers being grown amidst verdant paddy fields. The sight was heavenly and for sure we were not going to miss it. So we took a walk through the paddy fields till we reached the flowerbed. You can see the fields from the road on the way to Triveni Sangama. Park your vehicles and head to the field. This is something not to be missed. After this we headed back to Bangalore and reached home at 11 in the night with a pit stop in between as our numb asses begged for a break.

IMG_0180

Goa

October 9, 2009 by abhirama

Just came back from Goa yesterday. When someone tells you they have been to Goa, what they actually mean is they have visited beaches and places in Goa, as Goa is a state, albeit a very small one.

We were a group of 8 friends who drove through Tumkur, Chitradurga, Davangere, Ranebennur, Haveri, Hubli, Yellapura, Ankola, Karwar to reach Goa. The whole stretch can be done in approximately 10 to 12 hours. The road is very good till Tumkur, sucks from Chitradurga till Haveri, gets better once you cross Haveri. But, we Camped in Hubli and started the next day. Beyond Yellapura you will have to drive through thick forests and descend the western ghat, to reach Karwar. This part of the stretch has some sharp curves and is deserted, save for a few trucks here and there. Also keep one thing in mind, once you cross Tumkur there are no good restaurants on the highway. Either you have to pack your own food or drive into one of the towns on the way. The police at Karnataka Goa border harassed my friend Gowda saying show me the original RC book and took 50 rupees as “entry fee” (read it as bribe).

Our first stop was Palolem, a beach in Canacona district of Goa, approximately 20 kms from Karwar. Palolem looks more European than Indian as it is abuzz with white skin. The place has a lot of options to stay, but a couple of ones that we enquired were full. We finally wound up staying in Om Stays which is a line of huts(tiled huts not thatched) with attached bathroom and toilet located 5 minutes away by walk from the beach. The place was neat for 500 rupees per hut. Some of the huts had TV and hot water while others did not. The owner was a very friendly chap who provided us with extra beds and gave us a quick run down of Palolem. We were the only ones in that place and we took 3 huts. I talked to the owner regarding the rates and he informed me that 500 rupees was the off season rate. During season, it varies from 1000 rupees to 1500 rupees, 2000 rupees during new year. The tourist season in Goa is supposed to start from October 15 and peaks during the new year time.

Palolem beach

Palolem beach

I found Palolem beach serene and charming, with an ample mix of commercialisation and village charm. On the south side of the beach there are two out crops. I guess during high tide this is surrounded by water. One of the posters I read on the way refered to them as Venus island. The view from the out crops is breath taking and I could have sat there for hours in solitude listening to the chirping birds and the sound of the sea. I have no idea how it is during the peak season as, hut construction was going on through out the beach and the out crops, to be ready by the peak season. There are lots of shops on the way to the beach selling everything from toilet paper to clothing.

Palolem, Southern tip

Palolem, Southern tip

We had a ball of a time in Palolem playing beach volleyball, football and swimming. We were by the beach till 3 in the morning and no one came and enforced discipline on us. Also there are two bars on the beach side which are open 24 hours and also there is a Baskin Robbins ice cream shop which is open till one in the night.

Approximately 15 kilometres from Palolem there is another beach called Agonda which was deserted save for a single family and a couple at the time of our visit. You can see rocks jutting out from the sea and the beach ends with a majestic hill on either side. There is a fort called Cabo De Rama which is at approximately 10 kilometers from Agonda. We reached Cabo De Rama late, so we could not explore it completely but the view of the sea from the fort was heavenly. We spent some thirty minutes there monkeying around. The resort owner informed us that the sun rise and sun set from the fort is something not to be missed. The fort is surrounded by a deep moat and we were afraid as to whether the fort closes at night. So I went and enquired at the nearby bar regarding this and the person there assured me that it was open 24/7. The drive from Palolem to Cabo-De-Rama was scenic and the twilight added to the magic.

After 2 days in Palolem we headed to Panjim, capital of Goa. The road to Panjim was good, in general we found all the roads in Goa smooth with good direction boards. After a brief stop over in Panjim we headed to Calangute beach some 15 kilometres from Panjim. This beach sucked with crass commercialisation, crowd and garbage. I remembered Juhu beach. We had food in a hotel called Sagar near the beach and started hunting for a place to stay. We split into two groups with one group heading towards Anjuna while the other explored Baga for accommodation. We finally settled down for a place called Lua Nuva in Baga. Since it was off season, the proprietor agreed to rent out the room for 1800. It had AC but TV was not working and there was a small pool where we had a ball of a time the next day. The advantage of staying at Lua Nuva was that it was very close to Titos street, the happening street of Baga.

We wanted to explore the night life of Baga, so we headed towards Titos, a famous night club, which was our planned destination for the night. But to our disappointment we found out that it was open only during the weekends. It’s sister concern Mambos allowed only couples inside. After this let down we roamed Titos street up and down hopping in and out of lots of places. Lots of guys approached us with offers of disco parties. The usual deal was, for 300 rupees they supply you with an escort for the club and she stays with you until you come out. We did not go with this shady deal.

Next day we checked out Aguada fort which was buzzing with tourists. We were under the impression that this was the fort featured in the movie Dil Chahta Hai but later we came to know that we were wrong. From one side of the fort you get to view the grand sea. On the base of the hill where the fort is situated there is road that leads to a small beach by the Taj resort. Ahead of this beach, there is a path by the side of the mountain base which snakes towards the top. It was drizzling slightly and I had very slippery sandals on my feet. The verdant cliff, the raging sea, the overcast sky, the slight drizzle and the slippery ground made the trek a very enjoyable experience. If you have deep enough packets stay at the Aguada Taj resort. The view from the resort is splendid but starts from 16,000 rupees and goes till 60,000. Later we tried the cruise at Panjim. It costed 130 per head and lasted almost an hour. I would not recommend it to any one.

From Aguada fort

From Aguada fort

Next day we checked out Anjuna beach which actually has a very small stretch. Since it was raining heavily there were not many tourists around, but the place was buzzing with hawkers. We spent maybe ten minutes there and started towards Vagator to check out Chapora fort where the fort scene of Dil Chahta Hai was actually shot. En route for a brief period we stopped at Vagator beach. One has to endure a pretty steep climb to reach the fort, but the climb is worth every calorie you burn. The fort is surrounded by the majestic sea on two sides and you get a spectacular view of Morjim, Arambol beaches. Even though we did not visit these beaches, the view from the fort convinced me to make this visit mandatory the next time I visit Goa. There is a jutting in the hill, like a wharf, where you can walk to the edge of the cliff, like a diver going down a plank, for a jump into the pool. We sat there for sometime chatting and taking in the majestic sea. After this we headed back.

Outcrop at Chapora fort

Outcrop at Chapora fort

Since it was off season and rains accompanied us most of the time there were not too many people around. Also the hotel prices were really cheap when compared to the tourist season rates. Out of all the beaches we visited I found Palolem serene and tranquil, where one can spend time at his own pace. Have to experience Goa during the peak season.

3 day mototcycle tour of Bisle, Belur, Halebidu and Shravanabelagola

September 25, 2009 by abhirama

Summary:
3 day motor cycle tour of Bisle Ghat near Subramanya, Belur, Halebidu and Shravanabelagola with Pavitra. Clocked 714 kms in my first generation 3 year old TVS Apache.

19 September 2009:
Started from Indiranagar at 5:30 in the morning. It was drizzling slightly. First day plan was to ride till the view point near Bisle village located in Sakleshpur taluk of Hassan district near Subramanya. On the way back, check out Manjarabad fort in Sakleshpur town and then camp at Hassan for the night. Sakleshpur town lies on NH48. The usual route from Bangalore to reach NH48 is through Nelamangala. My friend advised me not to take that route due to the road widening work going on. So we took a slightly longer, alternate route which goes through Magadi town and joins NH48 near Kunigal.

The work on NH48 is going on in patches. With a few minor hiccups here and there, the road is not that bad and once the road work completes I am sure this road is gonna kick ass, as parts of the road where the work is done is a treat to ride on. Just outside Kunigal town we stopped at a road side restaurant and had our morning tea and breakfast. My hands were sort of numb by the time we reached this place due to the constant drizzle that had accompanied us. I warmed my hand with the tea cups and the blood started to flow again. Once we started, the weather cheered up and we saw the first glimpse of sun amidst the clouds. It felt good as the sun rays kissed our skin. At around 10:45 we were in Sakleshpur where we refueled our motorcycle and had good buns in a local restaurant. If you have not had buns before give it a shot. It is yum.

nh48

On NH48

On the outskirts of Sakleshpur town the road forks. One prong leads to Subramanya and the other to Mangalore. Bisle lies on the road to Subramanya. The sign board is crappy and we almost missed the turn. In many of the blogs we had read that the road leading to Bisle is extremely bad and desolate, save for a couple of vehicles here and there. But, we had a different experience. We kept meeting vehicles on the way and every now and then passed a small village. Also the road was pretty motor able and in a couple of places it was good. But mind you, we only went till the view point which lies a few minutes out of Bisle village. Have no clue as to how the road is after this. Also the direction boards are bad. So we kept asking people for directions.

On the way to Bisle

On the way to Bisle

A few kilometres outside Bisle village, forest department has constructed a view point from which you can catch a breath taking glimpse of Kumara Parvatha, Pushpagiri, Doddabetta, Sannabetta and the gushing Giri river at the base of these mountains. We were the only ones there. We sat there enchanted, taking in the surroundings until a group of morons came and started playing music in their cell phones and drinking beer. Once they left another family came and we soon left the place towards Hassan.

Bisle view point

Bisle view point

En route, some ten kilometres from Bisle village we stopped at a small green pond on the road side. Abutting the pond was a hill. The lure of the hill was too much for us to resist. So we started climbing it and once we reached the peak we got a 360 degree view of the surroundings which took our breath out. We just sat there doing nothing for sometime. Past few minutes clouds started moving in. The clouds moved in so fast that, the 360 degree view of few minutes back was reduced to a few meters. Now we were pretty much fucked as we did not have a clue as to which side we had to climb down to reach our motorcycle. We both debated on the path to take down and with our gut feeling directing us, somehow managed to reach the base. We thanked our stars as we reached our motorcycle but the scene of the clouds enveloping us on top of the hill is something that both of us will cherish throughout our lives.

Cloud Conquest

Clouds approaching us

Once we started back it started to drizzle and past a few minutes the drizzle became a heavy downpour which accompanied us throughout our way back to Hassan. We stopped just outside Sakleshpur town for tea and snacks. We were greeted by a dark Hassan. The main road of Hassan was covered with slush, the result of the heady downpour. We found the main road of Hassan (BM Road) more difficult to navigate than the Bisle ghat road. We were looking for a lodge, to camp for the night and Pavitra spotted a lodge called Kadamba. We went in and enquired the rates and found that it was pretty reasonable with 600 rupees for a night and 24 hours check out time, which suited us very well. Also it was apparent that the hotel had power back up because, when the whole city was engulfed in darkness the lodge shone bright with lights. The person in charge told us that hot water was available only in the morning. When we told him we need hot water for the night he cheerfully agreed to provide us with 2 buckets which was on our door in a jiffy. The room was decent, not spic and span clean but manageable. We were not hungry for the night as we had loaded ourselves on our way back. So we ordered soup and settled for the day.

20th September 2009:
Got up at 7:30, had breakfast in the hotel attached to the lodge and then set out towards Belur and Halebidu. The road was kick ass with a spattering of green fields, water bodies and mountains on the side. The cold wind was biting our skin while the early morning sun was casting his warm rays on his. With that atmosphere, a beautiful flawless road riding was a joy. The Metallica song “And the road becomes my bride” kept ringing in my head. Came to an intersection where a sign board asked us to deviate to the right for Halebidu and travel straight for Belur. We took the straight road and soon enough reached Belur. Cell phones are not allowed inside the temple premises. So, had to keep it at a shop and entered the Chennakeshava temple. Chenna means beautiful and Kesahva is Vishnu, the presiding deity of the temple.

The temple was built around 12th century AD and took 103 years to complete. Construction started during the reign of Hoysala king Vishnuvardhana and completed during his grand son’s tenure. There is a huge pillar(dwaja stambha) in the front. The guide told us that the pillar signifies a functioning temple. Right in front of the pillar is an idol of Garuda, Vishnu’s vehicle.

Chennakeshava Temple, Belur

Chennakeshava Temple, Belur

We were spell bounded by the intricate carvings on the temple walls. The attention to the most minute of the details in the carvings is something that we had never seen before. The carvings depict the way of life during those times, the styles in vague, moral stories, mythological stories and also as to how proportionate a woman’s body should be for her to look hot. By the way, hire a guide. For 150 rupees he brings life to those carvings with his stories. Every paisa that you pay is worth it. We spent some 3 hours in the temple checking every nook and corner. There is a lodge right outside the temple but I have no idea how good it is. Also there is a restaurant and lots of shops selling cool drinks and other tourist paraphernalia surrounding the temple compound. The temple opens it’s doors at 7:30 in the morning and shuts down at 7:30 in the evening. After this, we headed towards Halebidu. The road to Halebidu is also pretty good although a bit narrow. We reached Halebidu in around 30 minutes.

In the olden days, Halebidu was called Dwarasamudra because of the huge lake at the town entrance. Dwara means door and samudra means sea. The temple is situated on the bank of this lake. The lake was overflowing with water and we were told that this is the maximum water the lake has seen in the last twelve years. Dwarasamudra served as the Hoysala capital during it’s hey days before Mallikafur, the Islamic general of the Delhi sultanate plundered the city and destroyed parts of the temple. During his invasion the artists working on the temple fled from there. So the temple is incomplete. Due to this pillage of the city, it is today called Halebidu derived from Halada(spoilt) beedu(town).

This is a Shiva temple and as per the norms with Shiva temples, there are Nandis outside the sanctum(garbhagudi).The temple has 2 sanctums and both these sanctums have a monolithic Nandi outside them. They are the 6th and 7nth largest Nandis of the country. This temple is divided into two parts to signify the jeevatma and paramatma.

Halebidu

Hoysaleshwara Temple, Halebidu

The engravings on the temple walls and the temple construction is similar to Belur as both the temples are believed to be carved by the same sculptor Jakkanacharya. One main difference is, there are some erotic carvings here which are absent in Belur. The guide informed us that the stones used in the temple construction are clamped to each other, not glued. So the whole temple can be disassembled and reconstructed at another place. The same eye for detail that we saw in Belur can be seen here again but I guess the number of carvings are more in Halebidu when compared to Belur.

Both Belur and Halebidu temples are of the star shape. The guide informed us that all the temples built by Hoysalas are in the shape of a star. There is nice park outside the temple adjacent to the lake. We spent almost two hours in the temple studying the carvings and taking in the minute details. After this, we visited the ASI museum on the temple premises where there is a nice collection of the sculptures found in and around the temple and also from the other Hoysala temples in the surrounding areas. You have to pay a token fee of rupees two to enter the Museum. Seeing our interest, the guide informed us that we can collect a book on Halebidu from the ASI office, which we did. This book has some detailed history of Halebidu and the Hoysalas which I have not yet read in full but, plan to do.

Half a kilometre from the temple is a Basadi which has finely polished stone pillars which reflect your image as you walk past them. There is a huge monolithic statue of some Thirthankara inside the Basadi. Also some 100 meters from the Basadi is another temple which also exhibits some fine carvings. It was almost 5:30 by this time and the person in charge asked us to hurry up as it was time for him to leave.

We took the road next to the lake back to Hassan. There is a small bridge by the lake and we stood there for sometime taking in the view. The road back to Hassan was not as good as the one we had taken in the morning but was more picturesque. We reached Hassan in another one and half hours.

21 September 2009:
Got up at 8 in the morning. After having breakfast, checked out of the lodge and hit the road towards Shravanabelagola. To reach Shravanabelagola, we had to deviate from NH47 a few kilometers outside Chennarayapattana. The sign board asking us to take the deviation was pretty crappy and had it not been for Pavitra’s keen eye I would have missed the turn. The road to Shravanbelagola is world class and you pass through many villages on the way.

A few kilometres outside the town, we saw a temple on the hill and climbed it. Once we reached the premises, we came to know that it is a collection of Basadis and dates back to the 10th century. Also there is a proper path to this Basadi from the other side of the hill. There are lots of small Basadis and century old rock engravings inside the premises. From this hill, we got a very good view of the monolithic statue of Bahubali(Gomateshwara) located on the other hill and the steep climb one had to endure to reach the statue. After spending an hour exploring the basadis and the engravings, we got down and rode into the town.

Basadi on the hill top

Basadi on the hill top

After a long climb we reached the abode of Bahubali, the biggest monolithic sculpture in India, standing 18 meters tall. There is a collection of Jain Thirthankara statues in the premises and also a number of small sculptures scattered here and there. After taking in all this, we started our descent. Once we reached the base we had food in one of the Jain Bhojanalayas. The lunch consisting of roti, rice, two sabjis and one sambar costed us 40 rupees. It was pretty decent. After this we travelled back by the same road we had taken earlier to reach NH48 and then back to Bangalore through Magadi. Rode slowly taking in the views and was home by 7:30 in the evening.

Gomateshwara

Gomateshwara

The whole journey was a scenic treat with the colour green splashed all over, as this was the fag end of the monsoon season and the monsoon was really good at the end, this year. The temples at Belur and Halebidu are a class apart from anything that I have seen or heard before. My words will not do justice to this testimony of Indian art. You have to see it for yourself to experience it.

Quick sort in erlang and python

September 3, 2009 by abhirama

Python:

def quicksort(list):
	if len(list) == 0:
		return []
	else:
		return quicksort([x for x in list[1:] if x < list[0]]) + [list[0]] + quicksort([x for x in list[1:] if x >= list[0]])

Erlang:

quicksort([]) -> [];
quicksort([Pivot|T]) ->	quicksort([X || X <- T, X < Pivot]) ++ [Pivot] ++ quicksort([X || X <- T, X >= Pivot]).

This is so beautiful and concise.

Expression tree

August 26, 2009 by abhirama

Below is the python code to convert algebraic expressions to expression(binary) tree.

Some points to keep in mind:
1. Only -,+,*,/,(,) are supported.
2. Expression supplied is assumed not to contain white spaces.
3. Works only on single digits.
4. Parentheses are assumed to be balanced.
5. There is no error checking.
6. Multiplication and division take precedence over addition and subtraction.

operator_precedence = {
	'(' : 0,
	')' : 0,
	'+' : 1,
	'-' : 1,
	'*' : 2,
	'/' : 2
}

def postfix_convert(infix):
	stack = []
	postfix = [] 

	for char in infix:
		if char not in operator_precedence:
			postfix.append(char)
		else:
			if len(stack) == 0:
				stack.append(char)
			else:
				if char == "(":
					stack.append(char)
				elif char == ")":
					while stack[len(stack) - 1] != "(":
						postfix.append(stack.pop())
					stack.pop()
				elif operator_precedence[char] > operator_precedence[stack[len(stack) - 1]]:
					stack.append(char)
				else:
					while len(stack) != 0:
						if stack[len(stack) - 1] == '(':
							break
						postfix.append(stack.pop())
					stack.append(char)

	while len(stack) != 0:
		postfix.append(stack.pop())

	return postfix

class Node(object):
	def __init__(self, value):
		self.value = value
		self.left = None
		self.right = None

class ExressionTree(object):
	def __init__(self, root = None):
		self.__root = root 

	def inorder(self):
		self.__inorder_helper(self.__root)

	def __inorder_helper(self, node):
		if node:
			self.__inorder_helper(node.left)
			print node.value
			self.__inorder_helper(node.right)

	def preorder(self):
		self.__preorder_helper(self.__root)

	def __preorder_helper(self, node):
		if node:
			print node.value
			self.__preorder_helper(node.left)
			self.__preorder_helper(node.right)

	def postorder(self):
		self.__postorder_helper(self.__root)

	def __postorder_helper(self, node):
		if node:
			self.__postorder_helper(node.left)
			self.__postorder_helper(node.right)
			print node.value

def create_expression_tree(infix):
	postfix = postfix_convert(infix)

	stack = []

	for char in postfix:
		if char not in operator_precedence:
			node = Node(char)
			stack.append(node)
		else:
			node = Node(char)
			right = stack.pop()
			left = stack.pop()
			node.right = right
			node.left = left
			stack.append(node)

	return ExressionTree(stack.pop())

print "In Order:"
create_expression_tree("(5+3)*6").inorder()
print "Post Order:"
create_expression_tree("(5+3)*6").postorder()
print "Pre Order:"
create_expression_tree("(5+3)*6").preorder()

The forum mall Bangalore == crappy service

July 24, 2009 by abhirama

A man comes to a store with a tire he had purchased 6 months ago and asks for a refund saying the tire has manufacturing defects. The customer service representative at the store reimburses him without even a single question asked. The junior customer service representative is taken aback by this and confronts the senior saying “Why in this world did you reimburse him. We do not sell tires”. The senior says “He must have bought the tire from the previous shop that existed in this place 6 months ago. But our retail chain does not sell goods, here we sell an experience and I did not want him to leave our store in a negative state of mind. We value him as a potential customer. Today we might have lost a few dollars, but as we have made him happy, in all probabilities we have won ourselves a potential future customer. “

The above incident is from a book on marketing I read when I was in 7th standard and still after 13 long years I remember it. This is what I would call as the epitome of customer service. I do not expect this sort of customer service in India yet, but I certainly did not expect the crappy customer service we(Pavi and me) got in Forum Mall, Bangalore today, who advertise themselves with a web site called theforumexperince. The site name sounds like an oxymoron to me after today’s incident.

Our friends had gifted us forum vouchers on our wedding. The expiry date of the vouchers was 17th July. We had never checked the expiry date and also had no time to shop with all our post marriage settling down things. Suddenly yesterday my dad chanced to see the expiry date and told us about it. He was pretty apprehensive, but we pacified him telling that it is just 6 days since the expiry date and it is not from some petty shop, but from a mall and we are sure that they value their customers, so they will work something out.

We went to the mall today, and the following conversation took place.

I: Hi, we have these vouchers. Their expiry date is 17th July…
Mall representative: It is past the expiry date. We cannot do anything.
Me thinking in my mind, we know that it is past the expiry date and we do not need you to tell us that and this is for sure not the way to talk to a customer.
I: But, I am sure you can do something as it is just 7 days past the expiry date. I have had friends who had vouchers of other places and used it way past the expiry time. Can you please talk to your superiors regarding this?
Mall representative: No, we cannot do anything.
I : Can you please put me in touch with your superior so that I can have a word with him?
Mall representative: Ok.

Another female mall representative comes by and we have the same set of conversation repeated and she also exhibits haughtiness similar to her co worker. After this the guy leaves and in about 5 minutes the superior arrives. He repeats the same thing about our negligence and some other crap and a flat no. De javu. I guess we should have expected this from the way his subordinates behaved. Not even once did he say “Let me try to do something. I am not sure whether it will work out, but I will try my best”.

I totally agree it was our mistake and negligence but the way they treated us is for sure not the way to treat customers that too coming from someone who advertise themselves as “The forum experience.” If he had at least tried to do something we would have been happy irrespective of the outcome. I am for sure not going to gift any of my dear ones vouchers from the “Forum mall, Bangalore”. I do not want them to undergo a similar ordeal.

I am planning to write a mail to the customer service department of forum, Bangalore regarding this. Let me see what they reply, but I would be surprised even if I get a reply from them.

Updates: I got in touch with a member of the customer services team and the concerned person agreed to reimburse half the worth of our original voucher value.

ifdefs in Java

July 22, 2009 by abhirama

One of my colleagues who is new to Java asked me how to do ifdefs in Java? I said there is no way.

Why?
Whole concept of Java is “write once, run anywhere without code changes”. So ifdefs do not make sense in Java.

Triangular nos

July 9, 2009 by abhirama

Java:

public class TriangularNumbers {
  public int get(int no) {
	if (no == 1) {
	  return no;
	} else {
	  return no + get(no - 1);
	}
  }

  public static void main(String[] args) {
	TriangularNumbers triangularNumbers = new TriangularNumbers();
	System.out.println(triangularNumbers.get(4));
  }
}

Python:

def triangular_no(no)  :
	if no == 1:
		return no
	return no + triangular_no(no - 1)

print triangular_no(4)