Thursday, March 15, 2007

Noiz2sa by Kenta Cho (2002) |

"Noiz2sa is an early study in the art of bullet barrages and playing strategies. It is Cho’s Well Tempered Clavier, in which he challenges several of the aesthetic assumptions of the genre, showing off a talent for composing dizzyingly varied game stages out of a self-imposed set of constraints. "

Here's a diversion for you. I found Noiz2sa by accident in Ubuntu's repositories. It's an abstract 2D space shooter. The review quoted had the funniest--and pretty much the only review for it. The game really is like an exploration of the genre. It's like he said to himself, "what if we had, lots of bullets, and it was hard for you to get shot?" You have no powerups, and you have to make it through 10 substages. It's actually a fun and addictive game, not to mention pretty.

Beyond being a diversion, I thought it was noteworthy that he expresses the bullet patterns in BulletML, a markup language for bullet patterns in 2D shooters. This makes it interesting, since you can attach it to a genetic algorithm, and evolve it as the player got better at dodging your previous bullet patterns through the game. It would not be far fetched to write a server that served these BulletML files in front of of the genetic algorithm, so players can download it, and then report how they did.

BulletML actually just describes a particle system. It might be applicable in certain data visualizations--though I don't know what. What other uses do you think BulletML would have?

Wednesday, March 14, 2007

Vertical markets for social networking sites

Goodreads is a social networking site for book lovers. That really puzzled and surprised me. I know for a fact that vertical (niche) markets are always better to start off with when you're starting out. It lets you build a community of like-minded people, and it makes you focus your product, which makes it not only easier to build, but makes you design a tighter product.

But the question to me at first impression was, why would people join a vertical market for something that already exists?

Goodreads is a well designed site. It has a core, limited feature, and it's clean, and it's easy to add books that you've read and write reviews on them. One can also see what your friends are reading and what they'd recommend.

However, the big three social networking sites, Friendster, MySpace, and Facebook all have a section where one can list and name books that interest you. And Amazon, already has both places to read/write reviews for each book, and a recommendation system that works pretty well. In addition, you can actually buy books there.

So what does Goodreads have to offer? Well, for one, at this early stage, it's fast and responsive, and the mechanisms for actually adding a book is very easy. In addition, it plays on one of the elements of gaming, which is namely, collecting. And that goes along very well with those that read books...they like to have a full bookshelf (almost like trophies on display). There are many games that focus on the collection aspect. Yugi Oh! and Pokemon are the two that spring to mind. Goodreads is like pokemon...for people that like to read.

In addition, I think the book covers help enforce that idea of a collection, so you can see books in your bookshelf. And not only that, you can segment them according to what you've read, are currently reading, didn't finish, etc. That's something you can't do with a normal bookshelf.

I won't say that it's inevitable that a niche market in an already saturated global market of social networks is going to succeed. But the way Goodreads did it makes sense. In fact, the same mechanism of collection that I outlined above can readily be applied to a social network of fashion geeks.

I own this shirt, or that blouse. I can see what my friends are wearing the next day. I can ask to trade clothes. I can make outfits for myself from my closet, and recommend them to others that have the same pieces of clothing. I can rate clothes and brands, and I can see what the overall trend for different types of clothing are.

I'd be tempted to make it myself, since I usually have an awful time shopping for clothes--I can never remember what I already have. However, 1) I'm not much of a clothes person myself, so I'll only probably work on the 'help me choose my clothes' part, and 2) there are already plenty of niche market fashion sites out there.

What other vertical markets for social networks do you see that would have potential?

Tuesday, March 13, 2007

Using SMTP over SSL in Ruby

Ruby 1.8 doesn't yet support SSL for both POP3 and SMTP, though Ruby 1.9 does. I had a post earlier on POP3 over SSL, and I didn't think I needed/wanted to do SMTP. Well. here I am. I was googling for some type of solution, and the first site the came up, was well, a non-free solution.

So I did eventually find this solution posted on the rails wiki, which had the original solution from a blogger in japan. It's odd that it's ranked so low on google. Hopefully, one more link to it will help it bump that useless first site off the top link.




Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Monday, March 12, 2007

Sending data from rails to javascript using JSON

RJS templates are a beauty, really. They allow you to run javascript code generated by rails, to be executed on the browser. Usually, this javascript code affects the DOM. But RJS, as it is often used now, is for affecting the look and behavior of a page with javascript. What if you have data that needs to be transferred from Ruby on Rails to the Javascript in the browser?

Well, my first inkling was to write a helper function that converted a matrix in Ruby, one by one, to a matrix in Javascript. But it felt ugly, like specialized complexity that's just in your face. There has to be a better way, since I can't be the first one to run into this problem.

Of course, there is and that's using JSON--JavaScript Object Notation. A simple way to think of it is as XML, with less overhead, because JSON is simply that, a way to represent data in a standard format that's easy for both humans to read and machines to parse.

In Rails 1.1+ (apparently, this has been around since at least May 2006), there's been an extension added to Object class, and that's to_json(). That's right. You can serialize any object in rails to JSON, simply by calling to_json(). However, it's not documented in the Rails API, so your best bet is to google for it.

As a quick and dirty way to demonstrate it, you can have this in your controller:

def some_action
# some type of data from somewhere in the database
@data = Data.find(1)
end

and then the following in your view somewhere:

<script type="text/javascript">
var data = <%= @data.to_json %>
// act on data as if it were a Javascript object
</script>

You should be able to create helper functions that generate the javascript tags and the enclosing javascript so that it'd be a bit prettier, so it'd look like this in your view instead:

<%= act_on_data(@data) %>

Neat. So in this way, you can pass your data from your server to code in your views that isn't to be displayed in HTML, but in some other form. One person has tied Adobe's Flex in with Rails for this very purpose. Tip!

But one other thing that I realized after reading through JSON for the masses, is somewhat startling...at least to me. And in hindsight, perhaps it was because it never seemed easy to do in XML.

Usually data transfer languages such as XML and the like are declarative languages. They say the "what" instead of the "how". That hasn't stopped people from trying to do remote procedure calls with XML-RPC. But with JSON, it really is an object notation, meaning that you can put functions as data. So the example I gave before of javascript classes, they can instead be written in JSON notion in the source code and it would still work.

Therefore, the javascript interpreter itself IS the parser for JSON. You don't need a separate parser in javascript like you do in XML. If JSON really does have cross-language compatibility, that's actually rather neat. This implies that JSON-RPC is possible, and of course, a quick search on Google reveals that this is exactly what people are trying.

This kind of reminds me of how Von Neumann's computer architecture was novel at the time because it treated program commands and data as the same thing. Before, computers had one place for data, and one place for a program. You didn't store programs the same place that you stored data. By the same token, it also reminds me of how Lisp's data is pretty much its code, and vice versa, and that's where it derives a lot of its power.

Looking into the future (meaning, here on out, I'm talking out of my ass), perhaps that makes it easier to do distributed computing, and the stitching together of applications so very much desired by the Service Orientated Architecture crowd, but also a host of security issues. You might be able to get javascript programs that update each other on the fly in the field, instead of going all the way back to the server for updates (maybe).

Tuesday, March 06, 2007

Dynamic fixtures for time didn't seem to be working...

For it while, it seemed like eRb wasn't working in Rail's dynamic fixtures. It use to work, and since I wasn't paying attention, at some point, something like this stopped working:
post:
id: 1
timestamp: <%= Time.now.to_s %>

After only a bit of head scratching and thinking (it pays to think!), I figured out that it only takes xmlschema datetime formats. I don't remember it being the case, but yeah, that's what you have to do now...at least for Rails 1.2.0+. So now, it should look like this.
post:
id: 1
timestamp: <%= Time.now.xmlschema %>

Hope that saved you some time. Tip!

Monday, March 05, 2007

Traffic reporting for Google Maps

Google Maps just added traffic reporting. Screen shot below:

That's pretty neat, though yahoo has had traffic reporting on their beta maps for some time now. I just like google's interface better...it's fast. And I noticed they also have metro stops now. Neat.

Overriding Time.now for Rails testing

When testing in Rails or otherwise, there are times when you need to test time-sensitive, or time-related methods. Before today, I had a hard time finding a good solution to that.

Let's say that you are a person that loves your friends, and the more time that passes, the more you adore them. You'd want to test the love you give a friend grows over time. So you might have something like this:
class Friend
def love
Time.now - @when_first_met
end
end

def test_love_grows_over_time
friend = friends(:jon_lee)
love_now = friend.love

# do something here to shift time forward
# so that Time.now gives a time in the future

love_later = friend.love
assert love_later > love_now
end

A tip here from Rails Studio inserts a wrapper class around Time, and then proceeds to use their wrapper class MyTime in the rest of their application. This is certainly easier to write, but not always possible. There could be methods that uses Time.now in it that you don't want to rewrite (read: don't want to mess with) in a library that you need to use in the tests of your application. And would you really want to replace all instances of Time.now in every library that you use? Search and Replace!

