How I do things

HTTP download speeds

In some of the Web projects I’m working on, I have a choice of many small files vs few big files to download.

There are conflicting arguments. I’ve read that many small files are better, because you can choose to use only the required files, and they’ll be cached across the site. (These are typically CSS or Javascript files.) On the other hand, a single large file takes less time to download than the sum on many small files, because there’s less latency. (Latency is more important than bandwidth these days.)

I ran some tests, and the answer is rather easy. The graph below shows the average time taken to download a file of size 1KB – 100KB.

Time to download a file of size ranging from 1KB - 100KB

The X-axis is the size of the file. The Y-axis is the number of milliseconds taken to download the file, averaged over 10 attempts on my home computer. (I did the same thing at work and at a client site. The results are similar.)

The key thing is, it’s not linear. Larger files take less time. Specifically:

  • A file twice as big only takes 30% longer to load.
  • Breaking a file into two parts takes 54% longer to load.

These days, it looks like few big files are better.

To give you an example: my home page had the following components:

Size (KB) Load time (ms)
HTML 25 680
CSS 4 340
Javascript 6 400
Total 35 1420

The total time for these 3 files would be about 1.4 seconds. Instead, if I put them all on one file…

Size (KB) Load time (ms)
All-in-one 35 770

The combined file takes only 0.77 seconds — half the download time for split files. It’s a compelling argument to put all your CSS and Javascript (images, too, if possible) into a single page.

But what if people visit multiple pages on my site, and lose the benefit of caching? Not really. The benefit of caching is small. By having a single file, I have 770 – 680 = 90 ms additional time for each HTML to load. But I don’t have to load the CSS and Javascript individually, which takes 740 seconds. The breakeven is about 740 / 90 = 8 page visits.

So, on average, if people, visit more than 8 pages in my site, it’s worth breaking up the CSS and Javascript. But the average for my site is only 2 pages per person. (It’s a skewed distribution. Most, from Google, just visit one page. Few, from bookmarks, visit several pages. On average, it’s just over 2.) I’d argue that unless you’re using an external Javascript / CSS library (prototype, etc.) or people view many pages each visit, you’re better of having a single HTML+Javascript+CSS file.

Making a Media PC

Two weeks ago, I pulled together a Media PC.

This has been a long-term ambition. I’ve always wanted to have a PC as the centre of all my media. To use it as a radio, TV, stereo system, CD player, DVD player, etc.

I finally did it, for just under 1000 pounds.

Media PC Setup

At the centre of the setup is my 42″ Plasma TV (LG 42PC1D). I was debating between a plasma and LCD TV. The differences, as I understand them, are:

  1. Plasma TVs have a higher contrast ratio. My LG 42PC1D has a 10000:1 contrast ratio. An LG 42LC2D has a 1100:1 contrast ratio. The Plasma TV is also brighter (1500cd/m2) than the LCD TV (500cd/m2).
  2. Plasma TVs are cheaper for a given size. A 42″ LCD TV costs about 5-20% more.
  3. LCD TVs are lighter. The only reason this matters for me is if I carry the TV back home to India. But the shipping costs are exhorbitant anyway. So I’d be better off leaving the TV behind. And the weight becomes irrelevant.
  4. LCD TVs consume less power. And my power bill is quite high. But I replaced most of the bulbs in our house with energy-efficient ones. Hopefully it will balance out.
  5. LCD TVs work better with computers. If you leave an image on a plasma TV for a long time, it burns on the screen. Screensavers become a must.

I finally picked the Plasma TV, but it was a borderline decision.

The TV is hooked to a Cyberhome DVD player with DivX and a Freeview receiver. The DVD player lets me watch DivX movies I download as torrents. The Freeview player gives me over 40 free channels for casual viewing. (I don’t watch enough TV to need Sky TV.)

I bought an Intel Pentium III Tower that I bought on eBay. This is my “media PC”. I hooked this up to my TV (which has a PC input), a pair of Bose Mediamate speakers (a gift from my brother-in-law) with excellent sound response, and a Labtec webcam.

Two other components I bought were wireless: a Microsoft wireless keyboard and mouse to control the system from my sofa, and a Linksys cordless Skype phone (with a speakerphone), so that I could hold videoconferences on Skype while on the sofa.

