HTML5 Experiment 1 – Burst the Balloon

HTML5 seems to be the buzz word now. People around me are excited about HTML5 or already working on something with HTML5.

Curious to know what the hell is this HTML5, I started reading something from https://developer.mozilla.org/en/HTML/HTML5. Well, truth be told, I finished the overview in say 15 minutes and didn’t know what exactly to do after that. I was in no mood to implement any of the HTML5 features in interviewstreet now (Btw, if you don’t know, interviewstreet.com is my company where we simplify the hiring process by assessing the candidates using automated tests.)

Then for the next 15 minutes, I started playing around with some of the demos at http://html5demos.com/. They are cool, but nothing new or mind blowing. We’ve already seen these stuff in flash and javascript using libraries like jquery, prototype etc. So, now the browser gives native support to these features. What’s the big deal?

I guess unless I create something using HTML5, I’m never gonna realize it’s true potential. I started with the canvas tag.

So, after loads of google search, copy pasted code and a few cups of coffee, here is my first HTML5 game. :) This is the screenshot of the game.

You can play the game at http://sp2hari.com/html5/burst_the_balloon.html.

TODO:
1. Some sort of levels in the game, where you are taken to the next level once you shoot all the balloons.
2. Display score, time taken and other details.
3. Two player game, where two players can shoot arrows from both the directions and one who gets the highest score wins.
4. A special balloon which gives you more score if you shoot it.
5. Better animation for arrow and balloon. Right now, the balloon looks like an egg.

Anyone interested in playing/learning with HTML5 can take up this code and implement something from the above TODO list. Do mail be back at sp2hari AT gmail DOT com if you implement anything or even if you have anything to say about this game :)

Advices…

More than an year since I’ve quit IBM and into startup world. Too many things to write.. Things moving at such a rapid rate that if I write something today, tomorrow it might not be valid or correct. Makes me stop and think at times whether what I’m doing makes sense, is it the right path or am I yet another crazy person.

Advices are something whichi I’ve got more than I’ve wanted in this one year. Way too many advices. Contradictory advices. Person X says do this and Y will say don’t do this. Among all the advices I’ve got till now, I remember just 3.. These 3 are now a part and parcel of every small decision I make and are a part of my system.

SwaroopSwaroop is currently working in Infibeam and has worked in Adobe, Yahoo and his own start-up. He blogs at http://www.swaroopch.com/. We met swaroop when he was just about to join infibeam and the main goal was share his experiences and basically to get some start-up gyaan.

He started the whole conversation with the following disclaimer

Hey, I'm going to say a lot of things which I've learnt from my experiences. I might give loads of experiences. But don't take them for granted. Never apply them directly in your business. Anything I say, please use your brain and make sure you check whether it makes sense for you to follow it or not. We met a bunch of VC's and every VC suggested a change which changed the business by like 10%. After meeting 10 VC's and implementing a whole lot of changes in our product, we came to realised that we've changed the product by 100% and what we have now is not what we started to do.

If you don’t consider that as an advice, read it again twice.. thrice.. maybe 100 times. I did the same mistake. I didn’t realise I was doing it before I met him. I knew I was making tangential changes. But what I forgot was these tangential changes add up and change your product whole lot.

So, every customer or client has his/her own requirement. Before we met him, we used to put a night-outer, finish the feature for that customer and try to make him happy. What we failed to think was what will happen beyond that customer.

Now, things wait. We take 2 days even to start a new feature. We have a build cycle, where in our new features gets pushed to production only on Mondays. So, even if I code something fast and quick, I have to wait till Monday to get it to production. So, I take this time to think more about the feature and this helps us a lot.

NithyaThe second advice is again way too obvious and I can’t believe I started following this only after I heard it from someone.
Nithya Dayal is the CEO of Muziboo.com, where you can upload music and share it with friends. I happened to meet her in Yahoo Big-Thinkers event and we were talking about Product Management and what role does she perform as a CEO of Muziboo. So, she mentioned like ”

As a developer, it is easy to get excited with new technology, tools, products etc. So, what a developer does and what you've planned for the product might diverge at times. It is my job to make sure that what has been planned is executed. If you don't follow your plan, then the hours you spent on making the plan goes down the drain. So, either you shouldn't plan or if you do it, you should execute it