In Ruby, all classes are open, and you can dynamically add methods to both objects and classes. This means that the importance of the wrappers is rather diminished--unless you don't like the idea of a class being open. Because of this example and others, I'm more convinced that design patterns are signs of weaknesses in a language.

So! I know that in Ruby, you should be able to somehow dynamically override Time.now, in order to run friend.love again. You could override Time.now completely, but accordingly, that messes up times in the Unit testing, so tests look like they end before they begin.

In my searches on google, I happen to come across this thread on Ruby talk, which in turn, had a post to Jim Weiriches's OSCON 2005 slide:

def test_warmer
Warmer.use_class(:Heater, MockHeater) do
# Here, anytime a method in Warmer references Heater
# it will get a MockHeater class instead.
end
# Here Warmer is back to normal.
end

Wow, this is pretty neat. What use_class does, is allow you to create a scope where the Heater class is replaced by MockHeater! All classes still use Heater, but Heater is actually replaced with MockHeater within this scope. When the code execute goes back outside of the block, Heater is returned to the original Heater, and not the MockHeater. He achieves this by using a class proxy. You can see the code here.

This is pretty much what I need, so that I'd be able to replace Time with a MockTime. However, as it was written, it doesn't work with Time.now, since now() is a class method. With the way it was implemented, the ClassProxy does not know anything about an object's class methods.

I originally was messing around for hours on how to dynamically add class methods, but I'll spare you the details. What ended up being way easier was just to use method_missing() and pass on any method ClassProxy doesn't know what to do with to the proxied class. So you end up with an extra private method.
class ClassProxy
attr_accessor :proxied_class

def initialize(default_class)
@proxied_class = default_class
end

def new(*args, &block)
@proxied_class.new(*args, &block)
end

private
def method_missing(method_sym, *args)
@proxied_class.send(method_sym, *args)
end
end

So now, you should be able to do this in your test:
class MockTime
def self.now
Time.now.in 2.days
end
end

def test_love_grows_over_time
friend = friends(:jon_lee)
love_now = friend.love

Friend.use_class(:Time, MockTime) do
love_later = friend.love
assert love_later > love_now
end
end

And it should pass! Tip!

Saturday, March 03, 2007

A simple isometric engine

For a day or two, I've been messing around with Canvas for firefox. I've managed to code up a very simple isometric engine in about 2 days, provided the canvas tutorial. The hardest part was really just making sure it rendered correctly from back to front. But other than that, everything seemed pretty straightforward.

One thing I'll have to say though, is that this was my first foray into javascript, and it's been more flexible than I had remembered back in 1996. Most people don't take advantage of javascript's language features, since most scripts are fairly short. However, javascript supports object orientated programming, but using a prototype based object instantiation. This means that there is no such thing as classes, but all subsequent objects are created by cloning existing objects. The new objects are then extended to fit the need of the programmer. The following mirrors how you would create a 'class'.

