October 1st, 2006

Ruby wrapper for Yahoo! Browser-Based Authentication

As you probably know we launched Browser-Based Authentication. What this means is that users can grant third-party web-based applications access to their Yahoo! data. (Actually, this could be used for non web-based apps too.) For a more detailed explanation, go here.

Anyway, I’ll explain how this works using the Ruby interface I just wrote and (sorta) tested:

  • Registering your web application: First off, you need to register your web application. After registration you’ll get your appid and shared secret.
  • Logging-in users:

    obj = YBBAuth.new(appid, secret)
    obj.get_auth_url('')

    Once you get the auth URL, direct the user there. Now the user is informed that your amazing web application is asking for permissions (read, write or both) and whether he wishes to grant permission, etc. Once the user grants permission, Yahoo! will redirect the user to your application (you would’ve submitted the URL when registering for an appid).
  • Getting user credentials: When Yahoo! redirects the user, it adds a token parameter to the URL. You need to extract this token in order to get user credentials:

    obj.get_access_credentials(token)

  • Making an authenticated request: Now you can make authenticated GET/POST requests:

    obj.ws_auth_get_request('http://photos.yahooapis.com/V3.0/listAlbums')

    The above snippet makes use of the Yahoo! Photos API.

» The Ruby wrapper

The interface isn’t complete or well-tested (I have a flight to catch in a few hours so I need to leave in a bit). I’ll work on it in a day or two.

Posted at 10:15 pm | Link | 25 comments | Leave a comment

September 22nd, 2006

YDN Ruby

Alright, long time. Long story for some other day. I have been posting stuff to Flickr, though.

Just wanted to let you guys know that we just went live with the Ruby Developer Center on the Yahoo! Developer Network. If you’ve hacked something in Ruby that makes use of Yahoo!’s web services, let me know. Of course, let me know if you have any feedback.

Official post on the YDN blog.

Tags: , , ,
Posted at 12:53 am | Link | 12 comments | Leave a comment

August 1st, 2006

Unmemoize

I tried to add an unmemoize function to the memoize module I talked about earlier:

module Memoize
   def memoize(func_name)
      cache = {}
      (class<<self; self; end).send(:define_method, "#{func_name}u", method(func_name).clone)
      (class<<self; self; end).send(:define_method, func_name) do |*args| 
         return cache[args] if cache.has_key? args
         cache[args] = super    
      end     
   end
   def unmemoize(func_name)
      (class<<self; self; end).send(:define_method, func_name) do |*args| 
         eval(func_name.to_s+"u(#{args})")
      end     
   end
end

So now you can memoize a function and then, at a later point, unmemoize:

def fib(n)
   return n if n < 2
   fib(n-1) + fib(n-2)
end

include Memoize
memoize(:fib)
...
fib(15)
...
unmemoize(:fib)
...
fib(15)
...

It works — in that the function actually unmemoizes, but the function takes noticeably longer than the original function. There’s definitely something I’m not doing right — I don’t know what though.

Anyway, it’s been a long and tiring day. Later.

Posted at 01:23 am | Link | 11 comments | Leave a comment

July 24th, 2006

Memoize

MJD was talking about Memoize. Here it is in Ruby:

module Memoize
  def memoize(func_name)
    cache = {}
    (class<<elf; self; end).send(:define_method, func_name) { |*args| 
      return cache[args] if cache.has_key? args
      cache[args] = super     
    }       
  end     
end

There’s a lot of code in the Perl Memoize module; maybe it does other things—I haven’t really looked. Oh, and here’s this Memoize module from RAA. I’m some months late. :-)

Here’s some pictures from Portland.

Posted at 03:15 pm | Link | 7 comments | Leave a comment

June 12th, 2006

RubyKaigi


RubyKaigi
Originally uploaded by ma2.
Somebody please send me a RubyKaigi tee!
Posted at 08:55 pm | Link | 9 comments | Leave a comment

June 5th, 2006

What’s playing

I play all my music from iTunes now (most of it is on my FreeBSD box, though, served using mt-daapd). Anyway, time to update my current song script:

#!/opt/local/bin/ruby

require "rubygems"
require "net/ssh"
require "net/sftp"

script = <<SCRIPT
        tell application "iTunes"
                set {art, nm} to {artist of current track, name of current track}
                set disp to art & " - " & nm
                if disp is "" then
                        set disp to current stream title
                end if
                return disp
        end tell
SCRIPT

song = `osascript -ss -e '#{script}'`.chomp

exit if song == ""

`convert -fill black -pointsize 12 'label:#{song}' curr_song.png`

Net::SFTP.start("<host>", "<username>", "<password>") do |sftp|
        File.open("songs.txt", "a") { |f| f.write "#{song} (#{Time.now.to_s})\n" }
        ["songs.txt", "curr_song.png"].each { |file|
                sftp.put_file(file, "public_html/journal/#{file}")
        }       