How this helped me?
Lots lots and LOTS. I stopped doing multiple things at a time. Both in my desktop and my mind, I had only one thing to do. Stopped switch tasks and realized that “Developers are monkey minded.” Even now, it is so damn itching to work on cool stuff like scaling, mysql replication, multiple servers and other stuff. But the plan in the board says “Get 10 paying customers and then think about anything else”. So, back to the small small features customers asked for and trying to close the deal than work on new cool features. :)

MukundLast one, is from Mukund from Buzzgain. If you’ve by any chance met him, you will become his fan. Simply awesome guy whose enthusiasm level is never less than 100% :). So, we showed him a demo of our product and he liked it, suggested changes, sales tips and while we are about to leave and say bye, he asked us a question.

"Why didn't you ask for more contacts from me? You SHOULD ask that. Do you remember the binary tree you read in college, that is how you should do sales. Every person you meet ask him 3 more contacts. ".

I was speechless. I was SO dumb that getting more contacts from him never even occurred to me. Again, a simple advice. I’ve made it a habit now.

I hope following just 3 advices over a period of 12 months is not so bad after all.

The Frog in the Well

Frog
Once there was an old frog who lived inside a deep well. Frog was so happy with his home that he always told his friends who also lived in his well how wonderful the well was.

One day, Frog was sitting on a ledge near the wall of his well appreciating the sky when he saw an unexpected visitor at the corner of the big round sky. It was a big turtle from the Eastern Ocean that Frog had never seen before.

“Hi there!” Frog croaked. “I don’t believe we’ve met before! Please friend, please come into my well and pay me a visit. My well is the best place in the world, and I’m sure you’ll be very comfortable here.”

Turtle looked down inside the small well, straining his eyes. “Alright,” said Turtle. But the closer he got to the well, the smaller the opening looked to him. “I’m sorry Frog, I don’t think I can make it down there – I think I’d get stuck!”

“But of course you can fit in my well!” said Frog, “It’s very spacious! And you don’t look too big to me.”

“That’s because the opening to your well is so small, you can only see my face. You still can’t see the rest of me! But you’re right, in comparison with my friends from the Eastern Ocean, I’m not very big.”

Frog’s eyes bulged. “You mean there are creatures outside of my well there that are bigger than you?”

“Much bigger!” Turtle said. “Here you have tadpoles, but in the Eastern Ocean we have whales! Here you have goldfish, but in the Eastern Ocean we have Sting rays, sharks, and schools of small fish that are so big that they look like clouds. The Eastern Ocean is so big that it can hold all of those things and we never feel cramped. We can’t see the end of the Eastern Ocean like you can in your well.”

The Frog fell off his lily pad in shock. Then he climbed back up, a little unsteadily. He stared at Turtle for a moment in disbelief, and then said, “I’m not sure I believe you. I don’t think there could be anything that big, and certainly not as nice as my well.”

Turtle smiled, “Then I’ll take you to see it.”

It took all of his strength but by hopping off of the walls, Frog was finally able to jump out of his well and land on the dewy grass beside it. But once outside, Frog couldn’t sop sneezing and squinting.

Turtle asked, “Do you feel alright, little friend?”

The sun was so hot on his back, but eventually Frog nodded. “I always thought that the sky was round and that it was the size of my well’s opening. I never knew that it was so huge – I can’t even see its edge! And the sun! It blinds my eyes! I never knew it was so powerful!”

“Now do you understand why I said the well is small?” Turtle said gently. “Certainly your well is a great place to live, but there are many great places on the earth – some much greater than your well.”

Frog just hung his head in embarrassment. He knew he would still enjoy his life in the well, but now he realized that he and his well were a small part of a very big world.

Next time,
1. A newbie linux user tells me that linux is secure than windows because it is virus free,
2. A moron tries to convince me that opensource is the way to succeed in business
3. Even my manager tells me that gvim is better than emacs,

this is the link I’m going to forward to them. It is like fighting with a dirty pig when you try to argue with these people. You are gonna waste your time and energy at the end.

