Thursday, November 01, 2007

Nerd time 11 - Open social, web on desktop, random tidbits

I use to work at a research lab, and most of them are playing around with other toys outside the web. I send this out as a mailing list just to keep them updated.
---
Google Gphone
Rumor mill's on full churn with speculation about google's gPhone, so even if you read a bit of tech news, you'll probably have heard something about it. I personally don't think that they're looking to compete with apple's iPhone. To me, it makes more sense for them to license an open phone to other phone manufacturers to make it a platform they can do mobile and location-based advertising. We'll see what actually happens.
http://www.techcrunch.com/tag/gphone/

Google Open Social API
Google's going to announce the openSocial API that is suppose to out-open facebook. There are moves here and elsewhere to try and make your social network portable across different web services. That way, if you sign up for a new service, you don't have to tell it who your friends are all over again. The last link is by Marc Andersen of the Netscape Fame. His latest thing is Ning, a tool that lets you build social networks--so obviously, he has a vested interested in the topic.
http://www.techcrunch.com/2007/10/30/details-revealed-google-opensocial-to-be-common-apis-for-building-social-apps/
http://www.techcrunch.com/2007/10/29/googles-response-to-facebook-maka-maka/
http://blog.pmarca.com/2007/10/open-social-a-n.html

Eye-fi
This is something I've been waiting for for about 2 years now. It's an SD card that's also a wifi card. It enables any camera to be wifi-enabled. So you can take pictures and have it be uploaded to the web at the same time. This sort of a thing is a boon to Mobtropolis, as it lowers the barrier between taking a picture and sharing the photo. Hopefully, people will stop taking pictures of the same group pose with all different cameras soon.
http://www.eye.fi/

Mozilla Prism
Prism is still experimental, but both mozilla and adobe are thinking of taking the web experience and putting it back onto the desktop. Prism is mozilla's Thus, every web application will seem like a native application, regardless of whether you're actually connected or not. Thus, you can browse your mail or feed reader even if you're not connected. In addition, desktop apps can take advantage of local hardware acceleration for graphics. This seems similar in concept to Java's Web Start, except it's built on top of web technologies. While nothing's for sure, all the stars seem pointed in this direction. Thus, web developers might start moving on desktop developer's territory in the near future.
http://labs.mozilla.com/2007/10/prism/

How can I use spreadsheets to answer some of my many questions about the world?
One example of mixing the web with traditional desktop applications is that you can actually put queries in your spreadsheet, such as # of users in Paraguay or the ERA of Roger Clemens. Just a tidbit I thought was neat.
http://documents.google.com/support/spreadsheets/bin/answer.py?answer=54199

Evidence Based Scheduling
Joel came out with this article a couple days ago. I thought it was pretty neat and obvious (in hindsight). He comes up with a way to estimate shipping dates of software with a specific probability. He adapts a version of Monte Carlo in order to do it, and while I don't know if it works as well as it claims in practice, I assume that Joel eats his own dog food, and it seems to make sense. If you're interested in software scheduling, defn give it a read.
http://www.joelonsoftware.com/items/2007/10/26.html

The 4 boneheaded biases of voters
As some of you know, I'm pretty interested in decentralized systems--especially since Mobtropolis will have social problems at larger scales if I don't pay attention to them. Capitalist economies and voting systems being two examples. This is an article I found detailing the biases that people have about large-scale decentralized systems--specifically the economy. It's an interesting read.
http://reason.com/news/show/122019.html

State Machine Compiler
Ragel generates state machines for you. I found this to be interesting because I was wondering about how to do minimal aspect orientated programming without a full-fledges AOP system in place.
http://www.cs.queensu.ca/home/thurston/ragel/

Ruby's Object Model
When you grew up with OOP, you think you know it all. But the object model changes when you're using a dynamically typed language. It's a rather different beast altogether, and in order to keep straight the meta-programming things that people do, it helps to know and understand the object model. These are the two best ones that I've seen that explains Ruby's Object Model, and particularly, the Metaclasses.
http://rubyforge.org/docman/view.php/251/96/ChrisPine_UROM.ppt
http://www.klankboomklang.com/2007/10/05/the-metaclass/

MapReduce in a Week
If you've got a week to spare. Mapreduce is how google churns through embarrassingly parallel problems. It has its roots in functional programming. If you don't know what mapreduce it, check out joel below. Though I'm sure I posted that link before, it's worth checking out. He gives a good overview.
http://code.google.com/edu/content/submissions/mapreduce/listing.html
http://www.joelonsoftware.com/items/2006/08/01.html

Nerd time - issue 10

Nerd time is just a short mailing list I put out to my ex-coworkers at APL. They're in the applied engineering research fields, so what's going on in the web world isn't well known to them in their daily work, so I fill them in from time to time. If you regularly read techcrunch, proggit, or slashdot, I'm sure you've seen these before.

---
Hey all,

I was going to make this one about new services I use that might not be well known, since there's nothing terribly interesting going on lately. But after a month of haphazardly collecting interesting things, no particular pattern appeared. Just a hodgepodge of things I found interesting. There's nothing terribly hard this time. All easy reading, except for the one on APL at the end.

Take screenshots to measure your productivity.
This is something Ian's been asking for, and I thought he'd like to check it out. No Linux client yet though.
http://www.rescuetime.com

Prof. Randy Pausch's Last Lecture
This is a CMU prof that is dying of cancer, and he gives a last lecture. You can skip all the intros and extros, as the actual lecture is about an hour. It's pretty good, and entertaining. I found his lecture of time management to be pretty helpful.
http://video.google.com/videoplay?docid=-5700431505846055184