end

Yeah, that’s a bit of AppleScript in there.

I’ve set it up to run every ten minutes. It also generates a list of all the songs I’ve played. I can probably use that data to figure not-so-useful patterns.

Posted at 06:19 am | Link | 17 comments | Leave a comment

May 30th, 2006

UpcomingFS

I like to use the terminal when I can. Presenting UpcomingFS—access upcoming.org event information:

[ppillai@renegade ]$ ./upcomingfs.rb /tmp/fuse/ &
[1] 10700
[ppillai@renegade ]$ cd /tmp/fuse
[ppillai@renegade fuse]$ ls -1 texas
66002 - Nine Inch Nails
74539 - Suds on Sixth
77608 - Exposure Dallas - See and be seen.
77609 - Exposure Dallas - See and Be Seen.
[ppillai@renegade fuse]$ 

You can also view events in a city within a state (it doesn’t seem to work very well, though):

[ppillai@renegade fuse]$ ls -l massachusetts/boston | grep BarCamp
71709 - BarCamp Boston
[ppillai@renegade fuse]$ 

To view an event's details:

[ppillai@renegade fuse]$ ls -1 massachusetts/boston | grep Band
79932 - Live Band Karaoke - Beatles Night!
[ppillai@renegade fuse]$ cat 79932

Live Band Karaoke - Beatles Night!
==================================
                 
The Milky Way is hosting a special Beatles theme at the first and best Live Band karaoke night in Boston.

Sing the Beatles backed by a live band!

Prizes for best song and best costume.
No cover, as always.
22:00:00 to 01:00:00, 2006-05-30 to 
[ppillai@renegade fuse]$ 

To unmount the filesystem:

[ppillai@renegade fuse]$ cd..
[ppillai@renegade tmp]$ fusermount -u /tmp/fuse/
[ppillai@renegade tmp]$ 

Get the code here. You’ll need fuse and the ruby bindings. (I just got a Linux box; it’s got to be of some use other than writing Java.)

Posted at 06:13 pm | Link | 11 comments | Leave a comment

May 13th, 2006

Comparing eating out patterns in different cities: normalized graph

I normalized the data (see earlier post). Readable? Got suggestions on how to improve?

I ditched rgplot and instead used Gruff (wraps RMagick which wraps ImageMagick). Installation is pretty straightforward. However, I faced a problem with installing ghostscript on my OS X box. Something in the portfile is broken or something. Anyway, you might need to comment the following lines in the ghostscript portfile (typically something like /opt/local/var/db/dports/sources/rsync.rsync.darwinports.org_dpupdate_dports/print/ghostscript/Portfile):

[...]

debc62758716a169df9f62e6ab2bc634 aj16.tar.Z md5
b24ac1b6966adf3a92edaae42eda662c ag14.tar.Z md5
f9cad1b32e56f65339da26266f568e97 ac15.tar.Z md5
a9d876f28dde1d4a0a6571eb0e281761 ak12.tar.Z md5

[...]

default_variants +aj16 +ag14 +ac15 +ak12

Posted at 04:57 am | Link | 43 comments | Leave a comment

May 7th, 2006

Comparing eating out patterns in different cities

If there’s a city you’d like to see in the comparison, let me know.

Posted at 02:41 pm | Link | 15 comments | Leave a comment

May 4th, 2006

People in Bangalore like to eat out on Sundays

Interestingly, folks in Bombay seem to like eating out on Tuesdays:

Notes:

1. Most people seem to end up using the tag “hotel” when they really mean to use “restaurant”, so I’ve gone with the former.
2. I rely on Flickr photo data and my program. You don’t have to take the graphs seriously.

Here’s the script I wrote to draw that graph (requires flickr.rb and rgplot):

#!/usr/local/bin/ruby18

require "../flickr"
require "gnuplot"

API_KEY = "078be2728a42f4e8228f2c2b8c9b6cca"

flickrObj = Flickr::Flickr.new(API_KEY, "")
photosObj = Flickr::Photos.new
days = Hash.new { |h,k| h[k] = 0 }
photosObj.search(["#{ARGV[0]}","hotel"], "all", 0, 1000).each { |ele|
	if /([0-9]+)\-([0-9]+)\-([0-9]+)/.match(photosObj.get_info(ele)["date_taken"])
		begin
			t = Time.mktime($1, $2, $3)
			days[t.strftime("%a")] += 1
		rescue
		end
	end
}
Gnuplot.open do |gp|
	Gnuplot::Plot.new(gp) do |plot|
		plot.title  "Photos taken in restaurants in #{ARGV[0]}"
		plot.ylabel "No. of Photos"
		plot.xlabel "Days"
		i = 0 
		plot.xtics("("+days.keys.map{|ele| "'#{ele}' #{i;i+=1}"}.join(",")+")")
		plot.data << Gnuplot::DataSet.new([(1..7).to_a, days.values]) do |ds|
			ds.with = "linespoints"
			ds.notitle
		end
	end