Just want to vent out my frustration. People are ever ready to start a flame war, but never ever think about learning something new. Biased Morons.

Delete a remote branch in git

We use Git here at interviewstreet. Using Git, branching, testing and reverting is so easy.

Almost all commands are simple and easy to remember in Git, except for deleting a remote branch.

The command to delete a remote branch “feature1″ is

git push origin :feature1

Just wanted to note this down.

Advanced Bash Scripting – Part 2

Shell ScriptThe problem statement is as follows :

The Playfair Cipher encrypts text by substitution of digrams (2-letter groupings). It is traditional to use a 5 x 5 letter scrambled-alphabet key square for the encryption and decryption.

Each letter of the alphabet appears once, except “I” also represents “J”. The arbitrarily chosen key word, “CODES” comes first, then all the rest of the alphabet, in order from left to right, skipping letters already used.

To encrypt, separate the plaintext message into digrams (2-letter groups). If a group has two identical letters, delete the second, and form a new group. If there is a single letter left over at the end, insert a “null” character, typically an “X.”

To read more about the question, check http://tldp.org/LDP/abs/html/writingscripts.html

The solution for this question is pretty long (over 100 lines in shell script). You can check the final solution at http://sp2hari.com/bash/playfair-cipher.html

Explanation of function/code used in the solution.

locateInKeySquare: Searches for the character passed as the parameter in the keySquare and returns the position of the character.
addToKeySquare: Adds a character c passed as the parameter to the keySquare. This checks if the character is already present, if it is J and changes it to uppercase (if needed)
printKeySquare: Prints the keySquare from 1D to 2D format.

The rest of the code adds the keyWord to keySquare. The the remaining words are added to the keySquare. After that, we extract the dialects from the plaintext and based on the 3 rules, we encrypt the text.

Hope this is helpful..

Query String in URL using Codeigniter

CodeIgniter by default won’t allow you to use query strings in the URL.

This is how you enable query string in url in codeigniter.

1. Set $config['uri_protocol'] = “PATH_INFO” in config.php

2. Set $config['enable_query_strings'] = TRUE in config.php

3. Make you sure you have QSA in your .htaccess. For example,

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|includes)
RewriteRule ^(.*)$ /index.php/$1 [L,QSA]

Note: If you make these changes, the pagination module is affected. So, if you had implemented any pagination before changing these settings, you might want to check them again.

My first 30 day challenge.

I’m a big fan of Matt Cutts (who isn’t) and especially like his 30 day challenges.

So, I decided probably I can give it a shot for a couple of months.

So, some of the stuff I had in my list are.

1. Learn Hadoop.
2. Read a book every 2 days.
3. Learn a new programming language
4. Go to beach everyday and spend at least 30 mins there..

So, this is what I’m going to try for this month. Sleep properly for a month. I’ve neglected my bad sleeping habits for a very long time and it’s time I try to do something about it.

So, planning to go to bed by 1 AM and not wake up before 6AM.

Let us see how long I can manage this one…

Importing Contacts from Google Mail using OAuth

This is my second post in the fetch contacts from email account series. In this post, we are going to fetch contacts from a Google account. This isn’t a detailed tutorial, but a quick 2 minute how-to.

$this->config->item(‘google_return_url’) is the url of the page to which user is returned after a login attempt.

1. Add the following code where the user has to select Google Mail to import contacts.

<a href="https://www.google.com/accounts/AuthSubRequest?next=<?php echo $this->config->item('google_return_url').'?data=abc'; ?>&scope=http://www.google.com/m8/feeds/contacts/default/thin&secure=0&session=1">Fetch Google Contacts</a>

2. Include these 2 functions in your PHP code.
function make_api_call($url, $token)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
 
function get_session_token($onetimetoken)
{
    $output = make_api_call("https://www.google.com/accounts/AuthSubSessionToken", $onetimetoken);
    if (preg_match("/Token=(.*)/", $output, $matches))
    {
        $sessiontoken = $matches[1];
    } else {
        echo "Error authenticating with Google.";
        exit;
    }
    return $sessiontoken;
}

3. Add the following code to the return url file.