Voice tracking camera
This is one of those "simple" things that you wish you did. Theoretically, it's pretty easy. You use microphones to do triangulation, to figure out where the voice is coming from. But when you see his setup, he uses seven all around the room--so it might be a bit complicated. It's a long way from our own two ears.
http://www.youtube.com/watch?v=rrOy6LpL940

Commenting engines
Commenting is one of those fundamental aspects of web interaction that gets implemented over and over again, in wikis, in forums, in social apps, in blogs. But with commenting comes a host of problems. Some technical such as spam bots, cross referencing them, keeping the most relevant ones. Some social, such as trolls, scaling a conversation, etc. These two implement that for you, and commenting becomes just a widget. Not a bad idea, especially if they can thread conversations
across different blogs.
http://cocomment.com
http://www.disqus.com/

Build your own car
I've always wanted a hackable Linux based car. Everything from the onboard entertainment system to the safety system. While this isn't it, it's a step closer. I think they'll ship you all the parts you need to build your own car.
http://www.grabercars.com/content/view/80/2/

Dopplr is a service way to tell your friends, "hey, I'm going to [town], who's already there, let's hang out, or I need a place to crash" sort of thing. It's a social network focused on travelers. I've often was somewhere, and found out a friend was there at the same time too, but we didn't know. It's still in private beta.
http://www.dopplr.com

Mozilla Lab's social network in a browser.
This is an experimental add-on from mozilla that tells you want your friends are doing online. It's like the news feed in facebook. So any time anyone posts a link, updates their status, etc. you'll see it. And sending links to people is easy. You just drag it to their photo in the side bar. So instead of me sending nerd time over email,
I might as well blog it or use something like "The Coop"
http://wiki.mozilla.org/Labs/The_Coop

OAuth is Open Authentication.
I think I posted something about OpenID way back. OpenID is an open way of having uses verify to you they are who they say they are. That way, you don't have to have a separate login/pass everytime you want to use a new service. OAuth is a way for users to grant permission to a new service for their API. So if you signed up for mobtropolis, and your social network is elsewhere, you'd use OAuth to authorize
Mobtropolis to look up your friends.
http://oauth.net/about/

XFN microformats and FOAF
This is also part of the effort to open up your social network. Microformats are basically little bits of meta-data inside HTML tags. It's part of the effort to make the web more semantic. This can be used in conjunction with OAuth to make your social networks portable. We'll see if people make headway. You can view microformats with the Operator mozilla plugin for firefox. Microformats are actually on quite a few web pages now.
http://microformats.org/
http://www.gmpg.org/xfn/
http://www.foaf-project.org/
https://addons.mozilla.org/en-US/firefox/addon/4106

Forth is a stack based programming language. I don't know as much as I should about it, but it's mind-expanding. The language lacked conditional branching and loops. But apparently, that's because you can write your own, not to mention any other weird control structures you can think of. In fact, you can write your own Forth based-PC, its environment, OS, and language in about 2000 lines of code (it is said)
http://weblog.raganwald.com/2007/10/until-you-understand-how-forth-is.html

APL -- the language
I heard of this language, but never managed to see any code. I can see why. You need a whole other keyboard to program in it. But it is pretty neat. You can write Conway's Game of Life in one line. I expect this is because it maps well to functions. Neat idea.
http://catpad.net/michael/apl/

Friday, October 26, 2007

ArbCamp 2007

Well, I'm headed out to ArbCamp 2007. It's my first conference in a long while, and a first "unconference". I think I've been stuck with my nose to the grindstone the last couple of months, so it'll be nice to see what other people are doing. If any of you happen to be out in Ann Arbor or doing to ArbCamp, drop me a line, and we can meet up.

There should be some more exciting things to post after this weekend, from ArbCamp and otherwise. Til Monday.

Monday, October 22, 2007

Where do you put the rules of Monopoly?

It's apparently a favorite interview question. I have to admit, the first response in my head wasn't a great one, which was "everywhere".

What are game rules? When browsing the rules of popular games like Monopoly and Scrabble, they seem to follow a similar format:

  • The initial conditions of the game (the setup)
  • Then given a condition,
    • the set of allowable actions for the player to do
    • the effects of the condition
I embarked on somewhat of the same problem, though on a much smaller scale. I wanted to implement a point system that gave points to those that participated in a Rails app. My first reaction was to make a Rule abstract class, and have different rule classes that subclass it. Something like this (variable names have been changed to protect the innocent):
class SceneRules
def initialize(model)
@scene = model
@user = @scene.submitting_user
end

def on_submit
@user.points += 1
end
end

class SceneshotRules
def initialize(model)
@sceneshot = model
@user = @sceneshot.sceneshot_uploader
end

def on_submit
@user.points += 10
@scene.submitting_user.points += 5
end

end
Then I'd be able to call it from the controllers. However, on second thought, it's rather ugly, since I'd be updating the karma everywhere in the controllers. If I understand cross-cutting concerns correctly, scoring karma would be a good example of one. I suppose it's a good candidate for aspect orientated programming, so I scrapped the code above.

Logging is often cited as the poster-child problem to solve with AOP. Logging needs to be done everywhere in the code, but it really has nothing to do with the responsibilities of the class that it's performed in. So you have the same code doing the same thing, duplicated everywhere because there's no one place to put it to make things easy to change.

By the same token, game rules and scoring are of the same nature. And because game rules involve lots of different objects at once, and scoring is interspersed throughout, I think that makes it a good candidate for AOP. However, Ruby has no such direct support for AOP. Instead, the closest thing we have are observers, before/after/around filters (in Rails), and some meta-programming.