end

Usage: ./eating-out.rb city_name

Enjoy!

Posted at 08:19 pm | Link | 5 comments | Leave a comment

March 30th, 2006

Export Firefox Bookmarks to Safari

Firefox on OS X sucks. Big time. I decided to move to Safari, but I couldn’t do that without exporting my bookmarks. Here’s how I did it:

The Firefox bookmarks is in an HTML file. It’s typically located at ~/Library/Application Support/Firefox/Profiles/<profile name>/bookmarks.html. Safari stores its bookmarks at ~/Library/Safari/Bookmarks.plist, which is a binary file.

Use this simple script to export your Firefox bookmarks as a readable XML, and follow these steps:

renegade:~ $ ruby ff2safari.rb  > ~/Library/Safari/Bookmarks.xml
renegade:~ $ cd ~/Library/Safari/
renegade:~/Library/Safari $ mv Bookmarks.plist Bookmarks.plist.backup
renegade:~/Library/Safari $ plutil -convert binary1 -o Bookmarks.plist Bookmarks.xml

Note that this script simply dumps all your Firefox bookmarks in Safari’s Bookmarks Bar. (I have a very few bookmarks on my browser, most of which are in the Bookmarks Toolbar.) You could use an XML parser to export bookmarks as is. To understand the format of the XML you need to generate, you might want to export the existing Safari Bookmarks file to XML:

renegade:~/Library/Safari $ plutil -convert xml1 -o readable.xml Bookmarks.plist

One interesting thing to note: a ktrace/kdump on Safari didn’t do any open on Bookmarks.plist. I wonder why.

This post brought to you from Safari.

Posted at 02:34 pm | Link | 14 comments | Leave a comment

March 10th, 2006

Wien

I’m not doing well at all (terrible throat, thus cold, thus headache, etc.), so no Vienna post.

Well, sort of.

That’s not a single image; each square is a CC-licensed image from Flickr. Click on any of the squares to go the that image’s photo page. (If this wasn’t LiveJournal I probably could’ve thrown in some JavaScript magic.) Generated using this badly written script. (Requires flickr.rb.) Basically, you can supply it a word, tags for the word (some color, for example; in this case it’s “blue”), and tags for the surrounding spaces (in this case I’ve inserted a specific image).

Blah.

Posted at 02:04 am | Link | 7 comments | Leave a comment

February 20th, 2006

Lookie!

Ruby-GTK Uploadr running on OroborOSX on Mac OS X Tiger. Of course, it doesn't feel native, but at least better than vanilla xorg. I should probably try playing around with GTK+OSX.

Posted at 07:26 pm | Link | 3 comments | Leave a comment

February 16th, 2006

Flickr Uploadr on OS X

So I finally managed to get my GUI Flickr Uploadr to work on OS X. It was not easy installing ruby-gtk2 in that I had lots of dependency issues. The issues were mostly with atk, gdkpixpuf, and glib. At first, I tried installing GTK2 using Fink. It failed because of GCC issues with glib (I think), which I later figured was because of a problem with pkg-config. I ditched Fink, and used DarwinPorts. Things were good.

After that, I had GTK initialization issues, which was because I hadn’t exported DISPLAY (to 127.0.0.1:0; thanks, Gopal!).

I couldn’t use my old code as is because the Ruby-GTK2 bindings on my FreeBSD box is an older version. (I’ll put the code up sometime later. And maybe also try to document some poorly documented Ruby-GTK2 stuff like Gtk::TextView, Gtk::TextBuffer, etc.) So, it works, but not perfectly:

Ruby-GTK Uploadr running on OS X

Yeah, it looks horrible, but then I&rsquo'm not going to play with it on OS X again—I just wanted it to work.

Oh, by the way, Google Talk is *love*!

Posted at 01:39 am | Link | 9 comments | Leave a comment

February 8th, 2006

Flickr Uploadr

I normally use the command-line Flickr uploader. Just hacked this up for GUI-inclined folks. Also, I’m not much of a desktop guy—“the web is the desktop”—so, yeah, just playing around. The code is here. Requires the Ruby API and Ruby-GTK. (The Ruby bindings for GTK are nice to work with, by the way.)

Doesn’t look very good, etc. I’ll probably try to improve on it.

While looking for pictures to test with, I found a picture of one of my college friends—she with the ocean behind her. There’s something about that picture that makes me smile. That’s my wallpaper for now.