Having set this up, I’m truly beginning to appreciate the convenience of wireless appliances. Right now, I can do any of the above things without gettin up from my sofa. My laptop, phone and wireless keyboard are always just a hand’s reach away! Here are some of the things I’ve been doing (wirelessly):

  1. Videoconferencing. I leave the computer on permanently. My parents or in-laws call me on Skype. The cordless phone rings. I can answer Skype calls directly from the phone. When I pick up the call, the webcam turns on automatically. We can sit on the sofa and speak, while they see us. I can turn on the TV and see them through their webcam. It’s a full-fledged wireless video-conference setup.
  2. Listening to radio. I use my laptop to connect wirelessly to my media PC using Remote Desktop, start up WinAmp, and pick a Shoutcast channel (which has a decent tamil channel list). The sound comes through the Bose speakers connected to the media PC, and I can control the volume from any room, using my laptop.
  3. Listening to MP3s. Ditto, except I turn on a playlist on WinAmp.
  4. Watching online videos. I turn on the TV, use my wireless keyboard, and connect to Google Video. Most of the time, I watch recent tamil movies or Google Techtalks.
  5. Watching TV. (Live from BD and ShareVDO being some choices.)
  6. Watching movies. I actually use “low tech” to do this. I record DivX files I download on to a DVD, and play them through my DVD player (which recognises DivX). On those occasions that I download WMV files, I play them through the computer.

With this setup, it’s easy to do more cool things, like a Truman-show like broadcast (which Justin.TV already does).

Hindi songs online

Click here to search for Hindi songs.
This is an article on how I wrote the search engine.

I find it a nuisance to have to go to Raaga, search for a song, not find it, then go to MusicIndiaOnline, not find it, then go to Musicplug.in, and so on until Google.

So I got the list of songs from some of these sites, put it together in one place, and implemented a find-as-you-type.

Just go to s-anand.net/hindi and type a song or movie name.

Update: How I created this is a very long story, spanning over two years. And here it is.


Over the last 5 years, my MP3 collection had grown quite large. Most of these were from MP3 CDs I had bought, songs I’d downloaded, or songs I’d recorded. In any case, the file names were a mess. In early 2005, I decided to organise the collection and put them all into one big directory per language, and name the files in the format “Movie.Song.mp3”.

People think I’m crazy to use a single large directory. But I prefer one directory with 5,000 files to 1000 directories with 5 files for a simple reason. Searching in one directory is easier than in multiple directories. You can just sort everything by name, date modified, size, whatever. On the command prompt, you can type “DIR dil*.txt” to see all movies starting with “Dil”.

I chose the “Movie.Song.mp3” format because the movie name and the song name were really the only two things I knew about every song I had. I didn’t always know the music director, singers or year of the movie. And I placed “Movie” before “Song” because I often browse songs within a single movie, and it’s useful to sort by name in Windows Explorer and see all the songs in a movie. I’ve never had a need to sort by song name. If I wanted to find a song that started with, say, “pehla”, I’d just type “DIR *pehla*” on the Command Prompt. (As you might have guessed, I have a Command Prompt window always open.)

So, having very rationally organised my music collection, I was happy.

Soon the problem shifted to song discovery. I’d heard the familiar songs in my collection many times. Of the unfamiliar songs, but I didn’t know which to pick. I knew I liked some music directors more than others, and had a hunch I liked older songs. (My subsequent analysis of song preferences confirmed this.) But I didn’t know the year or music director for any of my songs.

Since Raaga had a decent collection of songs, along with the year and music director, I decided to download this information and tag my files with this information. There were two problems. Firstly, the data in Raaga needs to be parsed. I need to hunt through each file to find the year and music director. The second was worse: my song names were spelt differently from Raaga’s.

Step 1: download the HTML and parse it. Perl is pretty much the only programming language I know. I used Perl’s LWP library to download the movie index of Raaga. Each movie in the index always has the URL http://www.raaga.com/channels/hindi/movie/something.html. So I extracted these patterns and downloaded all these URLs as well. (Others have a recognisable pattern as well: http://www.musicindiaonline.com/music/hindi_bollywood/s/movie.some_number/, http://www.musicplug.in/songs.php?movieid=some_number, http://ww.smashits.com/music/hindi_film/songs/some_number, etc.)