function IsoEngine(canvas_id) {
this.canvas = document.getElementById(canvas_id);
if (this.canvas == null) { return; };
this.ctx = this.canvas.getContext('2d');
var objects = new Array();

this.add_to_scene = function(object) {
objects.push(object);
};

this.clear = function() {
this.ctx.clearRect(0,0, this.canvas.width, this.canvas.height);
}

this.draw = function() {
for (var i = 0; i < objects.length; i++) {
objects[i].draw();
}
};


As you can see, it's all using functions, and it makes for weird looking syntax for those of us coming from a class-based OOP. What was also a pleasant surprise was that javascript supported higher order programming. This means that functions can take other functions as arguments, and if I'm not mistaken, this makes closures possible. It's hell of a lot better than passing function pointers around in C. The syntax for that always left me confused.

Articles and Snippets added to 3cglabs.com

I've revamped the 3cglabs.com webpage a little. I've added a section for articles, linking to what I think are some of my better writings on this blog, as well as a code snippet section that shows off some of what I've been playing with.

Friday, March 02, 2007

Ruby's broken breakpoint workaround

I was messing around with different installations of ruby, and I was aghast when breakpoint stopped working. Having a debugger for imperative programing is one of the fundamental tools in a programmer's tool box. Well, one option is to use the ruby-debug gem, which I have yet to try out.

But I did find that it was because Binding.of_caller() was rewritten (or something) for 1.8.5. In any case, something changed. So if you want a breakpoint and it was broken somehow, try this:

Breakpoint.breakpoint(nil, binding)

Sunday, February 25, 2007

How to install emacs major mode for javascript

As emacs is a harsh way of life, having documented things for other people is a good way to give back. Too bad it's hard for first timers. But I guess that's why people stick with it...it's a point of pride.

So how do you install a major mode for emacs? First, you need to find out what your emacs load path is.

C-h v load-path

Then you go and find a major mode file (javascript-mode.el) and put it in one of those directories. Since I don't know better, I put it in '/usr/local/share/site-lisp'. (Anyone else know a better place to put javascript major modes?)

Then put the following in your ".emacs" file. This file exists in your home directory, and if it doesn't exist, create it.

;; for javascript files
(autoload 'javascript-mode "javascript-mode" "JavaScript mode" t)
(setq auto-mode-alist (append '(("\\.js$" . javascript-mode))
auto-mode-alist))

And there you go, emacs major mode for javascript. If there's already a package in your favorite distribution of linux, install that package instead. It's way easier.

Emacs is a harsh way of life

I've had a fellow engineering friend quip to me:
Emacs. It's not just a text editor, it's a way of life. - Ian Martins

However, it's sometimes a harsh way of life, because most everything is hidden.

So I was looking up how to change fonts in emacs, since the recent Ubuntu upgrade of X windows gives you square boxes in your emacs. Linked in the title is what I've found, and it's pretty helpful.

I also found a small tidbit about how to search-and-replace with a newline.

M-%

to invoke search and replace. And then type whatever you're looking for. And then in order to replace it with a newline, type:

C-q
C-j

There you go.

Sunday, February 18, 2007

each vs. inject vs. map

Despite working in Matlab for a fair amount of time, where you have to think in terms of matrix operations, it's still hard to shake the "loop it through" kind of thinking when dealing with collections of things from a C heritage. So say I have posts with comments, and I want to get all the comments of all posts.

all_comments = []
posts.each { |post| all_comments += post.comments }

This was the way that I use to do it using a more C-like thinking. I really never liked doing it this way because you have that floating initialization with all_comments, and it can get separated from the actual loop when you have all sorts of stuff doing on. Then I found inject:

posts.inject([]) { |all_comments, post| all_comments + post.comments }

This code does the same thing, pretty much with the initialization in the loop itself. I liked it a lot better. However, map has its uses:

posts.map { |post| post.comments }.flatten

I'm not sure which one is faster on my machine, but the last one has an appeal in that a "map" operation tells me that this piece of code can be done in parallel. Given the way it's written, semantically it means that every piece in the collection can be independently calculated from each other, and then put together at the end (with flatten)--regardless of how it's actually implemented right now. Not that this isn't true for the first two code pieces, however, "inject" and "each" does not immediately imply that it can be parallelized.

I know that compilers nowadays are pretty sophisticated, with pipelining and all. But having a programmer use "map" could only be a help to the compiler figure out which part of the code parallelizes, no?

Update: I found another post talking about closures in Haskell, since the java people are resisting closures in Java. It gives a better argument over why a for loop is no good.

Friday, February 16, 2007

Convention over configuration is a culture over reinvention

Most programs nowadays are written with some code that the developer writes that are built on top libraries. We string together and manipulate the libraries in interesting ways in order build an application. No one goes and rewrites a graphics engine or a networking library anymore (unless you're doing something special or unique in that arena). So besides debugging, for every new type of application a developer is doing, they are mostly spending time figuring out how to use libraries.

I've found that some libraries were really hard to figure out how to use. Other libraries were a lot easier to adopt. Why? I've found that it was mainly due a culture that was common across the libraries, and often times, this is more apparent in some languages than in others.

When I started using Rails, I was struck by how some things weren't dictated by the syntax of the language, but merely a convention set by the framework developer. And as long as you followed the convention, things just worked. This not only simplified the complexity of rails, because it didn't have to handle all sorts of cases, but it also made it simpler to find your way around the framework once you knew its 'culture'.

"Convention over configuration", is what the creator of Rails calls it, and after thinking about it for a little bit, it makes sense. In Rails you don't have to make the mapping of class names to database table names, or their id attribute. There is already a convention, a culture, for doing that. Culture of a framework allows you to make assumptions that lets you say more with less.

It is the same with any human language. Idioms such as, "famous last words", "a rose by any other name", and "rolling a rock uphill" have a lot of meaning behind the words that are the result of references that most other people know--culture. So with just a couple words, you can convey quite a bit. The catch is that the other person has to understand that culture in order for you to convey much with little.

I think programming language--libraries especially--would benefit from a culture, so that programmers can more easily hop from library to library. Culture also has the advantage of being malleable over time. This way programmers can shift their conventions over time if the old ones aren't working.

Wednesday, February 14, 2007

No such file to load — mkmf | mentalized

I was trying to install the Hpricot gem, but it wasn't working. Ends up that you need to install the ruby1.8-dev package on Ubuntu...that's where the mkmf file resides. I suppose it's cuz Hpricot has things it needs to compile, and all those things are in the dev package. It makes sense now, but kind of annoying when you couldn't have guessed. Good thing for Google.

For the love of programmers, we need better concurrency abstractions

Lately, I've been pretty interested in parallelism. Processors are moving to multi-core architectures. And while I expect that computers will keep following Moore's Law for a while more, I think that there's a lot to be gained for figuring how to best make use of multiple processors, especially for the tasks that can be easily parallelized, such as 3D graphics, image processing, and certain artificial intelligence algorithms. If compilers and subsequently programmers can't take advantage of these multiple processors, we won't see a performance gain in future software.

However, in terms of programming for multiple processors, the general consensus among programmers is, "avoid it if you can get away with it." Multi-threaded programming has generally been considered hard, and with good reason. It's not easy to think about multiple threads running the same code all at the same time at different points, and the side effects that it will have. Synchronization and mutex locks don't make for an easy abstraction that works well as the code base gets larger.

One of the ways that people have been able to get around it is to reduce the amount of sharing of data that different threads and processes needs to have. Sometimes, this is enforced by a no side-effects policy in functional programming, and other times, it's by the use of algorithms that are by nature share nothing. Google's MapReduce seems to be a good example of this.

But there are some programs and algorithms that require the sharing of data, multithreaded programming for shared data is in some sense, unavoidable. Since that's what we're introduced with as THE thing for multi-threaded programming, that's all I knew for a long while. Therefore, I started to wonder, is the current concurrent programming abstraction with synchronization of threads and mutexes the only one that exists?

Apparently not. Like all good ideas in CS, they seemed to have all come from the 1960's. However, there here are futures, software transactional memory, actors, and joins (scroll down to concurrency). The post from Moonbase gives a probable syntax for these abstractions in ruby--they don't exist yet, but he's thinking what it might look like. I'm excited about this, if it makes programming multi-threaded applications easier. That way, programmers can more easily exploit multi-core processors or clusters for speed.

Most of the time, parallelism is exploited for speed, but I think parallelism can be also exploited for robustness. It's no secret to programmers that code is fairly brittle. A single component that isn't working correctly is a runtime bug for the entire system. I think parallelism can also be exploited to alleviate this problem, for a trade off of greater execution speed due to parallelism.

The only reason that I think this might be an interesting area to explore is because of the relatively recent interest in natural complex and emergent systems such as ants foraging for food, sugarscape, and termites gathering wood piles. A more technical example are the decentralized P2P technologies, as well as Bittorrent. This seems to be nothing new, as agent based modeling has been around for a while, in the form of genetic algorithms and ant algorithms. However, none of the current popular programming languages has good abstractions for it to exploit it as parallelism-for-robustness.

This might be a bit hard to design for, since it relies on the building of simple actors that will have an emergent system effect, while only sharing or using local information. It's not always easy to ascertain what the global effect of many interacting simple actors will be analytically, since it might not always be tractable. In the reverse, given a desired emergent global system effect, to find the simple actor that will do that isn't a walk in the park. However, I think once achieved, it will have the robustness that will make it more adaptable than current systems.

If anyone out there knows of such things, post a comment and let me know.
--
Update: I found that there was just a debate on Software Transactional Memory just now, and a nice post on how threading sucks. I know nothing compared to these people.

Sunday, February 11, 2007

A link back to referring page in Rails

So here's the quick problem. You have a long list of records in your rails application, such as posts. You end up using the standard pagination offered in rails, which we all know is slow. Regardless, it's pretty annoying to go down into an individual post, edit it in-place, and then hit the back button, since there's no link back to the previous page.

Well, since it's a pagination, there's not a static page to link a "back to list" link. You could pass in the page, but that's a pain in the butt. It's much easier to do:

<%= link_to "Back up to list", request.env["HTTP_REFERER"] %>

This'll put a link back to the same page in the pagination list that you came from. Saves pains. Ends up reading the HTTP spec on headers is a helpful, in addition to some Rails source.

Ends up that "redirect_to :back" also uses the same trick. You can use that in your controller to just redirect back to whatever method called it.

Friday, February 09, 2007

Spore Gameplay Video - Google Video

Spore Gameplay Video - Google Video

I was fascinated by the video of the new Will Wright game. He's the same guy that created SimCity and The Sims. This looks like nothing but good ol' sandbox type of fun, but on a 'powers of ten' scale. Often times, when I describe Will Wright's games, most people ask, "What's the point? What's the goal?" The goal or point is whatever you make it to be.

At this point, some people that ask that question seemed stunned, since it seems to them that a lot of effort was put into something that was pointless. I imagine these are the same people that can't handle open-ended problems.

Other people get it immediately. When you get to make your own goals, you have to rely on your own imagination, and you start to own the world. That actually make it much more fun, and something that you don't tire of easily.

Apple's open letter not quite convincing for music companies

Apple - Thoughts on Music

By now, the world has had some time to chew the fat on this letter, which seems much of a surprise to people. In summary, he says:
  • Apple can sell music, but only if DRM'd according to license
  • DRM requires secrets, and they can be broken by smart people
  • Alternative 1: do as we've been doing
  • Alternative 2: license FairPlay DRM
  • Alternative 3: abolish DRMs
He certainly wins consumers over with this letter. And I agree with him in principle, but I don't think his arguments will convince the music companies, who are the ones that need the most convincing.

All the arguments he gives about DRM-free music makes things easier for Apple not for the Music Monguls. Primarily, Apples doesn't have to use up resources to keep working on DRM. Secondly, if this were to happen, he would make commoditize his complement. A music store's complement is music. And if there were nothing to differentiate the music (one can play music from any store on any device), that's an advantage for Apple. It was the same strategy employed by Netscape: since browsers and servers are complements of each other, we'll give away the browsers (make it a commodity), and sell servers.

One last thing is that the argument at the end doesn't quite hold up. Even if music companies are currently selling over 90 percent of their music DRM-free on CDs, CDs aren't where the future revenues will be coming from, and CD revenue will certainly be declining. So of course music companies will be all hot and bothered by no DRM.

I think DRM-free is the way to go, and music companies will have to accept that the world is changing. In addition, they'll have have to lower their costs in publishing music, as well as finding artists. No more of this, pick a handful, throw it on the wall and see what sticks--and hope that the hit artist will make up for losses with everyone else.

Friday, February 02, 2007

Two submit buttons with form_remote_tag

At the beginning stages of any new framework or language, you can get away with just posting stupid-programming tricks. This was the case with Ruby and Rails. It was fairly new about a year or two ago, but now, it's pretty much old hat, so I sometimes don't bother posting things that I figure out, since I figured it's old news.

Except, I'm still discovering little things here and there. It's not just with the new fancy RJS templates either. Old favorites like link_to_remote() still have unexplored corners (which we'll get to in a minute). Although this one wasn't that painful, I found it as a footnote in the Rails documentation, that others might have easily missed.

So the answer to the common question I was looking for was "How do I have two submit buttons in the same form?" Usually, we need this when there is a set of user-entered data that has more than one action associated with it. For example, in a blog editing page, you usually want to do two things: "save as draft" or "publish". And when you think about it, the file system on your desktop operates with the same metaphor. You select a bunch of files (the user-data), and right-click to select an action (move, copy, delete, etc).

So with a normal form submission, there is the solution of just naming the submit tags, and since the submit button will submit its value along with the form, you can tell which button was pressed:
<%= start_form_tag :action => :post %>
<%= submit_tag "Save", :name=>"save" %>
<%= submit_tag "Preview", :name=>"preview" %>
<%= end_form_tag %>
And then, in your controller, you simply check whether params["save"] or params["preview"] exists, and do the appropriate action, or call the appropriate callback.
def post
if params["save"]
save
render :action => :save
else
preview
render :action => :preview
end

def save
# do saving stuff
end

def preview
# do preview stuff
end
Cake, right? But what if you wanted to do this with a form submitted by XML_HTTP_REQUEST? This hack doesn't work with form_remote_tag, since it serializes the entire form, regardless of which buttons was pressed. I was all ready to buckle down and really learn some javascript, instead of the bits and pieces that I know.

But after combing through the documentation, apparently someone on the Rails team needed to do something similar before. If you look at the very end of the documentation for link_to_remote(), you'll find this:
:submit: Specifies the DOM element ID that‘s used as the parent of the form elements. By default this is the current form, but it could just as well be the ID of a table row or any other DOM element.
It ends up that you can use this to serialize anything containing form elements. But not only that, there are two other bonuses.

One, you can stylize the submit links to look far better than the ugly submit buttons. Two, you no longer need a dispacher method. Each link_to_remote "submit button" routes to its respective actions, which means you can have way more than two submit buttons, and not have a gigantic "if elsif" statement in a dispatcher method in your controller. Neat.
<div id="image_collection">
<% @images.each do |image| %>
<%= check_box "selected_images", image.id %>
<%= image_tag image.path %>
<% end %>
<%= link_to_remote "Group", :url => { :action => :group }, :submit => :image_collection %>
<%= link_to_remote "Delete", :url => { :action => :delete }, :submit => :image_collection %>
</div>
Notice that the parent tag doesn't have to be a form. It can be a div.

One downside to this is design related. Because the link_to_remote call can be anywhere on the page, unlike a submit button which has to be inside a form tag, one can put it anywhere. This added flexibility means that you have to be careful to put the newly minted submit button where it is obvious and intuitive that it submits the intended data. But if you're aware of that, have fun with your new and shiny multiple action form.

Update:
If you use :confirm in conjunction with :submit, make sure :confirm is in front of submit, as order seems to make a difference here.

Saturday, January 27, 2007

"Installing" net/https library in Ruby

This isn't written anywhere that I've looked, so it's either obvious, or I just missed the boat. But basically, in order to use the "net/https" library, you don't need to download it. It's included in the build of Ruby 1.8.4+

However, what you do need to install is both openssl, and the ruby-openssl packages for it in ubuntu in order for it to be working. Tip!

How to install Ruby 1.8.5 from source on Ubuntu

Well, it ends up that installing Ruby 1.8.5 and the associated Gems is a pain on Ubuntu. I'm here to take away that pain, yo.

Installing Ruby 1.8.5 from source

First, get the source tarball of 1.8.5 from the ruby lang web page, and put it in /usr/local/src
sudo tar -xvzf ruby-1.8.5-p12
cd ruby-1.8.5-p12
sudo ./configure
sudo make
sudo make install
If all goes well, you're in business. But if it complains about "cannot open crt1.o"
(which is likely on Ubuntu), you'll divine on google that it needs a "glibc-devel-2.3.3-74.i386" package. But I've done the legwork already, and under ubuntu, it's actually called "libc6-dev"
sudo apt-get install libc6-dev
So try making Ruby again. It should be ok. If not, well, it's not documented here, since I didn't run into that problem.

What I did run into was more pain installing Gems.

Installing Ruby Gems from source


Again, go get the source tarball of ruby gems, and put it into /usr/local/src
sudo tar -xvzf rubygems-0.9.1
cd rubygems-0.9.1
sudo ruby setup.rb

Now, if all is well, you're golden. But since this is Ubuntu, it's likely that you're missing zlib. So, some people seemed to have been able to get it to work from using the "zlib-ruby" package. What I had to do was install zlib from source.

Installing Ruby Zlib from source


Get the Ruby Zlib source and again put it into /usr/local/src/
sudo tar -xvzf ruby-zlib-0.6.0
cd ruby-zlib-0.6.0
sudo ruby extconf.rb

If that didn't work, most likely, you got a bunch of stuff that said:
checking for deflateReset() in -lz... no
checking for deflateReset() in -llibz... no
checking for deflateReset() in -lzlib... no

That means that you need the headers for zlib. So install the package "zlib1g-dev"
sudo apt-get install zlib1g-dev

Then try it again. That should work, and once you get zlib installed, you can get gems up and running.

Friday, January 05, 2007

How to grep for the negation or not or something on the command line.

I've always wondered how to grep for the negation of something. When SubClipse messes up, I end up spending time in the terminal. I hate it. It should at least be able to recover from itself.

Anyway, I wanted to find the difference between two directories. So for diff, you simply use:

diff -rq directory1/ directory2/

And this will give you a slew of which files are different or same. But it'll give you all this stuff about .svn directories that you don't care about. So how do you grep for the NOT of something? I don't know, the regex for it (if someone cares to divulge, I'd appreciate it), but grep has a switch that does this for you:

diff -rq directory1/ directory2/ | grep -v 'svn'

And voila, it only gives you the differences other than paths with 'svn' in them.

Wednesday, January 03, 2007

Testing link_to_remote AJAX calls in Rails

I wanted to be able to test ajax methods in a rails controller, but I wasn't able to find good tutorials on this topic...so either no one uses it, or everyone else just got it right away.

let's say I have the following made up method:

def edit_importance
@friend = Friend.find(params[:id])
@friend.update_attributes(:importance => params[:importance]) unless @friend.nil?
render :partial => "shared/stars"
end
That gets called in the view by:
<%= link_to_remote(image_html, :update => "friend_stars_#{@friend.id}",
:url => { :controller => "friends", :action => :edit_importance,
:id => @friend.id, :importance => nth }) %>

How does this get tested? Well, I figured out there was an xml_http_request call in ActiveController::Testprocess, but I had no idea what to put in the parameters.
xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
It ends up that reading RFC 2616 (HTTP) helped, and request_method is just :get, :put, :post, :delete, etc.

So to test out this, all you have to do is:
 def test_edit_importance
jon_lee = friends(:jon_lee) # from a fixture
old_importance = jon_lee.importance

xml_http_request :put, :edit_importance, { :id => jon_lee.id, :importance => 3 }
assert_template "_stars"
jon_lee.reload
assert_equal 3, jon_lee.importance
assert_not_equal old_importance, jon_lee.importance
end
Remember to reload the old object, since it will still have the old values. You can also use jon_lee = assign(:friend) after the xml_http_request, if you don't want to reload.

Also note that you can test for returns of partials with assert_template. It just has to be a string with the preceding "_" as per partials convention.

As for testing RJS templates, you'd want to look into the assert_rjs plugin.

Incorrect use of exception handling

Exception handling was never something that I looked much into. I've caught exceptions from libraries before, but when it came to coming up with exceptions to throw, I never gave it too much thought. So I looked it up in detail, and to my horror, I had been using it wrong.

Documenting my stupidity, hopefully, I'll prevent others from doing the same basic mistake.

In a rails controller, there is always a simple case of creating a model, but sometimes, there's value checking.

def create
if params[email] == "bob@uiuc.edu"
flash[:error] = "Bobs at UIUC not allowed"
redirect_to :action => :list
return
end
@friend = Friend.create(params)
unless @friend.save
render :action => :edit
else
flash[:notice] = 'Friend was successfully updated'
redirect_to :action => 'list'
end
end

I thought, "Hey, why not move that error handling code to the end, so it reads better?"

class NoBobsError < Exception; end
def create
raise NoBobsError.new if params[email] == "bob@uiuc.edu"

@friend = Friend.create(params)
raise ActiveRecord::RecordNotSaved.new unless @friend.save

flash[:notice] = 'Friend was successfully updated'
redirect_to :action => 'list'
rescue ActiveRecord::RecordNotSaved
render :action => :edit
rescue Exception
flash[:error] = "Bobs at UIUC not allowed"
redirect_to :action => :list
end

That way, the error handling code doesn't really get in the way of the 'good condition' code. I personally think it's easier to read, though apparently, this is a bad idea apparently, mostly due to overhead costs in running through an exception, even if there were no exceptions thrown, and that I'm essentially using it as a goto statement. And as everyone knows, gotos taste like ass.

Exceptions are to be used when the method or object that the error occurred doesn't know what to do with the error at that time. Therefore, it will throw an exception, and hope that some other part of the code elsewhere up the stack will know what to do with it. And so hence the adage: "throw early, catch late".

So I'm a reformed exception handling abuser. I guess when you have a new hammer, the world looks like a nail, until someone sets you right.


http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

http://today.java.net/pub/a/today/2003/12/04/exceptions.html

Thursday, December 07, 2006

Adaptive polling as an alternative to HTTP streaming

I've been fairly interested in how the HTTP protocol works lately. For a long time, I didn't think much of it. It sat on top of the TCP/IP layers, and there wasn't much I need to do with it. It did what it was suppose to do: let clients fetch pages from servers upon request.

But then I started reading about REST (about a year after the hubbub), and in general about why stateless connections are desirable (it's scaleable). This lead me down equally saturated road of AJAX and eventually some joke about Comet. What was coined as "Comet" was really a play-on-words for another cleaning product applied to another old web technology--namely persistent HTTP connections.

Traditionally, HTTP doesn't allow servers to push data to clients. With the way the web is architectured, most clients are behind firewalls and routers, so the server has no way of knowing which machine to push it to, unless it was talked to first. In other words, only clients can initiate data requests. This isn't enough sometimes, as servers might need to push data to clients, such as live stock ticker feeds in your web browser without page reloading.

The trick to persistent HTTP connections was to get clients to initiate the XHR connection to the server first, and for the server to not immediately reply to the request. The server will hold off on replying (leaving an open connection from the client) until there's actually a message to be sent back to the client (i.e. when there's a new stock update). And that way, it'll look like a server-push. And then the client initiates another connection all over again after a certain wait.

This is the way that LivePage and JotSpot Live implements their responsive apps. However, the concern for most people is that it doesn't scale--at least not when they tried it circa 1998. A server having thousands of open connections to clients will probably buckle, although Twister might have already solved this problem, but I haven't looked into it much yet.

Another concern of mine is that the Ajaxian pattern of HTTP streaming can also require the client and the server to hold state. This is because a server does not know what version of the last set of updates it has received. Therefore, the client sends the server what version it has had (state), and the server will only reply if it has a newer version. This seems to violate the REST architecture. While I only have the original 2000 thesis to say this is not scalable, it seems to make servers a bit more complex.

So why not use polling? Usually, it's because too much polling is wasted bandwidth. And not enough polling, you have stale data. So depending on the nature of the data that you're trying to stream, polling may or may not be a solution. However, it is stateless, and it should scale better, as long as polling isn't overdone.

That lead me to wonder if there was adaptive polling. Why not have clients try and predict their polling frequency based on past observations of their past polling to optimize their polling success. Polling success is defined as every time they poll, they get 1) new data and 2) freshest data.

It ends up that it's a very similar problem in two other fields (and I'm sure many others): web caching and sensor networks. In web caching, you want to cache web pages, so that you can show clients results faster if the page hasn't changed. How do you know the page has changed, and when to throw away the cached copy and obtain a fresh one? In sensor networks, each connection is expensive in terms of energy consumption. How do you know when a node has fresh data, and how often should you poll to obtain polling success? In this case, a master node is analogous to the client and a slave node is analogous to the server.