I wanted something that allowed me to list out rules like games like Monopoly and Scrabble. I'd have a setup, and some conditions and their effects. Scoring is simplified here because the only time you can score is when one of the models is created or changes state. This is a good fit to the observers and the filters available in Rails.

class ScoringRules < ActiveRecord::Observer
observe Sceneshot, Scene
include Rules

setup { :scene => Proc.new { |sceneshot| sceneshot.scene } },
{ :sceneshot_uploader => Proc.new { |sceneshot| sceneshot.sceneshot_uploader },
:scene_submitting_user => Proc.new { |sceneshot| sceneshot.scene.submitting_user } }

rule :after_create_sceneshot do |board, players|
players[:scene_submitting_user].score += 5
end

# put more rules here

def after_create(model)
rule_dispatch(:after_create, model)
end

end
Here, the Rules module is what encapsulates the setup, rule, and rule_dispatch calls. I needed setup so that I can access different "game elements" (the board and the players) to update the scoring. It basically stores the setup as a list of lambdas that it can execute at a later time when the rule needs to be executed. Now, when a model is created, we ask the rule dispatcher to figure out which rules execute based on the rules we've named, and then execute the attached block. The block is passed a hash of different game pieces that it needs to update the score and the game conditions. That's it.

I thought it was an interesting way about it and probably warranted some criticism. Is there any particular disadvantage of doing it this way? And if you can think of a way to not have to explicitly state the model relationships in the setup, that'd be nice. half-tip!

Thursday, October 11, 2007

Operator for Microformats

I've put microformats in the stuff I've built before. And to be honest, I wasn't sure if they were going to take off. The formats were there, but none of the tools to actually use them were around. For a long time, I just used the tails export add-on in firefox. You couldn't really do anything with it, but you could at least see microformats.

The Operator takes it one step further, and adds actions to microformats. In a way, it's a god-send, and now I'm wondering why I didn't write it. I HATE having to cut and paste addresses into google maps. Now, if there's a microformat of an address on a page now, all I have to do is use Operator--two clicks and I'm there. (As an aside, Humanized Enzo makes it even easier to include maps.)

Microformats have been gaining momentum for a year now, and I think it will be important in the web to come. Not because it's one-more-thing to have to know, but because the guys over at social network portability are using it as part of their solution to open up the walled gardens of the social network stovepipes in effect today.

Given how we're all use to using web applications today, it's as if we're always 'reborn' every time we sign up for a new service. It's an odd idea to be able to "take your network with you". If you can do this, especially as mobile devices get more powerful, there can be more and more web applications that can act as mediators in social contexts of the users as they go about the world.

One nice little app would be a name-recaller. At a conference or a party, my mobile phone would detect which other mobile phones are around. It could then query the web application whether I've met any of these people before, and what their names are. So when I actually go to shake their hand, I can address them by name. And as we all know, the sweetest sound to a person's ears is his/her own name.

But that's still a long ways from now. Probably not in another 4 or 5 years, if not more. However, I'd keep an eye on this area. I'm sure you'd hear more about it soon.

Model Reduction of Complex Dynamics

Model Reduction of Complex Dynamics



Alright, for some actual news. This is something that has been hard to achieve in computer graphics--that is believable fluid mechanics like water or smoke. Traditionally, they've been modeled as really large particle systems, which gets to be pretty expensive computationally.

These guys have managed to reduce the amount of computation required to make these computations to simulate fluids, detailed in this paper.

I've only glanced at the paper, but it looks like they were able to frame the problem in such a way that they were able to use dimension reduction techniques to reduce the number of computations they need to do, but have the least noticeable effect. By noticeable, I mean not only to the eye, but also to physics. It also conserves kinetic energy in the simulation.

I don't understand much of the math in there, as it'll take some time to go through it, but it reminds me of lossy compression algorithms and search engines. Not every piece of information is important, or is important in the same way. If you can frame the problem so that you can throw away less important information and still have approximately the same thing. It's kind of novel to think of it as applied to a computational process, rather than a stream of data.

Tuesday, October 09, 2007

First Review!

Admittedly, I submitted mobtropolis to Geekheartland, but it was nice to get a first review. You'll probably see less and less of these self promotions, since there are only so many "firsts" you can have.

All in all, there was nothing scathing about the review, and it actually said it was interesting. In general, of everyone I've ever talked that got it thought it was "interesting". Honestly, that has me puzzled. From everything I've read and heard about the history of innovation, great and revolutionary ideas polarize people. So far, I haven't really had anyone that got it and was turned off by the idea or thought it could never work. Update: Probably because not enough people have heard about it. I'm sure if the bloggers at Uncov got wind of it, they'd rip it to pieces.

We'll see what happens as I expand on Mobtropolis's vision.

Friday, October 05, 2007

Mergesort in Erlang was to be my redemption--alas it was not

Well, once I got started, I kinda couldn't help myself. I really should be debugging and cleaning up Mobtropolis, but sometimes, you need a break. To add to my shame of Erlang neophytism (probably not even a word), I tried out merge sort.

mergesort([Last]) ->
[Last];
mergesort(List) ->
[Left, Right] = split(List, [], []),
io:format("~w ~w~n", [Left, Right]),
merge(mergesort(Left), mergesort(Right)).

split([Last], Acc1, Acc2)->
[ [Last | Acc1], Acc2 ];
split([First | Rest], Acc1, Acc2) when length(Acc1) <>
split(Rest, [First | Acc1], Acc2);
split([First | Rest], Acc1, Acc2) ->
split(Rest, Acc1, [First | Acc2]).

