Friday, December 14, 2007

Learning Ruby from Python

I just started to pick up Ruby today (to install: sudo apt-get install ruby irb ri rubygems). Here are some things I learned along the way, coming from a Python mindset. The (very good and highly recommendable) references I looked at were (in order):
  1. Ruby in Twenty Minutes
  2. To Ruby From Python
  3. Ruby Essentials (free, on-line book)
  4. Important Language Features and Some Gotchas
  • Brackets for arrays, braces for dictionaries (called hashes in Ruby)
  • Strong dynamic typing
  • Everything is an object, variables are just references
  • Exceptions are similar
  • No special line termination characters
  • # for single line comments
  • def to define a method, class to define a class
  • Interactive prompt: python => irb
  • Interactive prompt help: help(str.count) => help "String#count"
  • Interactive prompt reload: reload(foo) => load "foo.rb"
  • Command line docs: pydoc => ri
  • File extension: .py => .rb
  • Shebang line: #!/usr/bin/python => #!/usr/bin/env ruby
  • Indentation and blocks: : and tabs => either { } or end
  • Strings: immutable => mutable (can use freeze method for immutability)
  • Naming conventions: unenforced => enforced (ex. class names start with a capital letter, variables start with a lowercase letter)
  • Raw strings: r"blah" => 'blah'
  • Parantheses: mandatory => sometimes optional
  • Booleans: True, False => true, false
  • Null value: None => nil
  • Else-if statement: elif => elsif
  • Module import: import foo => require "foo"
  • Boolean conversion: 0, False, None and anything empty => Only nil and false
  • Doc generation: docstrings below things => regular comments above things
  • Output: print => puts (or print if you don't want a trailing newline)
  • Command line execution: python -c => ruby -e
  • Global Variables
  • Ranges: range(x,y) => x...y exclusive, x..y inclusive (.to_a to return array)
  • Slicing: arr[1:3] => arr[1...3] or arr[1..2] (inclusive)
  • Object initialization: __init__ => initialize
  • Object creation: a() =>
  • Ternary operator: if_true if statement else if_false => statement ? if_true : if_false
  • Substring matching: 'foo' in str => str['foo']
  • "Main": if __name__ == '__main__' => if __FILE__ == $0 ... end
Philosophical differences
  • Attribute access: direct access => method calls
    • Need getter and setter methods to access attribute outside class
  • Access permissions: convention by underscore => public, protected, private
  • Multiple inheritance: allowed => mixins
Stuff Ruby has that Python doesn't
  • Double quoted strings allow expression substitution #{} and escape sequences \t\n
  • You can re-open a class at any time and add more methods
  • Block comments: ==begin and ==end
  • Special variable characters (begins with...):
    • $ global
    • @ instance
    • [a-z_] local
    • [A-Z] constant (triggers warnings when reassigned)
    • @@ class
  • Arrays support some set operations
    • difference -
    • intersection &
    • union |
  • Method conventions (ends with...)
    • ! changes internal state of object
    • ? returns boolean
  • do keyword -- optional loop keyword (unless on single line)
  • Crazy for loop alternatives
  • General delimited strings
  • Case statement
  • Lots of options for string element access and string substitution and insertion
  • Regular expressions as first-order objects
  • Perl-like control flow constructs that can be tacked onto the end of an expression

Tuesday, December 11, 2007

"Why don't you write a Facebook Application?"

There is a lot of hype surrounding the newly released Facebook application platform. Developers are falling all over themselves to get a product rushed out the door, funding for Facebook apps is flowing in from VCs and you can even take a class in Facebook application development at Stanford. Amid all of this irrational exuberence, I find myself frequently getting asked why I don't write to it. Well, there are a lot of good reasons to stay as far away from the platform as possible. It's proprietary, unpredictable, not a level playing field in the least and crowded with unworthy offerings. My time and effort is much better spent somewhere else.

First of all, even if we assume for the sake of argument that I am interested in developing a Facebook app, the deck is stacked against me. Tim O'Reilly points out that there is a steep drop off in users after the first four or five most popular apps (the graph on O'Reilly's page is instructive). There are a few reasons for this. The first is that the door has largely closed on the willingness of users to add new applications or suggest them to their friends; the fad has come and gone. In other words, "[W]e must acknowledge that ... users have grown accustomed to a small subset of applications available to all users, and the exploratory period has come to an end... Facebook is all about communicating an image of yourself to your peers, and unless someone creates a truly captivating, innovative, or better F8 application, no one is going to adopt it on a whim." The quickest functional and moderately compelling apps to get out the door were the ones that users pounced on. The second reason for the disparity in users parallels the disparity in the finances and professionalism of the makers of the apps. Five of the top six apps right now are made by just two companies: Slide and RockYou!. [A] Making little flash widgets is essentially these companies' entire business and both of them are well financed. Amateur developers do not stand a chance against a small army of VC-backed Flash coders who do this for a living. [B] Any entry into the Facebook app market now is essentially futile.

The survivability of the Facebook platform is another issue. It bears some eerie similarities to "walled garden" initiatives past. Perhaps most illustrative is the case of AOL, whose proprietary platform, of course, nobody uses anymore. Should I really bother developing against a technology predicting that it won't survive 10 years? Perhaps, but I would rather write to a platform that is built on open standards. Jason Kottke explains: [E]
As it happens, we already have a platform on which anyone can communicate and collaborate with anyone else, individuals and companies can develop applications which can interoperate with one another through open and freely available tools, protocols, and interfaces. It's called the internet and it's more compelling than AOL was in 1994 and Facebook in 2007.
The fact that Facebook could change its platform or go out of business at any time is a disincentive to write a Facebook application. I don't like my creations functioning at the whims of Facebook or its investors; it's a better bet to go with an established, open platform.

I ran across a similar post on Facebook app suckiness that raised an additional reason not to develop a Facebook app. If, against all odds, your application is truly innovative and distinguishes itself in the crowd of petty profile pollution, you still are on Facebook's turf; that carries some important consequences. Specifically, Facebook could copy your idea with a feature that they subsequently build in to Facebook itself. It will be accessible to all users, not just the ones that choose to add it as an application, and there will be no use for your app anymore. Facebook could take your idea and reimplement it, thus sucking away all of your users, and there would be nothing you could do about it.

Then there is the embarrassing stigma of being in the company of Facebook application developers. The (many) applications are written by developers who want to jump on the Facebook hype bandwagon. Most of them are amateurs, and it shows. Take the Quizzes application, for instance (ranked 14th in most active users, so a reasonably popular app). It lacks basic functionality that one would expect in such an application: namely, the ability to see the correct answers after you take the quiz. It also creates a quiz that other people can take before you even indicate you are finished adding questions! Furthermore, I couldn't access the application at all today because, presumably, it is choking under the load that Facebook is sending to it (another all-to-frequent problem of these applications). Quizzes, admittedly, might be an application that one might use occasionally. I can not say the same about other applications, most of which can be broken down into four categories:
  • Horoscope
    • What flower are you? -- "Are you rose, lilly, foxglove, daffodil, nigella, sunflower, violet? Find out."
    • Birthstones -- "From the time gemstones were discovered, they were believed to have mystical powers and attributes that could be passed to the wearer. The red of ruby was fiery and passionate; cool blue sapphire was calm and composed. What's yours?"
    • Psychic Breeze - Psychic Readings and Fortune Telling -- "Accurate psychic, psychic medium and clairvoyant readings are available today. Our extraordinary psychics, mediums and clairvoyants use their psychic ability to provide you with guidance in relationships, love, finances, and other life hurdles."
  • Decorative trinkets
    • Snow Globe Gifts -- "Snow Globe Gifts! Send your friends realistic, shakeable, snow globes..."
    • Christmas Music Tree -- "Create your own special Christmas Tree. Decorate your tree with your friends and make them play many famous Christmas songs. It's your Musical Christmas Tree."
    • My Fab Bag -- "Buy and give your friends designer handbags. Choose your favorite to carry and display on your profile."
  • Finding a boyfriend
    • Likeness UNRATED -- "Find out who you're like on mature topics like purity, vices, and the seven deadly sins. Can you find a perfect match?"
    • Will you KISS me? -- "Send kisses to loved ones, lovers, romantics, mistresses and everyone! Ever wanted a friend or crush to kiss youand find that they want to kiss you too What if it happens on a Full moon night? Give and take kisses"
  • Just good ol' pestering people
    • Zombies -- "Bite your friends and make them zombies! Mmmmm... Brains! Also - you can fight Zombies, Vampires and Werewolves now!"
    • Vampires -- "From the makers of Zombies comes Vampires! Kind of like Zombies. Except that the vampires are hot. VERY hot. Also - you can fight Zombies, Vampires and Werewolves now!" [C]
    • X Me -- "Tired of just poking? X me opens up a whole new world of action-based messaging, for example 'Hug Her, Slap Him, Tickle Them!'"
Is this trash what I really want to spend my time developing? Do people actually waste their time using this filth? It's depressing that humans' frontal lobes have not yet developed sufficiently to resist soliciting the advice of fortune-teller applications. [D] Given this kind of crowd, I don't think I could expect anyone to take me seriously if I told him I was developing a Facebook application. I would anticipate him laughing in my face.

That's why I don't develop for the Facebook platform: it's pure hype. Nothing of significance has been produced in the form of a Facebook application, and the only applications that get any views are ones that are made by companies who specialize in them. This environment exists at the whim of Facebook and its investors, and could come crashing to a halt if the business goes belly-up or Mr. Zuckerberg has a change of heart. I'll take my code somewhere else, thank you very much.


[A] Prepare for some awful, awful music and graphics if you go to RockYou!'s page. I had the displeasure of being aurally assaulted by Lil' Mama blowing kisses at me. You have been warned.

[B] To hammer this point into the ground, RockYou!'s CEO discusses here how, in order to prepare for an expected spike in traffic, they ran around filling a 24-ft truck full of servers and hooking them up over a weekend. Does this sound like the kind of thing you could pull off with the change you found under the sofa? I didn't think so.

[C] "From the makers of Zombies..." As if Zombies was a fantastic, useful product to stake their reputation on. They have WereWolves, too. Maybe there's more, I didn't care to look.

[D] And there's a hell of a lot more dumb applications, if you want to take a peek.

[E] He expands on the "Facebook as AOL" theme in this post. Scott Rosenberg also has his thoughts on the subject.

Why I am Still on Facebook

Facebook sucks. And yet, I can't bring myself to terminate my account. It has a few essential features that I just could not do without because of its dominant position as today's preeminent social platform. Like the AOL of yesteryear, everyone else uses it (a bit too much) and expects you to use it to communicate with them. These few communication and sharing features are the site's strengths. Facebook counts on users sticking around in order to use these features regardless of how many ads they plaster on their pages or how many privacy violations they can rack up. Facebook's flaws are outweighed by its utility, which is why I haven't quit Facebook... yet.

Facebook's best feature is what it started out as: a directory of contact information. The average person does not have the time, skill, interest or money to register a domain name, set up a personal web page and push it to the top of Google's index for searches against his name. A social networking page is a much more convenient way to disseminate contact information. Facebook is the best solution for this because it shares contact information only with people of which the person approves. This arrangement makes many more comfortable than if they had shared their contact information on a public site such as MySpace. As Facebook also started out as a college network about the time that I was in college, it is the platform of choice of virtually all the people I would desire to contact. Most of the time, the aggregate contact information for someone just starting their professional life is not available anywhere else. I can not count the number of times when I quickly needed to contact somebody, only to realize that I did not have her AIM screen name, email address, phone number, etc and fetched the information off Facebook.

The other killer feature of Facebook is photo sharing, which is why it is now the largest photo sharing site in the United States with over a billion pictures. If I were to withdraw from Facebook, I would no longer have access to my friends' photos and they would no longer have access to mine. Of course, I could always migrate all of my pictures to Flickr or some other site and then point all my friends there. But is it really worth the time and effort to do that, knowing that Facebook already has a great framework for doing this that my friends and I currently use? Again, Facebook's privacy controls are also an important feature: if I transitioned to another platform, I would need to re-implement the privacy controls there (assuming they were even supported!). Additionally, all of the tag data and comments that Facebook supports would be lost in translation.

And let us not forget the networking part of social networking. Facebook does provide opportunities to network, in the business sense. [A] It's easier to approach a person if he looks familiar, you have some background on him and you can draw from a number of topics of conversation. Also, even if the only contact two people have is seeing each others' name go by on their respective News Feeds and having the other's face pop up once in a while on sample friend lists, that connection is sufficient to leave a lasting impression on the subconscious mind. [B] And requesting someone to be a friend on Facebook can be sometimes interpreted as a digital 'good meeting you' compliment. In spite of all this, I believe the networking aspect of Facebook to be a relatively minor incentive for staying on the site.

So photos and contact information are really the only two things that keep me from ending my adventures with Facebook. For the time being, it seems that I'm just going to have to swallow my pride, eat my words and keep using the site.


[A] "Expanding one's social network or sphere of influence by initiating mutually advantageous new relationships with people." (link)

[B] I didn't come up with this theory, my friend Monique did.

Monday, December 10, 2007

Facebook Sucks

Every time I sign on to Facebook, a little part of me dies. Not only am I usually wasting my time, but I am allowing Facebook to violate my privacy, potentially offending hundreds of "friends" and being bombarded with ads and spam. Furthermore, I am forced to use Facebook's clumsy tools to communicate with others on Facebook who seem to never have heard of email, all while wading through the ostentatious posturing of Facebook's users. In short, Facebook sucks.

Facebook is a great opportunity to offend people. As if I didn't have enough trouble minding my etiquette in the real world, the choice to friend or not to friend (or grant restricted access, or defriend) provides daily chances for someone accidentally or intentionally insult someone else. The heart of the problem is that some people have different conceptions of what a Facebook friend actually entails. Does it mean you are friends in real life? Is it meaningless? Some are willing to Facebook friend total strangers and others keep a very small circle Facebook friends that might actually be closer to the number of good friends they have in real life. There is a point at which this managing of digital networks becomes tiresome, evoking a social network fatigue. The value of a particular user's experience on Facebook (or on any social network) rises and then falls as the number of users increases. [B] At first, the user is excited to connect with all of his friends and perhaps reconnect with some that he had lost touch with. But over time, as more people join the site, more time is spent on fending off unwanted friend requests and friend network management. This eventually drives the user to become much less active on the website, if not to opt out of it completely.

Facebook is a black hole that sucks up time. There is certainly something compelling about browsing your "social network" through a hyperlinked photo yearbook. In fact, it's too compelling -- some have complained of "Facebook addiction." Facebook exacerbates this problem (well, certainly not a problem for them) by sending you incessant reminders of activity on your account by default ("Someone has done x to you on Facebook") which pull you back to the site again. [A] Apps have worsened this addiction because now every app requires its own micro-management and sends its own messages to your inbox. Here is a picture of the overwhelming number of annoyances a typical Facebook user might face upon login. All of the time spent on Facebook wouldn't be wasted if there was substantive communication taking place on the site but, for the most part, there's not. It's all just about how many people you've converted into zombies or whether you identify more with pirates or ninjas.

Facebook reinvents the wheel in a variety of ways, moving online communication a step backwards. Since Facebook wants you to stay within the site's walls, Facebook provides tools for you to accomplish certain goals, no matter how mediocre those tools may be. For example, Facebook provides a "Marketplace" for users to buy and sell items on their site. Of course, there are many superior auction/barter/market sites already on the Internet:, eBay and Craigslist, to name a few. Facebook provides "Posted Items" and "Notes," whose features are poor substitutes for nearly any blogging platform. And Yahoo and Google groups are many times more advanced than Facebook's groups. The most irritating example of Facebook's compulsive re-engineering is Facebook messages -- it reminds me of a dark age when GMail didn't exist, and also gives me another inbox to manage (much more clumsily, mind you).

Twice Facebook has disregarded its responsibilities to its users and precipitated privacy invasions, both for which Zuckerberg promptly issued apologies. First there was the News Feed, which broadcasted users' actions to all of their friends. Facebook followed that with Beacon, a system that tracked a users' actions on affiliate sites, such as the New York Times, and then fed information back to Facebook (and that users' friends through the News Feed) about a users' behavior. Twice Facebook has recklessly played fast and loose with its users' data, and twice it has pushed its audacity to the limit until it faced a revolt by its users. The most shocking part of this whole story is that these systems never went away! In each instance Zuckerberg waved his hands to make an apology, as if users' concerns had been assuaged, and only partially disabled the systems that caused the uproar. The News Feed, although it did get some controls, still doesn't give the user a choice if some types of stories are broadcasted. Beacon is also wholly intact, but was changed from an opt-out to an opt-in system. [C] There is no reason to think this is the last time this pattern will happen, as Scott Rosenberg points out. To justify its massive valuation, Facebook is under a lot of pressure to find additional ways to monetize its service, and there is good money to be made selling out users. What privacy-infringing "feature" will Facebook be pressured to invent next? [D]

And then there are ads -- lots of ads. In addition to the easily blockable banner ads on the bottom and sides of the page (an Internet staple since as far as I can remember), Facebook has devised ways to deliver ads to users that are not so trivially thwarted. Facebook actually embeds ads inside the News Feed that come from the same server as the rest of the News Feed, unlike other embedded ads (like Google's) which come from a third-party server and are thus easy to identify and block. Fortunately, there are some ways to rid your eyeballs of these menaces. It is also much harder to tell that you are looking at an ad in the news feed: Facebook blends them in so well to almost make them indistinguishable from bona fide News Feed stories. This approach is in stark contrast to what Google and other sites do, clearly identifying which content is sponsored and which content is not. This practice is irritating at best and deceptive at worst.

And speaking of deceptive ads, how about using my image in an ad for a sponsor, as if I were sending a personal recommendation to a friend? Taking a "social action" (as Facebook puts it) is not a license to use me as a viral marketing stooge for Blockbuster, et al. [I] To add insult to injury, Facebook is now allowing advertisers to send targeted emails directly to your Facebook inbox (the first line of the most recent one I received from "Hey College Hoops Fan!"). Hm, unwanted emails in my inbox trying to sell stuff; I think that's better known by its more conventional name -- spam. You spam your "friends" with application requests, corporations spam you with messages in your inbox, your "friends" spam you with pokes and news feed items. This is essentially what Facebook has become: a very efficient platform for spamming people.

You can put a lot of data in to Facebook, but getting that data out is an entirely different story. It is quite easy, for example, to import your contacts from another platform into Facebook. Facebook, however, provides no convenient method for exporting those contacts into Outlook, Gmail, or the other social network flavor of the week. The same goes for photos, videos and all other multimedia. Looking for a "backup my photos" link? Sorry, it doesn't exist. There are ways to get data out of Facebook, but they are inconvenient and few. One is to use the API either by writing an app yourself (clearly out of the reach of most users) or using an application like FriendCSV [K]. The API, however, doesn't allow extraction of some types of information, like email. Another is to scrape the site, which is against the terms of use (like most companies') and can lead to the termination of your account if they catch you doing so. And it is also impossible to get Facebook to delete your information from their servers, even if you quit using the site! Facebook is not only a black hole for your time, but also for your personal data.

Facebook has become the victim of its own success: phishers are starting to use the site as a launchpad for attacks. Phishers embed links on a user's wall that point to a malicious domain that harvests their names and passwords for Facebook. This, in turn, can lead to more phishing attempts as well as stealing other credentials (such as banking login information) and/or spamming for pharmesuticals, etc. Of course, no site is immune from the scrutiny of attackers, so this is hardly Facebook's fault. As a commenter on the Wired blog puts it, "Anywhere there is popularity and potential profit, there will be hackers and scammers." However, it is notable that criminals now see Facebook as a lucrative target. Facebook needs to crack down on these activities if it expects users to continue to feel comfortable using it. [J]

Perhaps this isn't the fault of Facebook per se, but a lot of the people on Facebook are really annoying. You know the ones I'm talking about. The coward who thinks that the epitome of activism is clicking a button that says "Join Group." [E] The gullible student that believes the world will be changed by joining groups with titles like "For every [number] people that join this group, I will donate [amount] to [cause]." [F] The narcissist that ceaselessly uploads pictures of themselves and her friends partying and broadcasts her status message to the world at least ten times a day. The clueless folk carrying on what, prior to Facebook, would have been a private conversation on each others' walls. [G] And people that have way too much free time giving each other gifts [H] and engaging in poke wars (or now, thanks to SuperPoke, throwing cow wars or the like). Facebook is often a cesspool of narcissism and ignorance that I could do without.

It may come as a surprise that, despite all of these grievances, I haven't terminated my Facebook account. It is true that I still grudgingly sign on to the service at least once a day because it provides some tangible benefits that no other service offers. Regardless of its flaws, I haven't quit Facebook... yet. I intend to write two follow up articles to this one, the first discussing what Facebook gets right and the second as an answer to "Why don't you write a Facebook application?" Stay tuned.

Update: I'm finally getting off of Facebook. The straw the eventually broke the camel's back for me was the sheer unusability of the site. Nearly every page load on Facebook maxes out my processor (on a decent machine). It's not just the sheer load of crap that Facebook is bringing into each page; even the most basic user actions cause my browser to lock up. For example, entering characters into a text box (for commenting on a photo or sending an email) has a delay of several seconds between when I hit the keys on the keyboard and when the letters show up onscreen. These inexcusable bugs plague the site. Congratulations, Facebook, you've finally driven me away.


[A] Yes, I know you can change this in your settings. Yes, I know that they now send the contents of messages in the email as well. Everything else, however, still gets you the same information-void kind of notification that begs you to come to Facebook if you want to find out what was actually said.

[B] I'm certainly not the first person to identify this phenomenon, by the way. I'm not sure who, if anyone, is the right person to attribute this to. Thoughts?

[C] And who knows what Facebook thinks "opt-in" means? The devil is in the details: does not clicking on an "I don't want this" indicate the user wants to participate? Zuckerberg, upon Beacon's release, already had some interesting ideas about what "opt-in" meant.

[D] Ed Felten provides an excellent Beacon post-mortem here.

[E] Some think that the best way to protest Facebook's practices and policies is to join a group whose cause is to recognize the fact that all its members dislike a new feature. It's not. The best way to protest is to delete your Facebook profile.

[F] A frequent question I ponder when I see groups like this is, why do people waste their time supporting these groups if they have zero assurance that the donation/action/whatever will actually happen?

[G] I really, really don't need to know the day-to-day private details of your life. And I REALLY don't need them broadcasted to me in my News Feed. If you're negotiating a play date with your friend, take it off Facebook! If you're dumping your boyfriend, take it off Facebook!

[H] Perhaps these do serve a cause since Facebook donates $1 for most of them to charity. But it annoys me when it is implied that there is some kind of scarcity to information, playing to misconceptions about the Internet. Okay, pet peevey rant over.

[I] In the legal sense, as well: could this practice be illegal?

[J] It is also a testament to the cleverness of the phishers (and the nature of Facebook's users) that they are using such well-targeted bait in the text for their links: "lol i can't believe these pics got posted.... it's going to be BADDDD when her boyfriend sees these,"

[K] Careful, FriendCSV's creators try to sign you up for their own social network when you use their product. How hypocritical, offering a way out of someone else's frying pan and into their fire.


Facebook is sharing too much data with application developers. (Link)

Facebook, in violation of their privacy policy, is now sharing your personal data with Microsoft. Hm, does that have anything to do with taking $240 million of their money?

Facebook is arbitrarily removing applications that don't seem to be in violation of their privacy policy, a la Apple and the iPhone store. The victim this time? Burger King.

Facebook may be eliminating local networks, exposing more personal data to more people.

In a rare moment of good news, Facebook has agreed to abandon Beacon.

Another reason to stay off Facebook: STDs.

Tuesday, December 04, 2007

Code formatting

Here are some tools to make your code pretty (in Ubuntu repos):
For indent, I find that the following arguments seem to work well for code I write: -bap -bbb -bl -blf -bli0 -bls -cli3 -di1 -fca -hnl -i3 -ip0 -l80 -lc80 -nbbo -nut -nsaf -nsai -nsaw -psl