$sessiontoken = get_session_token($_GET['token']);
$contacts = make_api_call("http://www.google.com/m8/feeds/contacts/default/thin?alt=json&max-results=1000", $sessiontoken);
$contacts = json_decode($contacts, TRUE);
foreach ($contacts['feed']['entry'] as $contact)
{
    $emails[] = $contact['gd$email'][0]['address'];
}
//$emails array has the email addresses of all the contacts.

4. That’s it folks. It is that simple.

Further reading :
1. http://code.google.com/apis/contacts/
2. http://code.google.com/apis/contacts/docs/3.0/reference.html

Importing Contacts from Yahoo Mail using OAuth

Importing contacts from mail accounts using OAuth is a long solved problem which doesn’t have a good implementation. I googled and googled for a good library which imports contacts from Yahoo/GMail/Hotmail. Finally, I was forced to create one by myself. Here are the instructions on how to get it up and running for Yahoo Mail in your server in 2 mins.

1. You need a Yahoo API Key to fetch contacts from Yahoo. Proceed to Yahoo Developer Dashboard and create a key.

Application URL in the createKey page is the URL to which you will be redirected to after a successful/failed login attempt.
Application Domain is be your domain name.
Choose “This app requires access to private user data.” in the Access Scope and under the options which appear below that, select “Read” access for “Yahoo! Contacts”.
Store the API Key, Shared Secret and Application ID carefully.

2. Download Yahoo Social SDK for PHP from http://developer.yahoo.com/social/sdk/php/

$this->config->item(‘yahoo_consumerkey’) is your Yahoo API Key.
$this->config->item(‘yahoo_consumersecret’) is your Yahoo Shared Secret.
$this->config->item(‘yahoo_applicationurl’) is your Application URL you provided in Step 1.
$this->config->item(‘yahoo_applicationid’) is your Yahoo Application ID.

3. Add the following code where the user has to select Yahoo Mail


<a href="<?php echo YahooSession::createAuthorizationUrl($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationurl').'?data=abc'); ?>">Fetch Yahoo Contacts</a>

You may remove the ?data=abc if you don’t want to pass any data to Yahoo. Anything you pass here can retrieved back at Application URL as GET parameters.

4. Include the required files from the opensocial SDK library and then add the following snippet to the Application URL you provided in Step 1.

if (YahooSession::hasSession($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationid')))
{
    $session = YahooSession::requireSession($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationid'));
    $user = $session->getSessionedUser();
    $contacts = $user->getContacts(0, 1000);
    foreach ($contacts->contacts->contact as $contact)
    {
        foreach ($contact->fields as $field)
        {
            if ($field->type == "email")
            {
                $emails[] = $field->value;
            }
        }
    }
    //$_GET['data'] will be equal to "abc" at this page.
}
//$emails array has the email addresses of all the contacts.

5. That’s it folks. It is that simple.

Further reading :
1. http://developer.yahoo.com/social/sdk/php/
2. http://developer.yahoo.com/oauth/

Security settings for a LAMP Server : Iptables

Security is the major concern for anyone hosting a website on the internet. These are the preliminary security settings to be performed to protect your server.

iptables
Our server stack is LAMP. Hence iptables as the firewall is the most natural choice. The requirements are like

1. Block everything except Ping, SSH, Apache, and SSL.
2. Enabled SSH only from the selected IP addresses.

The following script takes care of all iptables settings. (Idea copied from here)

Note: Please enter the command one by one. Make sure you replace IP1.IP2.IP3.IP4 with your own IP address.

# Establish a clean slate
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F # Flush all rules
iptables -X # Delete all chains
# Disable routing. Drop packets if they reach the end of the chain.
iptables -P FORWARD DROP
# Drop all packets with a bad state
iptables -A INPUT -m state --state INVALID -j DROP
# Accept any packets that have something to do with ones we've sent on outbound
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Accept any packets coming or going on localhost (this can be very important)
iptables -A INPUT -i lo -j ACCEPT
# Accept ICMP
iptables -A INPUT -p icmp -j ACCEPT
# Allow ssh
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow httpd
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Allow mysql
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
# Allow SSL
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Block all other traffic
iptables -A INPUT -j DROP

I guess the above script should take care of the basic security issues. Hope it helps.