merge([], R) ->
R;
merge(L, []) ->
L;
merge([L_h | L_t], [R_h | R_t]) when R_h =<>
[R_h | merge([L_h | L_t], R_t)];
merge([L_h | L_t], [R_h | R_t]) ->
[L_h | merge(L_t, [R_h | R_t])].

Ugh. I thought mergesort would be my redemption, since in my mind, it looked shorter. But I ended up having to write split(), since I didn't know the libraries well enough, and couldn't think of a good list comprehension to split the list. Admittingly, it's like deciding to forgo inventing the combustible engine and deciding to start walking--I just built it out what I little I knew. If you're so inclined, you can also try one-liner-ing (also not a word) mergesort, as the bar I set was pretty low. :( Like Bryan says:

"Get back into Erlang! it's good for you. ;)"

Speaking of Bryan, he posted a solution to bubblesort that was pretty good in the last post. It was a good lesson. Like anything worthwhile learning, languages are often easy enough to pick up, but hard to master. This was a good wakeup call to go through the examples in the book and master more Erlang before trying to write anything else on my own.

Thursday, October 04, 2007

Bubblesort in Erlang

It's amazing how if a language isn't a part of your daily work, how rusty you get at it. Oh erlang, how I didn't mean to neglect you! I finally convinced Ian to give Erlang a shot, and he's been going through Joe Armstrong's book. He decided to write bubblesort, and it took him hours. This is what he had to say:
I'm having some difficulty
getting used to the idea of a language where every variable is a const.
its interesting, though.

but I have to admit the one line erlang quicksort is one of the
prettiest code snippits I've ever seen.

but "=:=" for equivalence? a three character long operator? who do
they think they are?

I wrote bubble sort and merge sort in erlang last night. it took
hours. the code looks horrible. for the first time since learning
basic in high school I feel like a foreigner in a strange land. its
invigorating.

actually I find it a bit intimidating. when something takes more than a
few lines of code I wonder if I'm doing it wrong. if joe armstrong ever
saw my bubble sort he'd probably take my book away.
I decided to give it a shot. It's certainly a far better exercise than FizzBuzz. Given that I had written a neural network in erlang before, I figured I'd be more than ok with bubblesort. Right?

Wrong.

It's taken an embarrassingly long time to get it right, plus, I took a shortcut that isn't very optimal. If I ever had to write this in an interview in Erlang, They'd take my keyboard away. Here's what I came up with:
-module(bubblesort).
-export([sort/1]).

sort([First | Rest]) ->
sort_helper([First | Rest], swap(First, Rest)).

sort_helper(List, New_list) when List =:= New_list ->
List;
sort_helper(List, [First | Rest]) ->
sort_helper([First | Rest], swap(First, Rest)).

swap(Current, []) ->
[Current];
swap(Current, [First | Rest]) when Current =< First ->
[Current] ++ swap(First, Rest);
swap(Current, [First | Rest]) ->
[First] ++ swap(Current, Rest).

Notice that I use the guard "List =:= New_list" to determine if a swap took place. In a large list, this would add n comparisons on every pass. Horrible. But since it's an exercise, I neglected to keep track of swaps.

More than half the time was wrestling with the syntax. I had forgotten a lot of it, and mixed up [First, Rest] with [First | Rest], and I kept forgetting that I needed to prefix the functions by their module names. It's bubblesort:swap(...) when you want to call it, and I was scratching my head for 10 mins. But the other time was just thinking recursively. Unless you're working in a language the heavily uses recursive to iteration, you don't often use it. But defn I prefer recursive as it's much more succinct. Can anyone come up with a one-liner Bubblesort?

For reference, "the one liner" quicksort Ian was talking about:
qsort([]) -> 
[];
qsort([Pivot | T]) ->
qsort([X || X <- T, X < Pivot]) ++ [Pivot] ++ qsort([X || X <- T, X >= Pivot]).

Wednesday, October 03, 2007

First blog mention!


It's been a little beyond a full month since I kicked Mobtropolis, a social photo scavenger hunt to expand your world, out the door to face some beating out in the real world. Whenever you release something to the public, it's a bit nerve racking. But you always learn something, and better to know early and fix it, than to know later and suffer.

The first major lesson is that people didn't know what they were looking at. I had figured with the advent of Digg and Reddit, that I wouldn't need to explain what Mobtropolis does. How wrong I was. Friends and forum readers would visit, and then leave. I spent the better part of the month refactoring the underbelly of the app, and working on a better and succinct way to communicate the value added for the user. I think this will be a constant struggle, and I'll have to be vigilant about always communicating clearly.

The other thing that I learned is that a lot of things simply don't matter because you're just not at that point yet. For example, I was reluctant on putting in comments since I figured with comments comes trolls, comment spam, etc. But in truth, it's simply not at the point yet. Though I put in some precautions, it was more prudent just to kick something simple out and start using it.

I had the first blog mention today at a spanish tech blog called Genbeta today. That was a nice milestone. While the post was neutral in tone, it did mention that Mobtropolis was:
An interesting collective game in which anyone can participate.

Hopefully, I'll keep getting better. So for those of you out there working on your own stuff, it pays to just get things out there then just iterate. Release early and release often is something you can do with web applications, so take advantage of it. If any of you readers find Mobtropolis useful or interesting, feel free to tell your friends to join you on some wacky adventures.

Saturday, September 29, 2007

Mushkin - Get More

Mushkin - Get More

If you follow my blog, it's really not often that I give plugs for products or services. But sometimes, when your experience is just overwhelming positive, you just have to give credit where credit is due.

Three years ago, I brought a Dell Dimension 2400. It's a 2.66GHz P4 computer--paltry by even by yesterday's standards, but it was cheap...about $500. I brought it on a whim, and since then, it's become my main development machine. However, I had only brought it with 512MBs of RAM...which I thought was more than enough at the time.

Enter Firefox 2 stage left. The elephant that easily eats up 230MBs.

Like I lamented before, I've been having productivity slow-downs due to applications using an extraordinary amount of memory. I was actually watching screens redraw itself because the swap partition was being exercised like crazy. I had sworn off Eclipse because I felt that for what I used it for, it was eating up too much memory. But at the end of the day, what room was left by Eclipse was taken up by Firefox 2.

In the end, I succumbed and went out to buy more RAM for my machine while waiting for Firefox 3. But it's been so long (2 years) since I brought hardware, I didn't know what to get. Kudos to Dell for providing easy ways to look up what RAM you need by its model number. I use to revel in being able to look up specs to find the lowest price, but I simply don't have the time anymore. Dell was offering 1GB RAM for $109. Seemed reasonable. But I decided to check Mushkin.

I've used Mushkin since my sophomore year in college (8 years ago!), and none of the RAM I've ever purchased from them have ever failed so far. Believe me, RAM fails. Probably not as fast as hard drives, but RAM fails. And when it does, it's the last thing you assume that has failed. As a result, you waste so much time in your dorm room debugging it instead of out there mixing it up with the co-eds.

I revisited mushkins for the first time in a long time, and I have to say that while they have a dizzying array of RAM from hardcore hardware enthusiasts (what I use to be), they also have easy-to-find components for owners of stock computer models (like for me now). Not only that, they offer the same type of RAM for $30's less. Tres awesome.

Normally, if I just saw Mushkin out of the blue, I don't know if I'd trust them. But having used them all these years, and given that their RAM keeps on ticking, they stand by their quality, however they do it. Not only is their stuff quality, but their shopping experience is a breeze.

So I'd recommend their stuff. If I get Mobtropolis to a point where I need huge servers, I know where I'm getting my RAM.

Ok, next time, will be more coding related stuff, as I have some interesting things to post that have been gathering in the queue. Stay tuned!

Wednesday, September 26, 2007

[115, 117, 109, 109, 97, 114, 105, 122, 97, 116, 105, 111, 110].map{|c| c.chr}.join

Time does fly by when you don't work on the weekend. It's been almost a week since my last post--so you know I've been busy coding. Today, I got stuck on caching, so here I am, blogging.

In Nerd Time 8, I had mentioned the algorithm on content-aware image resizing. For those of you that didn't hear about it a couple weeks ago, watch the movie. It seems pretty magical at first. It basically computes an energy function for the image to decide which part it can cut out if it needed to.

I don't know if the rest of you had the same thought, but content-aware image resizing is essentially image summarization. You're throwing out less important information in the picture in favor of preserving informational features of the image.

They use an energy function as a metric to determine which seams--and in what order--to remove from the picture to reduce its size.

The most surprising thing to me was that the basic energy function is just the magnitude of the gradient function. A gradient function of an image tells you how fast the colors are changing as you're moving across the image. This means the sky would be smooth and slowly varying (low frequency), and the trees would be rough and varies quickly (high frequency). Therefore, the basic gradient energy function just allows you to selectively cut out the low frequency parts of the image while the seam selection preserves the aspect ratio and image coherence.

Apparently, this metric works pretty well, even compared to other metrics like entropy, which is the standard measure of information content. This works mostly because of the assumption that high content areas of the scene will be high frequency, and background images, like sky, road, wall, are generally low frequency images. If you had a picture of me and someone else holding up a flag with a forest as a backdrop, it'll cut out the flag first, not the trees, using the gradient energy function.

This puts text summarization into clearer focus for me. There are two competing goals in text summarization: 1) reduce the amount of text 2) keep the information content high and coherent. With content-aware image resizing, it was able to achieve both goals by finding a metric that was calculable to distinguish between important and non-important. So by comparison, we should be able to do the same with text.