There's an additional issue to consider. One wouldn't want all the clients hammer the server all at once for a poll. That would make it seem like a flash mob to the server at periodic intervals. It would be best if the clients can spread out their requests, so that the traffic to the server is more constant. That way, the server wouldn't be overloaded. How do you coordinate the polling times of thousands of clients? Wouldn't that create more traffic on the network for the clients to ask each other? I'm guessing no, because the delay in response time from the server would indicate how busy it was at this moment. Using that as a type of "pheromone" from other clients (indicator left by other clients), a client should be able to adjust its offset time for its next polling request.

Sunday, December 03, 2006

Splatting in case statements

RedHanded � Wonder of the When-Be-Splat

I always feel like I'm playing catch up to Rubyists.

BOARD_MEMBERS = ['Jan', 'Julie', 'Archie', 'Stewick']
HISTORIANS = ['Braith', 'Dewey', 'Eduardo']

case name
when *BOARD_MEMBERS
"You're on the board! A congratulations is in order."
when *HISTORIANS
"You are busy chronicling every deft play."
end


That's pretty damn cool. The thing about new languages is that when you're learning to write with it, you'll write it in the style of the old language that you're use to. C programmers will write C++ as if it were C. Java programmers will write Python as if it were Java. Therefore, you might think that there isn't much to be gained from the new language other than some syntactic sugar sprinkled here and there.