You probably realise that I downloaded a fair bit of the entire Raaga.com site’s HTML. Actually, it’s not that big. The 800-odd files in the Hindi collection didn’t take more than 40MB of space, and a few hours to download. Here’s what the code looks like:

# Get the list of movies HTML file
my $index = get("http://www.raaga.com/channels/hindi/movies.asp");

# Extract the list of movies from that into a hash (movie, url pairs)
my %movie = ($index =~ m|<a href="/channels/hindi/movie/([^"]*).html" class="[^"]*">([^>]*)</a>|gsi);
 
# Loop through each movie
for my $file (keys %movie) {
  # Get the song HTML file
  my $html = get("http://www.raaga.com/channels/hindi/movie/$file.html");
 
  # Year is typically like this: Movie_Name (1983)
  my $year = ($html =~ m|<b>$movie{$file}\s+\((\d*)\)</b>|) ? $1 : "";
 
  # Music director always has the URL /channels/hindi/music/something
  my $md = ($html =~ m|<a href="http://www.raaga.com/channels/hindi/music/[^"]*" class="black">(.*?)</a>|) ? $1 : "";
  for (split /\n/, $html) {
 
    # Now get individual songs and rating. They always have an onClick="setList(something)"
    if (m|onClick="setList1\((\d*)\)[^>]*>(.*?)<\/a>.*?"http://images.raaga.com/.*?.gif" alt="RATING: ([\d\.]*)"|) {
    $song = $2;
    $rating = $3;
    print join("\t", $movie, $song, $year, $md, $rating), "\n";
  }
}

Incidentally, I’m showing you a simplifed version. I actually wrote the script in a way that I could resume where I left off. The ability to resume was probably the single most useful time-saver in the entire process.

Step 2: match the song names with those on my list. This is tricky. I hate doing it manually. So I developed a set of rules that could compare two spellings of a movie and decide if they were the same or not (see my earlier post on matching misspelt movie names). For Hindi songs and movies, here are my rules (in JavaScript):

w=w.toUpperCase();                      // Convert to upper case
w=w.replace(/\s+/, " ");                // All whitespaces = 1 space
w=w+" ";                                // Ensure there's a space after every word
w=w.replace(/W/g, "V");                 // V=W
w=w.replace(/Z/g, "J");                 // Z=J
w=w.replace(/PH/g, "F");                // PH=F
w=w.replace(/([KGCJTDPBS])H/g, "$1");   // Ignore H after most consonants
w=w.replace(/(.)\1/g, "$1");            // Ignore repeated letters
w=w.replace(/Y/g, "");                  // Ignore Y
w=w.replace(/([AEIOU])N /g, "$1");      // Ignore trailing N after vowel (hein, mein)
w=w.replace(/[AEIOU]/g, "");            // Ignore vowels
w=w.replace(/ /g, "");                  // Ignore spaces

These are the rules, incidentally, that I use in my Hindi quizzes. Even if you type in a different spelling, the rules above will match the correct answer.

I extended these programs over 2006 to cover MusicIndiaOnline, Musicplug.in and Smashits. (I’ve hit a point of diminishing returns, I think, so I’m not too keen on expanding this list.)

Now, with a database of song information, I needed a good media player to view this in. I’ve used several media players over time: WinAmp, Windows Media Player, RealPlayer, iTunes, and MediaMonkey. I’m a big WinAmp fan, but I’ve been forced to Media Monkey now. WinAmp has a 10 second delay before playing any song on my new laptop. MediaMonkey’s not bad, though. The lack of advanced filters is countered by the heavy programmability (I can use Javascript to update MP3 ID3 tags on MediaMonkey). Plus, I get all the WinAmp plugins. As for the other media players, I think they’re junk.

There are five things I want in a perfect media player:

  1. Find as I type. I shouldn’t have to type the entire song, or press a “Go” button. I’ll just type. It should show all matches instantly. WinAmp does this, and that’s why I loved it. (Today, most media players can do this.)
  2. Advanced filters. Instead of manually creating playlists, I’d rather create filters, like “Highly rated songs in the 2000s I haven’t heard recently”. (See How I listen to music.)
  3. Enqueable playlists. When I click on a song, I don’t want my current song to be interrupted. Just play it next.
  4. Global hotkeys. I want to pause the song when someone says something — without having to go to the application, search for the pause button, etc. WinAmp does this brilliantly with its global hotkeys.
  5. Online and offline integration. I want to be able to search online collections, like Raaga. Unfortunately none of the media players can do this. They have their own collections (radio stations, really), but even these aren’t really searchable.

Since my favourite media players (WinAmp and MediaMonkey) lack only one of these features, I thought I might be able to build them in.

But no such luck. It was almost easier to build my own media player. So I started to build my two weeks ago. My hope was to cover as many of my favourite requirements, beginning with find as you type.

The key to find-as-you-type is speed. You can’t afford many calls back and forth between the browser and the server. Even if people have a fast connection, my server is not fast enough. (A good part of the reason why I use Google applications is speed. Google’s server is blazingly fast, and the design of their applications complements that.) To make find-as-you-type fast, ideally the entire database should be loaded. Then, as you type, I just need to check with the database in memory. But downloading an entire database takes ages! (My full music database is 7MB right now.)

Step 3: compress the database. Rathern than load the full 4MB, I managed to get the page to start after loading 100KB of data. First, I cut down less important fields. Most searches are for a song or movie, rarely for a year or music director. So I took only the movie and song names. That brought the data down to ~2MB.

I don’t need to repeat the movie name across songs. If I have something like this:

Movie1  Song1
Movie1  Song2
Movie1  Song3
Movie2  Song1
Movie2  Song2

I can store this instead as:

Movie1  Song1   Song2   Song3
Movie2  Song1   Song2

I can also eliminate duplicate names. This brings down the space requirements to ~500KB.

The next step was the clever one. I don’t need to load the full database before you start searching! It’s enough to load a reasonable subset, and let you start searching while the rest loads in the background. So my hindi song search engine loads about 100KB of the data from one Javascript file, lets you search, and in the background loads the 400KB Javascript file. As soon as that finishes loading, it displays results from that set as well. (The initial portion is really songs on Raaga. I figured it would represent a decent search set.)

Step 4: find-as-you-type. This is quite easy, actually. I send the onkeyup event to my search function.

<input id="inp" onkeyup="csearch()">

The csearch() function goes through all the songs, checks if there’s a match, and prints all those results.

// Create a case-insensitive regular expression
var re = new RegExp(search, "i");
for (var i in songs) {
  if (re.test(songs[i)) { str += songs[i]; }
}
library.innerHTML = str;

But that, unfortunately, takes ages to finish. If you implemented this as is, you would have to wait 1 – 1.5 seconds between each key stroke. So I made two modifications. Firstly, I restrict the number of results displayed to 100. When you start typing, (for example, you’d go ‘c’… ‘ch’… ‘chu’…) there are several songs early on that match the string, so I don’t have to search through the whole list. This speeds up the search for small strings.

When the search gets bigger, (‘chupke chu’… ‘chupke chupk’…), there aren’t 100 results. So the search has to cover the full list, and that takes 1-1.5 seconds between each keystroke. So I took another clever step. I broke the search into chunks of 5000 songs. That takes a fraction of a second. I search successive chunks of 5000 songs. If I find any results, I add them. Then I wait for a keystroke. If nothing happens, I continue searching the next 5000 after 50 milliseconds, and so on. If you press a key in the meantime, I stop searching for the original word, and start searching for the new word. This makes the application appear a lot faster.

There are ways I could make this even faster. For example, people type more often than delete. A typical sequence would be (‘chupke ch’… ‘chupke chu’… ‘chupke chupk’…) rather than the reverse. Backspace is not pressed very often. So, instead of re-searching the whole list, I could just search the already-searched list in such cases. But right now, the search works fast enough, so I’ll leave it at that.

The next step is advanced filters. I’m working on that right now. Hopefully you’ll see in a while.

Statistically improbable phrases 2

My earlier list of statistically improbable phrases in Calvin and Hobbes is technically just a list of “Statistically Improbable Words”. I re-did the same analysis using phrases. Here are the top 20 statistically improbable phrases (2 – 4 words only):

baby sitter chocolate frosted sugar bombs comic books doing homework fearless spaceman spiff() good night hamster huey ice cream miss wormwood new year peanut butter really think slimy girls spaceman spiff stuffed tiger stupendous man sugar bombs susie derkins watch tv water balloon

That is, these are the 2-4 word phrases whose frequency in Calvin and Hobbes is substantially (at least 5 times) higher than in the other books I have.

While doing this, the single biggest problem that stumped me was: what is a word?

  • Is “it’s” one word or two words?
  • Is “six-year-old” one word or three words?
  • How do I distinguish between abbreviations (g.r.o.s.s.) and full-stops without a space ( … homework.what’s a …)?
  • Does a comma always split words? (It doesn’t in numbers, like “3,500”)

The other problem is, phrases with more words are more improbable. Right now, if a phrase occurs 5 times more frequently in Calvin and Hobbes than my other books, I include it. But three-letter words rarely occur that often, and four-letter words even less so. Maybe I should have a lower cutoff for longer phrases.

Anyway, this analysis is a crude first approximation. Clearly Amazon’s gotten much further with their system.

Most bookmarked pages

These are the most bookmarked pages on my site:

  1. My home page
  2. Excel tips
  3. Calvin & Hobbes quotes (I typed them all)
  4. Indian torrents (I have a search engine for Indian torrents)
  5. Tamil Transliterator (Lets you type Tamil in English)
  6. Tamil songs quiz
  7. Movie quote quiz
  8. My best links
  9. Top 10 lists

But this post is not about these links.

It’s about how I found this out.

Think about it… how could I know what pages have been bookmarked? The browser doesn’t send any information about bookmarks.

Some months ago, I moved away from Google Analytics mainly to have more control over tracking visitors. Among other things, I track referrers. When you click on any page and go to another one, the second page knows the first page you came from. That first page is the referrer.

So I know every page people clicked on to get to my site. Usually it’s Google. Sometimes it’s someone’s blog. Sometimes, it’s blank.

The blank referrers either indicate that the browser has blocked the referrer page, or that the person didn’t visit any page before mine. The former is rare (less than 1%). So, realistically, a blank referrer has either the person typed in the URL, or bookmarked it.

To make sure, I did a quick survey over the weekend. Those who came to my page without a referrer saw a survey form, asking where they came from. Almost all of them had either bookmarked or typed my page. The typists went directly to my home page. All the other links you see above are bookmarks.

So all I had to do was count the number of hits for each page with blank referrers. That’s the list above.

Absence of information can be a powerful indicator too.

Google custom search engine

I didn’t realise the power of Google Coop’s custom search engines (CSE) until I watched Scoble interviewing Google’s Shashi Seth. In a nutshell, CSE lets you create a search engine that’s focuses on specific sites, like UK blogs or Photoshop sites

Anyone can create these. You can edit other people’s search engines too. There are a huge number of custom search engines you can volunteer to edit.

I’ve created a bunch of search engines myself:

You’ll find that the Tamil mp3s and lyrics searches are very poor. This is because Google CSE does not show results in Google’s “supplemental index” — which has most of the useful results for MP3 searches. Fortunately Google plans to add supplemental results.

You can improve these searches. Just click on the search link and click on “Volunteer to contribute to this search engine” at the bottom.

PS: I’m working on a books search engine as well, but until the supplemental index is added, there’s not much I can do with it.

Wishlist for movies

I watch a lot of movies. Over the last year, I’ve watched over 250 movies (and read 50 books, but that’s another story). Other than making time to watch movies, my biggest problem is figuring out what to watch next.

The IMDb top 250 is a good guideline, and I’m running my way down the list. Twofifty.org has been useful to track what I’ve seen as well. But I have interests outside of the IMDb Top 250, and I need a way of tracking these.

I started a “to watch” Excel sheet. But there were three problems:

  1. I would forget what the movie was about
  2. I wouldn’t know what to watch next
  3. I’d have to manually delete movies I’d seen

So I wrote a program to do this automatically and create a Movie Wishlist. I just write the names of movies I want to see, and the program finds these movies on IMDb, gets their ratings and links them. It also goes through my “seen” movies and strikes out stuff I’ve seen.

So I can just click on the movie to see what it’s about. I can sort by rating or votes to decide what to see next. And I don’t have to manually strike out anything.

Take a look.

My Fuji Finepix S5600

My digital camera conked off. The cover that holds the battery fell off, and I can’t use it any more.

I went back to my buying principles, and prepared an Excel sheet to choose my next camera. Here’s what I was looking for:

  • Low-light photography. Flashes are lousy. This effectively means I need ISO control.
  • Shutter speed control. I sometimes take really long exposure (3-10s) snaps, and sometimes can’t afford the blur (1/250s).
  • Long battery life. My current camera consumed batteries like crazy.
  • Fast start-up. By the time I got my earlier camera out and it started, it was too late.
  • RAW mode. Gives me more control in Photoshop.

I didn’t care about:

  • megapixels. 2 megapixels (1600×1200) is more than enough, even for my printouts. Takes too much space besides.
  • zoom. I need wide-angle more than zoom, really.
  • removeable lens. I’m not going to carry around multiple lenses.

After scouting around on Amazon for many months, I found the Fuji Finepix S5600. Not an SLR, but had all the features that I wanted, and at a pretty reasonable price.

Fuji Finepix S5600

Here’s a shot I took from my drawing room. This is a 3-second exposure on ISO 100 at F 3.2. The streaks on the road are car headlights.

2006-11-28 01 Newbury Park

As a bonus, it had a pretty good (10X) zoom too. See the brightly lit buildings towards the top-left? That’s Canary Wharf. Below is a blow-up of those buildings from the same spot I took the above photo from.

2006-11-29 01 Canary Wharf

Google search in Tamil

When I wrote my Tamil song lyrics quizzes, I had two problems:

  1. I can’t write in Tamil (not on paper, nor on a computer)
  2. I can’t spell right in Tamil (ந vs ன, ர vs ற)

I overcame the first using a Tamil transliterator. I write in English, and you see it in Tamil.

The problem of ந vs ன was simple. ந occurs as the first letter of a word, and just before த. Nowhere else. (Is this always true?)

But ர vs ற can’t be solved except through experience, and I’m short of that. So, rather than bother my family with every quiz, I used the wisdom of crowds. I googled both spellings of the word. The correct spelling has more Google hits than the incorrect one.

I did this so often, I made a Google gadget out of it.

Just type the word in English, click ‘Search’, and my gadget will search in tamil. It’s amazing how much stuff there is in Tamil on the Web, from song lyrics to texts (thirukkuraL, for example).

You can add this gadget to:

  • your desktop (in the Search Gadgets box, type “http://www.s-anand.net/a/tamilsearchgadget.xml”)
  • your website or blog (click here for the code)
  • Google Reader. Add to Google

Here’s the transliteration table:

Tamil English
a
A or aa
i
I or ee
u
U or oo
e
E
ai
o
O
au
k or g
n
ch or s
j
n
t or d
N
th or dh
n
p or b
m
y
r
l
v
zh
L
R
sh
S
h

Automated resume filtering

I had to screen resumes from a leading MBA school. I’m lazy, and there were hundreds of CVs. So after procrastinating until this morning, I decided on 2 principles:

  1. I will not spend more than 45 minutes on this. (That’s the duration of my train ride to office.)
  2. I will not read a single CV. (I would write a program.)

The CVs were in a single PDF file. I saved it as text (it shrunk from 66MB to 1.6MB without the photos). Then I wrote a Perl program to filter CVs by keywords. We were looking for people with an interest and/or experience in IT consulting, so I picked “technology”, “consulting”, “SAP”, “IBM”, “Accenture”, “Deloitte”, etc.

Anyone without these keywords would fall out of the list. This eliminated 75% of the crowd. But since I didn’t want to read the rest, I used my favourite text-analysis technique: concordance. I extracted 3 words on either side of each keywords, and just read those. It was easy to see who’d “worked with suppliers like IBM” as opposed to who’d worked at IBM.

That’s it! I managed to cut the list down to 10%. Better yet, I also had a preference ranking. People with multiple keywords ranked higher than those with fewer keywords. And all this took little more than my train ride to office.

I can see this going to the next level. It’s easy to write a customised rejection letter, depending on which keywords are missing for each person.

Now, if it’s this easy to filter resumes, I can see every organisation do it in a few years. Which means, you need to write resumes for machines as well, not just for humans! For example, on my next CV, I’ll make sure I include the words “Boston Consulting Group” as well as “BCG” — just in case the software searches for only one of those keywords. Further, I’ll make sure I avoid spelling mistakes!