However, we don't know what, if any, the gradient between words means, and how that would fare as a measure of information content. We also don't have a good way of judging coherency of a piece of text--different people will come up with different summaries. In an image, we can look and just tell. This is because we judge all pieces of an image in parallel, and we have a database of images to compare to in our heads to tell if something 'looks right' or not.

One can tell how far apart a color is from another simply by measuring the distance of the hex values that represent that color. However, words that have similar letters may have completely different meanings.
The difference between the almost right word & the right word is really a large matter--it's the difference between the lightning bug and the lightning. - Mark Twain
I suspect that one would need to use a gradient map for words, or be able to use the etymology of words to measure how far apart the meanings of words are from each other. How to generate this map has been difficult, as far as I know.

Many people have used co-occurrences of words to map words to meanings, since it makes sense that words related to each other would appear in the same text. However it was found that even if two words had the same meaning, they might have different frequency of occurrences, thus throwing off the validity of the gradient map.

Wednesday, September 19, 2007

Diving into Rails source and explaining alias_method_chain in pictures

I've been involved with the local Ruby group, and I did a talk on diving into the Rails source code. I have to admit, I probably should have dove into it earlier, but there was a lot to learn just by using Rails, for someone that was doing engineering work before this. Originally, I was going to just relate my experience of when I had to dive into the code, but then I happened on Rails' Unusual Architecture, and it gave a good topic for introducing metaprogramming used in Rails.

At first, it was pretty confusing, since I came from a C++ background and was use to the idea of design patterns. Well, there are patterns, it's just that in dynamic languages, much of the traditional Gang of Four design patterns goes away.

I'll outline the meat of the talk. Rails doesn't use the Decorator Pattern. Instead it basically renames methods in calls to inject additional functionality that wraps around the original functionality. How does it do this? It uses something called alias_method_chain, detailed here and here.