As least for me, being open to other constructs like blocks, closures written more like functional programming has lead to more succinct and readable code.

a = [1, 2, 3]
Hash[*a.collect { |v|
[v, v*2]
}.flatten]


I would have done this with a for loop before, and that's probably less readable. But I have to admit, succinct code only has meaning if you know the vocab.

Thursday, November 16, 2006

FireBug for all other things

When working with RJS templates, it can be a pain, especially if you roll your own javascript in there. There's almost no way to debug it, so you have to be very very careful, or use your brain-the-compiler.

But aside from that, try out Firebug. It's a pretty need in-browser javascript debugger for Firefox.

Sunday, November 12, 2006

Symbol conversation in MMORPGs

Blue Rabbit�s Climate Chaos - Adventure Games - GamersHood - Online Games Paradise

This was something that was shown to me by Alison. I just tried it out, just to see what was fun about it. Didn't play much, but I was struck by the fact that this game decided to employ pictograms instead of words for conversation.

Now, I don't know why Blue Rabbit employed this mode of conversation. Perhaps it's because the target audience is young children.

However! I think this would be key to building a more dynamic MMORPGs. I haven't played World of Warcraft, so I don't know if quests are static. But I remember in Everquest, the quests were the same, time after time. Oh sure, there might be grace periods where it wouldn't be there, but for the most part, the same person would have his daughter kidnapped time after time.

Instead of having static quests, I think it would be better to have dynamic quests. It gives a better sense of realism to the world that the gamer is playing in, if the NPCs(non player characters) had different needs at different times.

In the Sims, each NPC is an agent with goals and needs. And it basically interacts with its environment to fulfill those goals and needs as time progresses. But never do any of the characters ask another Sim to fulfill those needs for him. Sure, they have conversations with each other to fulfill the direct need for being social. But they never ask the messy roommate to clean up his mess. They always get irritated and clean it up themselves, or rely on the player to make someone else clean it up.

With a simplified vocabulary of pictogram language, an NPC would be able to express what he desires. And that would be up to the player in the quest to fulfill it. These goals, like in the Sims would change as the environment and needs change.

file_column is easy to use

HowToUseFileColumn in Ruby on Rails

File_column really is a cinch to use. But not without knowing that you needed:

add_column :entry, :image, :string

in the migration. And here I was reading through file_column code. Things are always clearer in hindsight. But it did teach me a few tricks here and there, about how to add dynamic methods to objects.

Thursday, November 09, 2006

Annologger update: Commenting is available!

It's got no pictures of stars, but it's simple. Commenting is up for annologger!

Human verification CAPTCHAs will be done tomorrow, so that you don't get comment spam. In the meantime, get your friends, your readers, your fans, to comment, comment, comment away.

Friday, November 03, 2006

Annologger Update: By popular demand, Annolog Badges available

I'm happy to announce that you can now get annologger badges for your blog or website! What's a badge you say? It's basically a code snippet generated for you that you can cut and paste into any webpage, blog or otherwise. That way, you can floss your events on your blog now. :)

You can get your own annolog at http://www.annologger.com. Under the goodies section, you can create your own annolog badge.

It took longer than I had anticipated, due to not ever working with rjs templates before. I'll write a tutorial up later. On to comments for your annolog!



Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Late to the RESTful party

Apparently, I'm the last fool to really read about it. I only first heard about REST maybe 2 months ago by a long post by one of the rails guys.