Posted at 05:07 am | Link | 14 comments | Leave a comment

January 29th, 2006

When Code Flows Like Poetry

It’s not always that you get to solve complex problems. Many a time you need to implement something—something that you know is silly enough. How do you feel? Bored, I know. However, there’s small amount of joy you get when the “tool” you use lets you be creative. (Of course, there’s a distinction between the larger problem at hand and the smallest implementable part of it; it is the typically joyless implementation of this small part that I’m talking about.)

I had a situation where I had to read a data file that had on each line data like thus:

foo:bar

Obviously, you want to hold all that data in a hash. Implementing this in a typical programming language would, in pseudocode, look something like thus:

data = file("data.txt").read
hsh = {}
foreach line in data do
        k, v = line.split(":")
        hsh["k"] = v
end

Simple enough, but boring too. With Ruby, I can play:

hsh = Hash.new
File.open("test.txt").readlines.each { |line|
        hsh = hsh.update(Hash[ *line.split(":").
                map { |ele| ele = ele.match(/(.*)\n/)[1] rescue ele }
        ])
}

The Ruby code flows like poetry. Literally. There’s an extremely elegant solution, like why pointed out to me:

Hash[*IO.read('test.txt').scan(/^(.+?):(.*)/).flatten]

But then I’d say there are no blocks there. :-)

There are many such Ruby gems scattered all around. I’ll point you to some of them I found on RedHanded:

Go use a better tool, if you can.

Posted at 03:27 pm | Link | 18 comments | Leave a comment

January 6th, 2006

Command-line Flickr Uploadr

I had written a command-line script to upload photos to Flickr, but it used the old auth mechanism. A couple of days ago a co-worker pinged me because he was having problems getting auth to work. I realized I never cared about the web auth. I’ve extended the code to allow for that now. Apart from that I did some cleanup, etc.

And since the old auth no longer works, I’ve hacked up a simple script to upload photos to Flickr. (You’ll need the API too, of course.) Using it:

./flickr-uploadr.rb path/to/images/dir/ tag1,tag2,tag3

Hope someone finds it useful. :-)

Posted at 07:59 pm | Link | 4 comments | Leave a comment

January 5th, 2006

Shalom!

My visa for Israel just came through. I’ll be speaking at OSDC::Israel::2006. 26-28 February. Larry Wall will be there, and so will Audrey Tang (of Pugs fame). Should be fun. (All this assuming I’m not terribly bogged down with work.)

I’ll maybe speak to Larry about Perl and Ruby and all that stuff if I get a chance. ;-) You Ruby guys, anything you’d like me to ask Larry?

Need to apply for my Schengen visa now, as I intend to spend the weekend in Vienna.

Posted at 07:45 pm | Link | 28 comments | Leave a comment

December 11th, 2005

Kayak

I have been using Kayak for planning an upcoming trip. It’s awesome. It’s got all the Ajaxy goodness you want. Simply brilliant.

And there’s more interesting stuff:

[...]

Perl, of course, is the great do-everything of scripting languages. It is not exactly elegant, but it is supremely powerful in qualified hands.

We've started to do some work which we might normally do in Perl with a newish language called Ruby. I'm all smitten with Ruby: it has much sexier object-oriented structure than perl. I'm thinking of asking her to the prom. Don't tell my wife.

[...]

Posted at 10:53 pm | Link | 6 comments | Leave a comment

November 1st, 2005

Yahoo! Hacks, and other (unrelated) things

Yahoo Hacks

Yahoo! Hacks was released some days back. I got a copy while I was in Sunnyvale (thanks, Paul!). And there’s one that arrived in Bombay too. Sweet.

(In case you don’t know, and didn’t read Paul’s entry: I contributed two hacks to the book — one on Ruby, and another one on REBOL.)

Go, get yours!

Other things

Hong Kong is sweet. Too bad I couldn’t meet Cecily. After having lunch with some of the Yahoo! HK folks, I headed to the airport. I reached there at about 15:30 or so; my flight was at 16:00. I thought I’d reach easily and all, but gate 70 was like at one end! Anyway, I reached the gate at 16:10 — that’s ten whole minutes past the departure time. Interestingly, there was some problem starting the engine or something, so I made it! :-) Haha.

After I reached Bangalore, I wait at the baggage claim for an hour or so with no sign of my baggage. A few more minutes and there’s no more baggage from that flight (TG 325 from Bangkok). Yay, you couldn’t screw me up better, suckers! I was hoping to fly to Bombay tomorrow (err... that’d be today now), but thanks to all this baggage crap, that won’t happen.

The other day, my dad was telling me something about a domestic airline called “Go Airways” or something like that. Heard of it? Got a URL?

Posted at 04:59 am | Link | 11 comments | Leave a comment