And inside alias_method_chain, is a native method called alias_method. Since everything in Ruby is an object, and changeable, that means methods of modules and objects are also changeable. It basically makes a copy of the old method and calls it something new.

I made pictures to show the progression. Let's say we have a method called "save" that we want to enhance with "validation".


We start with ActiveRecord and the Validation module. So in our validation module, we make a method called "save_with_validation"(purple heart) that calls a method called "save_without_validation" inside it. "save_without_validation" doesn't exist yet, because we haven't called alias_method_chain().


Then our first step is to include the Validation module inside of ActiveRecord.

Then when we call alias_method_chain(:save, :validation), using alias_method, it'll make a copy of the original save method, and call it "save_without_validation".


Then, it'll rename the method inside of validation from "save_with_validation" to "save". This way, any code calling save() on ActiveRecord will execute the new save, which does validation first, and then turns around to call the original save (green sun). The client won't know any different, but in fact, code was injected between the original save (green sun), and the caller inside of the new "save" (purple heart). And the original save doesn't know any different either, since nothing's changed from its point of view.

In code, it'll look something like this:
class ActiveRecord
def save
# do saving stuff
end
end

module Validation
def save_with_validation
# do validation
save_without_validation
end
end

class ActiveRecord
include Validation
alias_method_chain :save, :validation
end

Which if we 'executed' the above as we did in pictures, it ends up being equivalent to:
class ActiveRecord
def save_without_validation
# do saving stuff
end

def save
# do validation
save_without_validation
end
end

I'm not sure how I feel about it as of yet, but at first glance, it's a nice pattern once you know what's going on. At first, I saw all these methods being called in the Rails source which aren't actually defined anywhere. It ends up it's because of metaprogramming stuff like this going on. I think other people have said this is bad idea because it's hard to inject functionality in the middle of chains that already exist. If you pick up one, you pick up everything before it. One might argue the same is true of Decorator patterns.

In any case, you'll see this repeated over and over again in the Rails source, so hopefully, this'll give you some idea of what's going on if you ever decide to go Rails splunking.

Sunday, September 16, 2007

Syntactic sugar for dealing with empty containers

In any web application, we're often just reading a collection of rows from the database and displaying it in the browser. Often times, we'll have code that looks like this:
<% unless @friends.empty? -%>
<% @friends.each do |friend| -%>
<li><%= h friend.username %></li>
<% end -%>
<% else -%>
No friends yet
<% end -%>
I don't know why, but this kinda gets to me, and doesn't look all that neat. I probably attribute it to having to upgrade and maintain a piece of C server code that was nested 8 or 9 layers deep all in one huge main(). It might be counter-productive, but I tried to see if I could do better.
<% if @friends.each do |friend| -%>
<li><%= h friend.username %></li>
<% end.empty? -%>
No friends yet
<% end -%>
Well, this is kinda nice in a way that it's only one hierarchy deep. When I look at it, one section is for what to display when there are elements in the list, and one is for when there isn't. I suppose your mileage may vary. However, I didn't like the "if" in front. It obscures the intent of displaying the list. So, in the pursuit of more counter-productivity and perhaps in the spirit of pseudo-altering the language, I tried this out:
<% @friends.each do |friend| -%>
<li><%= h friend.username %></li>
<% end.empty do -%>
No friends yet
<% end -%>
Well, that worked. I kinda like it. Since the message was so simple, I had wanted empty() to take a message, and just display it, but because it's a "%" and not a "%=", the message won't get displayed, so I had to do it in a block. In a way, it's almost like being able to write my own "else" statement. If I had used curly braces instead of "do/end", it might look pretty close. Here's the code for empty:
class Array
def empty(message = "")
if self.empty?
return block_given? ? (yield message) : message
end
end
end
Like it? Hate it? Tip!

Thursday, September 13, 2007

Unable to freeze rails due to problem in rake task

I think the current version of stable Rails is 1.2.3. For those of you using this version, rather than Edge Rails, there's a little gotcha in the rake tasks.

Since I'm on a shared host, it's good practice to freeze your version of rails into the vendor's directory. You do this by using a rake task, per "rake rails:freeze:gems" But before you do that, if you're using SVN, you'll want to use "svn delete" to remove the vendors/rails directory. None of the rake tasks use SVN delete. They all use "rm -rf", which in my experience makes SVN freak out if the .svn directory is gone.

However, even with that done, freezing a new version of gems was failing.

It was looking for rails version 1.4.0, and not being able to install it. And even worse, when you try to run rake again, it said it couldn't find it!

Well, the latter was simple. A failed freeze leaves a blank vendor/rails directory, and if you look in 'config/boot.rb', it says:

if File.directory?("#{RAILS_ROOT}/vendor/rails")
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
else
require 'rubygems'
...blah blah blah..

So make sure you remove vendor/rails.

The latter took a little bit of work digging around the rake tasks, and though it wasn't hard, I wasted about an hour. It ends up that the culprit is that the default rake task uses Gem.cache.search('rails'), which returns all gems with the name 'rails' in it.

I have a couple gems installed with the word 'rails' in it.

rails (1.2.3, 1.2.0, 1.1.6)
rails_analyzer_tools (1.4.0)
railsbench (0.9.2)

So it took the latest one, which was 1.4.0, and tried to install rails 1.4.0, which doesn't exist!

To hot fix it, the railities/lib/tasks/framework.rake file, under the freeze namespace and gems task, change "Gem.cache.search" to "Gem.cache.find_name"

That way, it only finds 'rails', and not all the other games with 'rails' in the name of the gem. This problem is solved in edge Rails, so no need to submit a patch. Tip!