Lately (as in the last 6 months), there's been a resurgence in figuring out the HTTP protocol. It's suppose to be RESTful. Mainly, the idea that network architecture are seen as a collection of resources identified uniquely by a URI. And that the whole network application is simply the user in a large state machine, where traversing the different resources equate to state transitions. This has implications of server and client design to be simpler.

Each HTTP request also has a method associated with it. The methods in HTTP most commonly used are GET and POST. In the early days of the web (ie when we were in college), I saw that forms submitted by GET or POST, and for a long time, I had no idea what the difference was. GET is intended to "read" but make no state changes in the server, and POST is intented to make state changes. So doing form submissions with GET is not only semantically wrong, but insecure, since it puts form contents in the url.

In addition to GET and POST, there are others, (I never knew). And the bunch of them map well to CRUD(Create, read, update, delete) operations. And using the native HTTP methods, you can take advantage of things already built into HTTP, like caching (for scalibility) without having to build it yourself.

Here's a simple intro , and I think one of the articles that spawned the discussion. This is the original disseration on RESTful architecture, if you want to read it.

Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Tuesday, October 31, 2006

Annologger Update: now with microformats and iCal


It's been long overdue, but I've added features that I've wanted for some time--mainly microformats and iCalendar. iCalendar isn't fully featured yet, meaning if you subscribed to it using your outlook calendar, you cannot update your annolog from your outlook calendar. That said, I'm working on it, and trying to keep the code base organized and healthy, so that it's not a mess that can easily be broken. It's like cleaning up your kitchen as you cook.

So while it might not look like much, there have been some minor bug fixes and major refactoring to get these features in. Thanks for the feedback so far, and keep them coming. :)




Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Thursday, October 26, 2006

Time can be needlessly complicated

International standard date and time notation

To think that of all things I could have picked to build, it was something centered around time. Having worked on a sunrise/sunset and moonrise/moonset calculator, you'd think that I would have learned my lesson.

Time is difficult because there's always exceptions to the rule, and some specifics are unclear on first thought.

Does midnight belong to the beginning of the day, or the end? Is the end date and time of an all day event inclusive or exclusive? It ends up that luckily, there were plenty of smart people that thought about all of this decades before I came about, but they like to write in a boring prose, in specs like ISO8601.

By the way, midnight belongs to the beginning of the day, and all day events have exclusive end times. However, that's not what people mean when they say they're going to iceland from october 18th to october 22nd. When people say that, the date is inclusive. Aye.

And do you store all times in UTC? Depends on the application. Throw in time zones, there's even more confusion, not to mention taking day light savings into account. And if you really want to get nitpicky, there's always leap years and leap seconds to think about.

Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Saturday, October 14, 2006

Enumerable still...

Still playing around with Enumerables. It was almost not worth mentioning, but it's a short post. I was looking for a short way to read in a file's contents all into memory all at once. Normally you wouldn't do this, because it eats up memory if you do it this way. But my files were short.
File.open('README', 'r') do |file|
file.inject { |contents, line| contents << line }
end

This will open up a file README and return the entire contents as a string. It's pretty cool, since I don't have to muck around with temporary variables much...and it's readable...well, if 'inject' makes sense to you. Also cool is that, like Java container classes, as long as you implement 'each' in your Ruby class, you get all the ones in Enumerable for free. You just have to include it.


Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Friday, October 13, 2006

Screencast of Annologger

Screeniac � Annologger.com

I'm usually pretty busy so I don't search often on the web for what people have been saying about Annologger. But for the first thing that I put out, it's both a bit exciting and apprehensive to hear about it.

I had a really hard time choosing a name for it. To this day, I'm still not quite satisfied with the name, but apparently, people get what it is. So that's good news.

And secondly, it seems easy enough to use, so people seem to get it. I've had a lot more japanese users lately, (presumably from this review and others), and they seemed to put more stuff on there than 'test'.

But all in all, I need to put in the other features that I've been dying to get done, so people get see what its potential is.

Time to get back to work.

Tuesday, October 10, 2006

Singleton classes not seemingly the same as Singleton pattern

So I was looking at someone else's code today, and I saw this:

module Formats
class BasicNestedFormat
class << self
def foo
...foo code...
end
end
end
end


Huh? What did "<< self" mean? I guess I didn't read my Ruby book closely enough. It's apparently a "singleton class", which doesn't seem to be exactly a "singleton pattern".

A "singleton class" is a sole metaclass that 'holds' methods for a single object. It would have been called a 'metaclass', except that it's not the class of a class, but a class of a class that only exists for that one object.

Keep in mind that this is the case because you can add methods to objects in ruby at runtime. Since everything in Ruby is an object(even the classes), it has to go somewhere, and in an anonymous metaclass is where it goes.

One can almost think of them as 'static' methods in Java. However, because objects can be added methods at runtime, they don't necessarily belong in the class, but to the metaclass of an object that only belongs to that object.

They're not like 'static' classes of Smalltalk or Java. You can call self (like this in Java) in Ruby's 'static' methods.

It's a curious construct because you can use it to specify 'static' methods all in one go. It's the equivalent of the following:

module Formats
class BasicNestedFormat
def self.foo
...foo code...
end
end
end


Apparently, you can also use it to do prototype factories. There's more to it than meets the eye. You can find better explainations here and here.

Ruby is weird.


Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Thursday, October 05, 2006

The need to write code, the need to ease reading

Lately, I've been doing more thinking, reading, prototyping, and moving, than I've actually been writing code. One of the things that got me thinking enough to write this post was the classic syndrome of software developers and engineers to be gripped by the "Not invented here" syndrome.

Some would say that's because engineers and developers like to create. That's part of it too, but I think it's also partially because we only get better if we write things ourselves. The only way to learn about something fully is to actually do it. The problem is, a lot of things that we would learn by doing, has already been done for a while now. Beyond linked lists and parsers, most anything you can think of has already been done. Not that we can necessarily do it better, but doing it is half the fun, and it's the only way you can get better.
You won't become a better programmer by passively studying other people's code. Similarly, you don't magically become a better writer by reading a lot of books. You become a better writer by.. wait for it.. writing. - Jeff Atwood
So it's a balancing act between using other people's code and reusing code to be more productive, and writing your own to learn and reduce dependencies.

Another aspect that compells people to write things themselves is that
It's harder to read code than to write it. - Joel S.
I think it's because code, like math, like poetry, is dense. There are meanings and implications that aren't literal and aren't at the surface. There are implications for what gets written at every line, and relies on a culture and context behind it to fully understand it. This is why it's hard to read math equations, Alexander Pope(first one that came to mind), and much less code.
But that doesn't mean that there can't be language constructs to faciliate the ease of reading code. Python does it as a language choice that restricts whitespace. Maybe the computer doesn't care about whitespace, but people surely do.

I have recently found that iterators with descriptive names actually help in reading code. Instead of a generic for or while loop, it kinda helps to have collect, and inject.