Tuesday, September 11, 2007

Nerd time, issue 8

I used to work at a research laboratory, where the fanfare and fads of the web aren't of great concern. But the co workers liked to know what was going on outside the ivory towers, so after I quit, I sent them an informal mailing list. I post it on here just for fun too.

---

So after a little hiatus deploying mobtropolis, nerd time is back. As
usual, easy reading is up top. This time it's on databases. Dbs and
backends usually inspire yawns, because frankly, they're not
sexy--there's no pretty screens to look at. However, dbs are often a
bottle neck, and scaling beyond the usual db configs has been a source
of pain for large scale software. Here, I point out some relatively
obscure db stuff on the horizon--after some easy reading and news.
And oh, if you don't want to get these anymore, just lemme know.

A group is its own worst enemy
Nothing to do with dbs. Just a classic piece of text on social
software. Easy reading, but good lessons for me when building
http://www.mobtropolis.com
http://www.shirky.com/writings/group_enemy.html

Firefox 3 with XUL runtime
I did comment on this, and FF3 should be less prone to crashes, unlike
FF2, and the significance of this is much like Adobe's Integrated
Runtime(AIR), web devs will be able to create native desktop
applications using the usual web tools--HTML, javascript,
actionscript, XML, etc.
http://arstechnica.com/journals/linux.ars/2007/08/21/using-firefox-3-as-a-xul-runtime-environment
http://webjazz.blogspot.com/2007/08/using-firefox-3-as-xul-runtime.html

Adobe also open sourced their Photoshop engines. Offhand, I'm not
sure what one would do with it, unless there were some type of
innovative image manipulation--of which you'll see on the next link
http://opensource.adobe.com/group__asl__overview.html

Content-aware image resizing.
This is kinda neat. It uses energy functions to resize images while
keeping important content, and killing out background parts of the
images. If you don't click on any of the links but one, I'd click on
this one.
Update:
Well, what's interesting is that the basic energy function they used is simply a two-dimensional gradient. It's under the assumption that high frequency image content is usually what contains information/foreground/interesting parts of the image. This is probably usually true, and probably works for a large number of images. However, I think if you had an image of a flag with a forest as the background, it'll cut out the flag first.
http://www.youtube.com/watch?v=c-SSu3tJ3ns
http://www.faculty.idc.ac.il/arik/imret.pdf

Byte-serving is an aspect of the HTTP protocol that I didn't know
about. Apparently, you can request specific parts of a file over
http. Web-based bittorrent?
http://www.coneural.org/florian/papers/04_byteserving.php

hBase - Google bigtable open source clone. Bigtable is a in-house
developed distributed database. I watched a video lecture of it one
time, and it seems pretty neat.
http://glinden.blogspot.com/2007/07/hbase-google-bigtable-clone.html

A free database of the world's spec-related knowledge in one place.
Oddly enough, it is populated with things. I'm not sure what
motivates people to enter things in, but probably the same motivation
as people contributing to wikipedia. The neat thing about this is
that you can query it with an API.
http://www.freebase.com/signin/

CouchDb is an database that doesn't use relational tables. Mostly for
documents. It's still in alpha.
http://couchdb.org/CouchDB/CouchDBWeb.nsf/Home?OpenForm

Ambition is an experimental ruby gem that makes SQL queries as Ruby's
Enumerable functions. Web devs seem pretty allergic to SQL in general
and has tried to build layers between the dev to have one less
language to learn. Probably also the result of wanting a 3 tiered
architecture too.
http://errtheblog.com/post/10722

Mnesia is Erlang's distributed DB. I'm under the impression that it
doesn't use SQL. One queries directly by using Erlang tuples. I'll
have to learn more about this one.
http://www1.erlang.org/documentation/doc-5.0.1/lib/mnesia-3.9.2/doc/html/part_frame.html

Thursday, September 06, 2007

Is preloading child tables always a good idea?

Optimization isn't something you should do too early on, but I think a little house cleaning every so often to make sure your pages aren't ridiculously slow is healthy. With any optimization task, you'd want to benchmark the results and see if there's an actual gain. The very basic tool for benchmarking is the ordinary script/performance/benchmark. The easiest to find analysis tools is the rails_analyzer gem. The last time I used rails analyzer, it wasn't that easy to use. The command line arguments seemed arcane. But its bench tool, which can benchmark controllers as opposed to just object models, is fairly easy to use.

Using the bookmarking example from before, let's say you have something like:
class SceneController < ApplicationController
def list
@books = Book.find_books
end
end

class Book < ActiveRecord::Base
def self.find_books
find(:all, :include => [:bookmarks],
:conditions => ["books.created_on > ?", 6.month.ago])
end

def bookmarked_by?(user)
self.bookmarks.select { |bm| bm.owner_id == user.id }.empty? ? false : true
end
end

In the listing of books, one would display whether it's actually bookmarked by a user or not. Normally, without the :include, the listing would make repeated queries to the DB every time it displayed a book list element, since it will use bookmarked_by?(user_id) to determine if a user bookmarked the book. So instead of just 1 query, it would make n + 1 queries.

Preloading child tables isn't necessarily wise all the time. It really depends on what you intend to do with the data after you fetch it. As the Agile rails book warns, preloading all that data will take time. If you look at your log files, you'll see that it's a significant amount.

If you're only going to load a limited number of these book list elements on a single page at a time, it actually might make sense to forgo preloading of child tables, and just use a find() instead of a select.
class SceneController < ApplicationController
def list
@books = Book.find_books
end
end