It would be nice if code was self-documenting, meaning that you would be able to tell what the code was doing from what the method names and variables were, rather than the comments around it. It would be nice if method signatures were all you needed to know what to put into a method (and no, static typing doesn't help completely here). I wonder if language constructs could help out with it, or would we always need to rely on the stylistic tastes and discipline of the individual programmer to write readable code and documentation?



Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Looking for cumulation in Ruby?

Module: Enumerable

This is pretty basic, but I only recently discovered it. I have a task that I do often in code. Usually, there is some list of things that I'd need to go through, and tack it on to another list if it meets some condition.

funny_posts = []
posts.each do |post|
if post.is_funny?
funny_posts << post
end
end

The same problem appears when I try to summate all the things that fit some condition. I dislike having the initialization there in the beginning. Is there a better/prettier way? I would have thought collect() would be it, but it is mapping one value for another. It's almost like a function in math--a certain input gives you a certain output.

So it was finally that I saw inject(), and it seems to be what I want.

funny_posts = posts.inject([]) do |funny_posts_thus_far, post|
if post.is_funny?
funny_posts_thus_far << post
end
end

I think that'll work. The difference doesn't look like much, but somehow it bothers me when I have that floating assignment before the loop. It's easy during maintainance that someone moves 'funny_posts=[]' far away from the loop, when semantically, it's a part of how the loop will work correctly.

inject() also applied to cases where you're trying to find the maximum in a list.

# find the longest word
longest = %w{ cat sheep bear }.inject do |memo,word|
memo.length > word.length ? memo : word
end
longest #=> "sheep"

I guess it's the difference between functional programming and procedural...using return of value instead of relying on side effects. I use to write off functional programming as something that was antiquited, but now, I'm finding gems here and there in functional programming. It makes me wonder how procedural took off so rapidly. Perhaps programmers think easier in procedural programming?

Update: I guess I should read Enumerable more closely. The example I had with collecting funny posts is done with a method called partition() in Enumerables.

Sunday, October 01, 2006

The names of things

In a number of fairy tales and old legends, the name of a fairy, a monster, or a god was pivotal to the story. 'To know someone's name is to control them', it is said. I actually never gave it much thought growing up. How silly. What's in a name? A Rose by any other name would smell just as sweet.

But when it comes to ideas and concepts, a name is pretty important. Naming a variable, class, or method correctly means that there's some convention the reader of the code can go by to be able to infer how to use it. It's a type of documentation.

So when it comes to finding names for things, I have a hard time. How are 'agreements' and 'disputes' related? Are agreements and disputes the same type of thing? If so, what is the name of that thing? Or are they not the same type, but merely the same thing in different states? An agreement is the alignment of opinion between two parties where a dispute is the disalignment of opinion between two parties?

How about the person that 'seconds a motion'? What do you call that person? What do you call the person that brought up the motion in the first place?

When I think about it, public method signatures should be well designed, so that, like well designed tools, it should be obvious how to use it. However, 'obvious' comes with a background and context, and even culture.

Update:
According to wikipedia, A person that makes the motion is a mover. The person that seconds a motion could be called a supporter. And according to my lawyer and english major friends, agreements and disputes are apples and oranges, apparently. agreements and disagreements are more on the same type.

Saturday, September 30, 2006

Designing iPod vulnerability into it makes it cuddly

Everyone often raves about apple design. How sleek they look. How cool they look. However, there are sometimes practical design aspects that people complain about. Namely, I remember the first generation Nanos would have a faceplate that scratched easily.

However, I wonder if there is a side to the design that hadn't been considered. For a device like the iPod, it had the requirement of storing large amounts of data, but flash devices weren't that big in size yet. Therefore, hard drives were the only choice. However, we all know that electronics and especially hard drives are sensitive to shock. It would lose its performance and its ability to store data if it was knocked around all the time.

Whether it is intentional or a consequence of making it look sleek, the exterior of the iPod, and perhaps its vulnerability, leads people towards behavior that make them take care of it. They buy protective accessories for it, and I'm sure they throw it around less than their phones.

It would be brilliant if that was part of the requirements and spec: to get people to take care of their iPod by making it both sleek and vulnerable. It's much the same way (in function, not in emotion) that a certain instinct gets triggered when we see cute fuzzy things, except Apple managed it without fur or a large forehead.




Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Sunday, September 17, 2006

Waiting for camera manufacturers

Jeffrey Veen

You know I'm not writing code since I've been posting a lot, and also reading feeds. But one last post...

"But simplicity isn't just interface improvements, but acknowledging the right tool for the job. One of the things that has always impressed me about the iPod, for example, is that the devices have no capacity for editing metadata, deleting or moving songs, or any of the other mundane tasks of maintaining your music library. Instead, designers at Apple moved all those tasks to iTunes, exploiting your computer's keyboard, mouse, and screen real estate. Flickr takes the same approach. They could have waited for camera manufacturers to add GPS chips or asked cameraphone users to thumb in their location. They chose, however, to exploit the fact that metadata can be added asynchronously without much penalty."

spoke to me. I have been thinking about this, and was wondering if geo metadata was in pictures. My initial thought was, camera vendors really need to move beyond just taking pictures. Cameras should send photos to a repository automatically over wifi, or cameras should record not only when but also where you took a photo.

Sometimes, you can't, because you don't have any control over those products. Therefore, you make due with whatever interface is available to tie things together first, and then slowly make it better.

Simple yet deep

Point and shoot software - Signal vs. Noise (by 37signals)

I think 37signals has it right with making things simple, and emphasizing simplicity, at least on a first use basis. But I still maintain something that Guy Kawasaki said in his book, art of the start...

I'm paraphrasing, but basically simple for new users, but deep for veteran users. There's something to be said about keep mastering a product over time.

New users, no matter how tech savvy, like simple to use. But there's something to be said for the constant exploration of a device (or domain for that matter). I liken it to driving stick after learning to drive automatic.

It's often hard to build the two conflicting things in a product...control vs simplicity. But I think it's important to think of deepness as well.

Too little focus in the information we get

My Whole Life in Happy Little Folders, by Jeffrey Veen

Jeffrey Veen was complaining that it seemed like all he did was un-bold things in RSS feeds. There's just so much info that you get overwhelmed. This was one of the primary reasons I unsubscribed to ridiculously prolific blogs like smartmobs, and now signal vs noise has hell of a lot more noise now. I still subscribe due to the few gems that get dropped occasionally. But once I find others that are more quality and less quantity, I'm ready to drop them off my feed reader.

But other than complaining about blogs, this was the primary reason that I moved from bloglines to reader google. I found that having the number of unread items just felt like I was being a slacker by not reading it. Google reader is much more unforgiving. News you don't read just become that--news you don't read, and it just scrolls on by as the days past by.

It's not something foresight would have seen, unless you've actually used a feed reader before. But I'm glad that google got that right with their feed reader.

I think there's always phases to technology, as others pointed out. But beyond the adoption curve, there is the phase where the users are over-saturated, and need some type of filter. This is often overlooked in my opinion.

Saturday, September 16, 2006

The FIRST keynote of Steve Jobs 1984

cyberian.nomad.blog: The FIRST keynote of Steve Jobs 1984 - a Legend !

I often wonder what it'd be like to go back to the past knowing what you know. It's been a good 22 years since 1984. The technology back them seems primative, although you recognize a lot of the same elements that you do now.

Could some people envision 2006 if we were to tell them about it in 1984? I think some would. And others, were probably more optimistic about certain things. Notice the AI thing with the Macintosh talking.

What would it be like in 20 years? I have to admit, I am optimistic about the advance of technology. I have dreams for the future. I dream that computing will really be ubiquitous, and that mobile computing and information gathering will be more common. I dream that augmented reality will come to be common place, whether on PDAs, cell phones, eye glasses, contacts, VRDs, or ocular implants. Devices, whether microwave to cell phones, will really begin to interoperate on open standards, and have a collective intelligence for the whole house. I dream that bio interfaces will allow the blind to see, to store information, or to access information. I dream that quantum computers will start to appear on the market. And I dream that code will be modular, reuseable, simple to read, and simple to maintain. haha.

Friday, September 15, 2006

First Principles of Interaction Design

AskTog: First Principles of Interaction Design

To be honest, this is a boring list of things to read through. Some seem obvious and common sense. But you'll find that in design, often times, obvious is shadowed by functionality and common sense is hard when you have constraints. This might have been better reading if it contained examples, like in The Design of Everyday Things.

But what I noticed was that these principles were very similar to those of game design. I can't pinpoint the article this afternoon, since I read it close to six years ago. But there was an article on gamasutra that talked about how hard it was to design games to make the player happy.

The game designer has to balance the hardness of the game. Too challenging, the game will be unobvious and frustrating (like this game was purported to be). Too trivial, the game will lose the interest of its players quickly (like Eat the stick.

I remember another thing about consistency. One game designer was talking about how he met a gamer, and the gamer had the idea that once you go to another section of the game, all the properties of the spells you could cast would change. The game designer went into detail about how this was one of the worst mistakes that early game designers make. Consistency affords a sense of building up a knowledge of the world around you from a player point of view.

If every time you went to another section of the game, and you had to relearn the mechanics of the game all over again, it would probably piss you off.

In a lot of ways, there are parallels between game design and application design. I also remember all those comic strips in the 90's satirizing how kids can't get jobs playing video games growing up. I think that's more and more untrue, with the way the gaming industry is unfolding. The idea the games are a diversion and are for children will be a thing of the past.

Monday, September 11, 2006

Friendships aren't binary

I feel old. Partially because social networks separate me from friends that are merely two years younger. I am part of the 'Friendster' generation. I was able to sign up for that, before the meteoric rise of 'MySpace', and 'Facebook'. I ignored MySpace invitations, writing it off as 'nothing special' (I also thought that Britney Spears was going to be a one-hit wonder), and by the time facebook rolled around, I had already left graduate school.

While I'm excited about social network applications, my opinion of social network apps was that they didn't actually DO anything. Beyond the novelty of being able to see my network, trouncing about the network didn't actually let me get anything DONE. No wonder why people called them the biggest waste of time. Perhaps, like bad TV, it was just a reaction to a guilty pleasure.

However, it was recently that I was able to sign on to Facebook, because I found that there is an alumni web mail service that I was able to utilize. I liked the Facebook interface immediately. Unlike friendster, it was clean, and it was fast. It didn't feel cluttered at all.

On the friends page, it would tell you that a profile was updated, and yet, I didn't know what. So I never really browsed, knowing that I won't want to spend time trying to find it. Therefore, I was pleasantly surprised by the mini-news feeds: now I knew exactly what was updated, so I don't have to look around for it.

Here, I was able to see what my network was doing. What groups they were joining, what messages they were posting. Perhaps here-in lies the utility of a social network; an individual would know what's going on with his or her friends. The flipside of this feature was that most people felt like their privacy was invaded.

It's odd, because I, as a newcomer, didn't have much expectations of how things worked, so I more readily accepted the mini-news feeds. Therefore, I wonder if facebook had this feature in the beginning, would there be as much of a protest? Perhaps it would have had slower growth?

I think the assumption that facebook developers had was that
  1. users wouldn't mind that their friends knew what they were up to because of #2
  2. everyone named as friends were trusted
  3. all friendships are created equal
In reality, often times, the people in your friendship list might not be friends, but contacts, or campers. And even if the only people that you accepted were friend friends, not all friends are created equal. I think it's safe to say we all have aspects of ourselves that we show in front of some friends but not others. I remember I had friends in college that did weed or drank a ton, but they never invited me out with them to do it.

Given that, I can definitely see how they went ahead and did it. And often times, as a developer, if you don't simplify things, you'll never get anything done.

One, facebook's reaction to the backlash was a pretty good one, in my opinion. They put out a major announcement, as well as give one-click options to remove it by choice within two days. I applaud them for it. However, they managed to keep things simple. Choice can easily come with its strange bedfellow, complexity.

Second, perhaps, the model for naming friends should be changed. Perhaps it shouldn't be activated by individuals, but rather, inferred through activities. Then, you can be able to tell between active friends, and long lost friends. You would also be able to tell the context of the relationship, as well as which domain it falls under. Then perhaps, privacy would be less of an issue with a selected multicast of information, such as photos, who I'm dating, and where I'm going.



Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Sunday, September 10, 2006

Cavets for doing what you love

The usual thing that you hear we tell kids is "you can be whatever you want to be" when it's really not entirely true. A more accurate saying might be, "you can be whatever you work hard at, even if you might not be the best." For adults, the line is, "do what you love."

What if you suck at what you love? If American Idol is any indication, passion doesn't always equal aptitude. Beyond American Idol, there are plenty of people that are always 'striking it out on their own' that are still doing so. There's plenty of actors and actresses that are waiters and waitresses. I suppose the assumption is that when you do what you love, you will spend time doing it, instead of going out, instead of playing video games, instead of watching TV. You'll keep going at it even after failure and rejected. And the biggest assumption is that you'll get better as you keep going at it.

So keep at it. And get better.



Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

Thursday, August 31, 2006

Getting Started - UIDWiki

Getting Started - UIDWiki: "Turn on Javascript errors for extensions. Normally the Javascript console only displays errors for web pages, not for Firefox or its extensions. Go to the URL about:config and turn on javascript.options.showInConsole."

This'll help speed development.

Sunday, August 27, 2006

Moving people versus building things.

My sister often marvels at my ability to build things.
You know, I always feels useless around you because you have tangible skills.
Being an engineer, I often found envy from the liberal arts majors on having 'tangible skills'. I was in a business writing class that was required of all majors, where we learned the basics of writing letters, resumes, and memos. During the resume writing session, we were doing peer critiques.

Looking at the number of projects that I've done, the programming languages I knew, the liberal arts majors exclaimed "Wow, you actually have skills!"

However, I find that the ability to move people is just as important. There are many things you can do as an individual nowadays. We have plenty of tools and information available for us to do that, more than ever. And yet, there are certain types of things where you need a group of people to move forward with together. And in order to do that, one has to be able to guide people in the same direction, to be able to move them in the same direction.

That, I find to be a skill more enviable.

Friday, August 25, 2006

Temporal Expressions as a cousin to Regular Expressions

When thinking about recurring dates, I realized that it's actually a pretty tough problem. How do you represent recurring dates in a database? Ideally, you don't want all the instances of recurring dates from the epoch until the End of Time. I had an inkling that it should be possible to express a generalized sense of a range of dates, but I didn't really know exactly how that would manifest itself.

That's when I started looking for what people had done before me, since I dislike reinventing the wheel. The first thing I came upon was this recurrence python module. Reading his comments in the code, I thought being able to express dates as an equivalent of a polynomial made a lot of sense.

In fact, functions are condensed form of a set of numbers. Not all sets of numbers can be expressed by functions, but most of the ones that we care about can usually be. That makes them useful. Are there equivalent of 'functions for dates'?

That's when I ran into Runt, a ruby library that deals with recurring dates, which are based off of temporal expressions pattern by Martin Fowler.

But it wasn't exactly what I had in mind when I read 'temporal expressions'. I was thinking that Martin Fowler came up with something like regular expressions, but for time. After reading the tutorial, it wasn't exactly what I had in mind. It used classes and patterns to represent recurring dates, rather than an expression, like a function.

So we come to the crux of my musing. Are there the equivalent of regular expressions for time, and would it be a good idea to use it?

When I first started using regular expressions, I thought it was hard to use. Not only could I not remember what some of the symbols meant, but it was dense and not easy to read. A complicated regex quickly got out of hand. I wondered if there were alternatives to regex. And apparently I wasn't the only one either(and that post was from 2001).

If I were to use something like regex for date and time, like a temporal expression--tempex*, I wouldn't want something syntactically like regex. It's really rather hard to read, even if it's powerful (read "dense": can say alot with a little).

In drawing the parallel between regex and functions, that could be the reason why people find math arcane: the expressions in math and regex both can say alot with a little.

One should be able to represent dates and times in a matter that you can express sets of dates succinctly, and event better, be able to do operations on them, such as union, intersect, and difference.

I was surprised that it seems like there's nothing out there that I can find that is a regular expression for time. This shouldn't be the case. Runt is the closest thing that I can find so far. Anyone else know of anything else out there?

* I'll have to pick some other name later. people already use the term for natural language processing of time-related phrases, in addition to Martin Fowler's usage for the pattern

Friday, August 18, 2006

Back to coding

I've been getting back into the swing of things after a brief haitus. Currently, there's a code freeze, so I can catch up with the tests. I know I'm not suppose to do it backwards like this, but when you're sketching out how things should work, updating both code and tests are tedious.

I figured this is a good time to update all the tests, so code freeze for about 3 days. Code coverage at...53%

I'll do more tonight. Then it's off to do more cool and exciting features!
  • RSS feeds
  • iCal publishing
  • better date/time selector
  • end dates that matter
  • photo posting
  • "I'll go if I can"

Friday, August 04, 2006

Major Nelson's Xbox 360 can blog

Major Nelson's Xbox 360 can blog

devices can blog...it's a readable log, really. Machines often log events that happen to them, but never really in a human readable form with style and prose. This illustrates that it's definitely amusing and possible, especially if personality engines were invented and utilized.

But in the end, the devices reflect its owner, and how they live their lives. As more and more devices log your life, you can compile stats and see how you actually live it in the long run, and be able to make changes and adjustments if you wish. This, to me, would be the ultimate personal information. Privacy in this term would have to be strictly protected.

Wednesday, August 02, 2006

Wheel robots makes designers rethink cars

This article about Smart Cities Team at MIT excited me a bit, not so much because of its potential (which is neat), but more the fact that they rethought the engineering of the car.
The MIT concept car is a complete re-think of vehicle technology. For a start, there is no engine, at least in the traditional sense. The power comes from devices called wheel robots. "These are self-contained wheel units that have electric motors inside,"

A traditional engine puts engineering and design restraints on what type of wheel rotations and movements are available. Because of this restraint, we've gotten so use to the idea of a car only having steering in the front two wheels.

With wheel robots, all the wheels can rotate independent of each other. That means that you can rotate while you're going forward, or slide into a parallel parking space. When new technology becomes available, we should take a step back and rethink why design and engineeering decisions were made in the first place.