class Book < ActiveRecord::Base
def self.find_books
find(:all, :conditions => ["created_on > ?", 6.month.ago],
:limit => 20, :order => "created_on desc")
end

def bookmarked_by?(user)
Bookmark.find(:first,
:conditions => ["book_id = ? and owner_id = ?", id, user.id]) ? true : false

end
end

And if you're going to display counts of arrays, but all means, use counter caching. It's easy to do (as long as you follow instructions!), for most situations.

Intuitively, if you want to display over a certain n number of book list elements, it makes more sense to use :include and select it. However, I wanted to point out that when you make decisions like this, you'll always want to measure the load times, because you earn what you measure.

Also, use the right number of runs. Too short number of a number of times you run a function, the more variation you'll have in your benchmarks. Let's say that you get two numbers for two different methods.
$ bench -u http://localhost:3000/method1 -r 50 -c 5
50....45....40....35....30....25....20....15....10....5....
Total time: 240.383527755737
Average time: 4.80767055511475

$ bench -u http://localhost:3000/method2 -r 50 -c 5
50....45....40....35....30....25....20....15....10....5....
Total time: 156.147093772888
Average time: 3.12294187545776

So it's obvious that method2 is better right? Well, not necessarily. While benchmarks only show averages, you'll need to pay attention to standard deviations. The bigger the standard deviation, the more runs you'll need to figure out the average load time, and the number of decimal points you can trust. That way, you can figure out whether the difference in load times is statistically significant or not.

That way, you can ascertain whether the optimization you made were worth the trouble or not. tip!

Tuesday, September 04, 2007

Mobtropolis Public Release

I've been working on Mobtropolis for about 10-12 weeks now. It's was finally released last week Tuesday. It's something that makes people expand their world by helping them discover and share local adventures around them. The easiest way to think about it is as a dynamic large-scale photo scavenger hunt or a photo-dare site that helps you expand your world--hopefully for the better.

Behavior is hard to change, so it's framed slightly in terms of a game. The basic mechanics should be familiar to those that frequent social news sites. Anyone can submit scenes or vote them up. The higher something's voted, the higher its visibility to others. Anyone can do a scene and take a photo as proof. They can then send it in via their camera phone, or upload it from their digital camera when they get back to desktop. Their friends who voted for a scene will then get an email with the photo attached.

It's been oddly thrilling to get photos of people doing scenes that you submitted.

There's still a lot of work to be done on it. Eventually, I hope to marry the virtual and the real in a tighter loop and better integration with mobile devices. However I'm putting it out in according to startup mantras of "Release early, then iterate like crazy". So check it out, and if you'd be so kind, give me some feedback, good or bad, so I can make it better.

http://www.mobtropolis.com

Enjoy!

Sunday, September 02, 2007

Use barriers to your advantage

I use to read iwillteachyoutoberich, as he had some useful tidbits, and I, like many twenty-somethings, usually worry about personal finances...But anyway, the one piece that I really like that I gleamed from him was his take on barriers.
I think the source of 95%+ of barriers to success is…ourselves. It’s not our lack of resources (money, education, etc). It’s not our competition. It’s usually just what’s in our own heads. Barriers are more than just excuses–they’re the things that make us not get anything done. And not only do we allow them to exist around us, we encourage them. There are active barriers and passive barriers, but the result is still the same: We don’t achieve what we want to.

He had another post where he turned it around and said that you can make barriers work to your advantage as well, not just in avoiding kooks, but in increasing your productivity.

Since I do web dev, the browser's up all the time, and it's really easy just to hit ctrl-t www.facebook.com. And then before you know it, a whole half hour's been wasted. It's even worse with proggit or hacker news. A couple days ago, there was a tip on 4 lines to increase your productivity (can't find it now) on reddit, and it was just lines in a /etc/hosts file. It reminded me of barriers, so I decided to try it out.

I set up my /etc/hosts file:

127.0.0.1 www.facebook.com
127.0.0.1 news.ycombinator.com
127.0.0.1 news.octoparts.com
127.0.0.1 programming.reddit.com

# if I'm really having problems concentrating:
127.0.0.1 www.gmail.com
127.0.0.1 mail.yahoo.com


And lo and behold, it actually worked. Just the extra step of having to type in a command and a password is enough to deter me from not working. I do still hit ctrl-t once in a while, but then I'm reminded that it's fruitless, and I might as well get back to work. My friend Ian closes everything but a max windowed emacs as his productivity trick.

Anyone got any others they fool themselves with to get crackin'?

Saturday, September 01, 2007

Ajax.Ajax.PeriodicalUpdater has a decay option

Prototype JavaScript framework: Ajax.Ajax.PeriodicalUpdater

There's plenty of treasure in API docs, I've usually found--like when you need two submit buttons for an AJAX form. While tutorials are helpful for just getting started, I'm a firm believer in just browsing through API docs and references once in a while, like a lazy grounds keeper checking for garden gnomes. I also like reading dictionaries. I don't do that too often, just when I'm looking up words. I never got any papers done until internet dictionaries came around.

The past two days, I've been playing more with Javascript, and that involved looking more closely at the Prototype library that comes with Rails. So far, my experience with prototype has been pretty good. It's less high level than, say mookit, but I think it was meant to fill holes in the current javascript language. Even little things like Try.these() are nice, due to javascript discrepancies between browsers.

As a result of browsing through the Prototype API, I found that the adaptive polling I had talked about before was actually already in the Prototype library. It was just never mentioned in any of the Rails docs or tutorials about periodically_call_remote().

Though I don't know if it was around when I blogged it last December, that should be lesson to me to stop talking, and just try writing a patch, as Prototype is open source. I probably would have learned a lot.