Saturday, April 07, 2007

Erlang and neural networks, part II

Two weeks ago, I did a post about Erlang (Part I), and how a simple feed-forward neural network might be a nice little project to do on the side, just to learn about Erlang. Here's what came next.

State of the Purely Functional

In the transition from imperative/procedural programming to functional programming, there are obviously things that you have to get over. You'll hear this from a lot of people just learning functional programming for the first time (myself included). The hardest thing for me to get over in a pure functional language is the absence of state. My first reaction was, "Well, how do you get anything done?"

Not having state has its advantages, and you'll hear stuff about side-effects and referential transparency. But I'd like to think of it as, things that don't have state can't be broken--they just exist. However, state is useful in computation, and different languages have different ways of getting around it. With Haskell, you use monads. At first, I figured it was the same with Erlang. But in this short tutorial on Erlang, it simply states that Erlang uses the threads to keep state.

This maps pretty well with what I'm trying to do. Each perceptron will be a thread, and send messages back and forth to each other as they fire and stimulate each other.

The essence of a perceptron




So once again, this is a perceptron. It's a weighted sum (a dot product) of the inputs, which is then thresholded by f(e). So we'll write a thresholding function and a weighted sum in Erlang.

We start by declaring the name of the module, and the functions to export from the module.
-module(ann).
-export([perceptron/3, sigmoid/1, dot_prod/2, feed_forward/2,
replace_input/2, convert_to_list/1]).
I exported most of the functions, so I can run them from the command line. I'll remove them later on.

First we write our thresholding function. We will use the sigmoid function as our thresholding function. It's pretty easy to explain. A value, X goes in, another value comes out. It's a math function.
sigmoid(X) ->
1 / (1 + math:exp(-X)).
Since I wasn't as familiar with all the libraries in Erlang, and I wrote a dot product function, and it wasn't too bad. Erlang, for the most part, doesn't use loops, just as Ruby doesn't. They both can, if you want to write a FOR control function, but the common way is to use library functions for list processing, list comprehensions, or recursion. The first part is the base case, and the second part is what you'd do if the "recursion fairy" took care of the rest.
dot_prod([], []) ->
0;
dot_prod([X_head | X_tail], [Y_head | Y_tail]) ->
X_head * Y_head + dot_prod(X_tail, Y_tail).
Simple, so far, right? So to calculate the feed forward output of a perceptron, we'll do this:
feed_forward(Weights, Inputs) ->
sigmoid(dot_prod(Weights, Inputs)).

The body of a nerve

So far, so good. But we still need to create the actual perceptron! This is where the threads and state-keeping comes up.
perceptron(Weights, Inputs, Output_PIDs) ->
receive
{stimulate, Input} ->
% add Input to Inputs to get New_Inputs...
% calculate output of perceptron...
perceptron(Weight, New_inputs, Output_PIDs)
end.
This is a thread, and it receives messages from other threads. Currently, it only accepts one message, stimulate(Input) from other threads. This is a message that other perceptrons will use to send its output to this perceptron's inputs. Notice that at the end of the message, we call the thread again, with New_Inputs. That's how we will maintain and change state.

Note this won't result in a stack overflow, because Erlang somehow figures out not to keep the call stack. I'm guessing it knows it can do so, since no state is ever kept between messages calls that everything you need to know is passed into the function perceptron, so we can throw away the previous instances of the call to perceptron.

We do come to a snag though. How do we know which other perceptron the incoming input is from? We need to know this because we need to be able to weight it correctly. My solution is that Input is actually a tuple, consisting of {Process_ID_of_sender, Input_value}. And then I keep a list of these tuples, like a hash of PID to input values, and convert them to a list of input values when I need to calculate the output. Therefore, we end up with:
perceptron(Weights, Inputs, Output_PIDs) ->
receive
{stimulate, Input} ->
% add Input to Inputs to get New_Inputs...
New_inputs = replace_input(Inputs, Input),

% calculate output of perceptron...
Output = feed_forward(Weights, convert_to_list(New_inputs)),

perceptron(Weights, New_inputs, Output_PIDs)
end.

replace_input(Inputs, Input) ->
{Input_PID, _} = Input,
lists:keyreplace(Input_PID, 1, Inputs, Input).

convert_to_list(Inputs) ->
lists:map(fun(Tup) ->
{_, Val} = Tup,
Val
end,
Inputs).
The map function you see in convert_to_list() is the same as the map function in ruby that would go:
def convert_to_list(inputs)
inputs.map { |tup| tup.last }
end
Now, there's one last thing that needs to be done. Once we calculate an output, we need to fire that off to other perceptrons that accept this perceptron's output as its input. And if it's not connected to another perceptron, then it should just output its value. So then we end up with:
perceptron(Weights, Inputs, Output_PIDs) ->
receive
{stimulate, Input} ->
New_inputs = replace_input(Inputs, Input),
Output = feed_forward(Weights, convert_to_list(New_inputs)),
if Output_PIDs =/= [] ->
lists:foreach(fun(Output_PID) ->
Output_PID ! {stimulate, {self(), Output}}
end,
Output_PIDs);
Output_PIDs =:= [] ->
io:format("~n~w outputs: ~w", [self(), Output])
end,
perceptron(Weights, New_inputs, Output_PIDs)
end.
We know which perceptrons to output to, because we keep a list of perceptron PIDs that registered with us. So if the list of Output_PIDs is not empty, then for each PID, send them a message with a tuple that contains this perceptron's PID as well as the calculated Output value. Let's try it out:

Test Drive


1> c(ann).
{ok,ann}
2> Pid = spawn(ann, perceptron, [[0.5, 0.2], [{1,0.6}, {2,0.9}], []]).
<0.39.0>
3> Pid ! {stimulate, {1,0.3}}.

<0.39.0> outputs: 0.581759
{stimulate,{1,0.300000}}
4>
So you can see, we got an output of 0.581759. We can verify this by doing this on our TI-85 calculator:
x = 0.5 * 0.3 + 0.2 * 0.9
Done
1 / (1 + e^-x)
.581759376842
And so we know our perceptron is working feeding forward! Next time, we'll have to figure out how to propagate its error back to adjust the weights, and how to connect them up to each other.

Erlang and Neural Networks Part I
Erlang and Neural Networks Part II
Erlang and Neural Networks Part III

Thursday, April 05, 2007

Google Maps of the World of Hello World

Google maps now allows the ability to create your own maps. The title link is a map of the major programming languages in use in the world. So it's like lots of little hellos around the world. Cute. Looks like Africa, India, Australia, and South America have a lot of catch up to do. They don't do all the languages in the world, but Japan would also have quite a few if it listed all the variants in the Lisp family.

It's also noticeable that the coasts dominate with programming languages. UIUC's gotta step up.

But most significantly, making your own maps has been a long time coming, and I would have originally thought they'd leave mappr.comFrappr alone in this field. But I think it makes strategic sense for them, especially if they make it easy to post maps that people create.

Tuesday, April 03, 2007

"Web 3.0" and "Killer App" sound like "Crystal Ball" to me

Ahh, web 3.0.

Indeed, as nanobeeper's asks and puts into perspective, What's up with the web 2.0 angst?, there doesn't seem to be a need to get bent all out of shape over the term. And yet, I usually don't use the term myself and am pretty reluctant to, for fear of being someone-who-doesn't-know-what-they're-talking-about, like the braying butthole in Jeffery Zeldman's famous post. It's what happens when marketers get out of control, and generally, it applies when someone that knows just enough to be dangerous. Fanboys of Japan is a good example. If you meet someone that LOVES Japan, they've either only watched anime (or been to Japan once or twice), or they've lived there for at least a decade. Usually the former.

But what I want to post here today isn't want I think is or isn't web 3.0, but more about the usage of the term. Why do people use it?

Killer app 3.0

It's an interesting parallel that ever since Visicalc came out and the term "killer app" was termed, people since then has been talking about the "killer app" on this platform or that. "The killer app of the web is..." "The killer app of the mobile phones is..." It's certainly reminds me of the way people talked about web 2.0. "Web 2.0 is...." "Web 3.0 is..."

The similarity between talking about web 3.0 and talking about killer apps is that when people talk about them, they're using those terms to try to communicate what they see, predict, or would like to be the future. Technologists are, if anything, always looking for the Next Big Thing. We're use to change, and in fact, we thrive on it. We're all interested in the future of change because if we're right about it, that kind of information is an advantage over whatever our goals are. But as we all know, predicting the future is well, inaccurate at best.

I'd trade intelligence for hindsight

Often times, we have limited scope, experience, and knowledge. That certainly will affect what we think to be in the realm of the possible and what will be in the realm of the impossible. If you look back on quotes about technology predictions, some of them might stun you at how stupid they are. But then again, you have the gift of hindsight. Keep in mind what technology was available at the time for them to relate to the new tech, as well as the fact that first iterations of any product sucks--as Guy Kawasaki so famously points out. (If you want to read more, they're from wikipedia)
"Heavier-than-air flying machines are impossible." -- Lord Kelvin, British mathematician and physicist, president of the British Royal Society, 1895
"Who the hell wants to hear actors talk? The music — that's the big plus about this." Warner Bros. was investing in sound technology though Henry Warner was more excited about the potential of scoring over dialogue. [3]
"Caterpillar landships are idiotic and useless. Those officers and men are wasting their time and are not pulling their proper weight in the war." -- Fourth Lord of the British Admiralty, 1915
"The wireless music box has no imaginable commercial value. Who would pay for a message sent to no one in particular?" -- Associates of David Sarnoff responding to the latter's call for investment in the radio in 1921.
"While theoretically and technically television may be feasible, commercially and financially it is an impossibility, a development of which we need waste little time dreaming." -- Lee DeForest, American radio pioneer and inventor of the vacuum tube, 1926
The last two quotes are notable. Lee DeForest, who had enough foresight and innovation to see that a radio had value, couldn't see beyond that to see how a television would have value just five years later. We all have limited breadth and imagination, but some people are worse than others. It would do you well to ignore those people. Sometimes you can recognize them if they counter with "Why would I ever do [insert whatever idea you just told them]"

And even if we had perfect scope, perfect breadth, it would still be hard. Predicting the future is computationally intensive.

As for myself, I didn't immediately see the value of social networks apps until Facebook showed up, even though I read research papers on social networks. And currently, I don't really get Twitter and Scribd, but the fact that people are using it, well, there's value somewhere in there.

So what's the chorus in all the noise?

So where does that leave us with Web 3.0? If you look at it as people merely trying to say what their predictions about the future of the web, it doesn't conjure up as much anger, because you know they may very well be wrong. But collectively, what everyone predicts to be web 3.0 will have some value because part of it might be a self-fulfilling prophecy. If we all say it's true, you can be sure that some of us will work to make it true.

Based on that flash in the pan, I was curious. What was the collective consensus on what web 3.0 is? I looked in two places. Wikipedia and del.icio.us. Just from eyeballing it, it seems to be that people are in consensus, at least about the semantic web. This would be the type of thing that Inkling Markets would be good for. I created a market for it, if you're so inclined to buy stock on web 3.0.

So take what any individual says to be the future with open mind and a grain of salt, but really pay attention to where the global trend is moving. As Joe Kraus says, you want to see what the trend is, take it out of geek land, and ride that wave.

Saturday, March 31, 2007

Crazy small nuances

I'm not particularly fond of nuances. Ruby is suppose to be easy to use and intuitive to the user. But as it grows, it has some crazy little nuances.

For example, there's a difference between system and exec. I wouldn't have known, as I was skimming the docs for something I needed. Were it not for this post by jayfields, I would have had no idea.

And there's something in Ruby 1.9 called "funcall", in which it's definitely not at all intuitive how that's different from "send". I hope these are just growing pains, because while Ruby is nice when you're taking it out for dinner on the first couple of dates, I hope it doesn't get abusive the more time that you spend with it.

Friday, March 30, 2007

Users know the problem. You know the solution

What's considered by now to be mantra out there in 'user-centric web development land', is "listen to your users". But in all that hubbub, you'll also hear, "don't listen to your users all that much."

So what's up with the paradox? Well, like all puzzles, it's only a puzzle if you think it's all or nothing. It seems pretty obvious once you think about it, but it bears reiterating:

Listen to your users when it comes to what's wrong with your stuff. Users are more familiar with problems with your application than you are. They are pained by how much your application sucks, and how it doesn't help them get on with their lives. So they'll complain to you, in hopes that you're listening and you'll fix it.

But users often times have no idea what solutions are good. They'll often offer up solutions to their problems with your application when they're telling you what's wrong with it. Often times, they won't even tell you the problem, they'll just offer solutions.

"You should put tagging in here."

"Why not put a chat room so we users can talk to each other?"

However, they usually don't have the overall vision, sufficient scope, and adequate background for improving the product. That's your job. You have to get beyond what users are saying to figure out exactly what the problem is, and find a solution that fits the overall vision of the product, and perhaps solves other problems all at once also.

Thursday, March 29, 2007

A default behavior for failure or nil

I read "The Rails Way", mainly because Jamis Buck writes there. Three days ago, they had actually posted one thing that I had address just a few days prior--that is, how to prevent users from looking at other users' data.

I have to admit, I was rather tickled by my solution. It's nice when you figure things out. But alas, after reading Koz's post on association proxies, I have to admit, I like his solution better. At least I made it to anti-pattern #3.

So what did he do? He simply used the find in the association, and let things throw an exception otherwise.
def show
@todo_list = current_user.todo_lists.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
flash[:warning] = "Stop playing around with your urls"
redirect_to '/'
end
It also takes care of the case where you have say, many items that belong to a todo_list. You can load it by using :condition in the association find. The only reason I can think of not to use it is if it happens to be a slow solution. But no use optimizing if you have no measurements and hard numbers.

Koz's solution let the default behavior of the method take care of things. This is a way of thinking that I need to start using more of.

I was use to nil being a failure state, something that you checked, and if it happened, everything's gotta stop--like the examples I often saw in C:
status = CallSomeMethod(with, some, parameters);
if status == NULL {
return ERROR_CODE
// or throw some exception here if you're using C++ or Java
}

Often times, these things got cumbersome, because NULL (or even an empty array or hash) was not considered to be a valid input for many functions, and would stop computation by returning error codes and throwing exceptions in C++.

One of the things that I found nice about the code from Ruby gurus was that it was conventional to do (and subsequently, I saw in Perl):
setting = params[:setting] || "default"
Instead of:
setting = params[:setting].nil? ? "default" : params[:setting]
Or
setting ||= "default"
Instead of:
setting = setting.nil? ? "default" : setting

It was because the operator || took nil by default, and had an appropriate behavior for dealing with nil, and that has made all the difference in being able to chain functions together. In addition, having default failure behaviors require you not have to write error checking code all over the place either.

I'm not sure what this is called (if anyone knows, enlighten me), but a completeness and liberal in what you accept for your input and strict in what you output also applies here to methods and functions. I think it makes code more readable, because it is not peppered with common sense error checking code.

Wednesday, March 28, 2007

Capistrano and Mongrel are easy to use, but deployment is still hard

This summary is not available. Please click here to view the post.

Tuesday, March 27, 2007

Does link_to_remote() submit using a GET or a POST?

A little while back, I had a post about how to have two submit buttons with form_remote_tag. A question was raised about having a POST as opposed to a GET request. It seemed like a short enough question, but after looking into it for about 15 minutes, I figured it was worth it to type something up.

To recap, when I first was doing web stuff in high school, I never got what the difference between POST and GET were. It seemed like the author of my HTML book then didn't really get it either. However, it wasn't until DHH started raving about REST as a web service did I get it. in short, when a user submits a form, GET puts the form contents in the url, and POST puts the form contents in the body of the HTTP request. The implication (apparently related to REST) is that you'd only use GET for server requests that didn't change content on the server--the request had no side-effects. That way, the same URL would refer to the same resource, time after time. Alternatively, POST is for server requests that change the content of the server. And that's why we care.

I find that reading documentation helps. So I first looked at the browser source for a link_to_remote() call and it's pretty clear it uses Form.serialize() to convert the form, and then sends it along using Ajax.Request(). The question is, does it send via POST or GET?

According to the documentation for link_to_remote(), it sends via POST by default.

The method used is by default POST. You can also specify GET or you can simulate PUT or DELETE over POST. All specified with options[:method]

Example:

  link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete

I also checked it out with a quick check inside a controller with a breakpoint to see if a link_to_remote() call really sends a post. I put a breakpoint inside a controller method called by link_to_remote:
$ ./script/breakpointer 
Executing break point at ./script/../config/../app/controllers/friend_controller.rb:60 in `test_ajax'
irb(#):002:0> request.get?
=> false
irb(#):003:0> request.post?
=> true

As for a regular form_for() call, simply use the :method option. I think by default it also uses POST.

Saturday, March 24, 2007

Erlang and neural networks, part I

So it's been a whole week since my interesting post about the OwnershipFilter. I was investigating several things all at once, all the while wrestling with internal motivation (another post, at another time). In any case, I thought I'd blog about it entirely when I had something full and concrete to show you. However, if it takes me that long, I might as well blog about it as I go along--and it might be more fun for you anyway.

Trace it back

It started with an article about how the free lunch is over for software engineers that a friend sent to me about two years ago. It basically stated that developers have been riding on the wave of Moore's law to save their butts, and it's not going to last forever. In addition, it's been known for a while that chip manufacturers are moving towards multi-core processors to increase performance. If developers are going to take advantage of hardware like they have been, they're going to have to learn how to program concurrent programs.

The problem is, programmers suck at it. It's well known that concurrent programming, as it stands, is not easy for humans. Even Tim Sweeney, the guy that architected the Unreal Engine (no mere programming mortal), thought it was hard. It was when I started looking beyond threads as a concurrency abstraction that I tripped over a programming language developed specifically for concurrency.

Yet Another Programming Language

A friend of mine, who is a teacher (i.e. not a programmer), recently asked me, "Why learn more than one programming language?" Ahh, little did she know that programming languages inspire what verges on religious debates between programmers. My short answer was, "Each tool is better at one task than another." I was looking for another language that might do concurrency better.

I had always thought that I should learn more about functional programming. It seemed like an odd beast to me, especially since you don't change state through side-effects. "How do you get anything done?" It's kinda like when you first learned that you don't need GOTO, and subsequently, when you learned that FOR loops suck.

And yet, I never really found a need or a small project I could do with functional programming that might prove to be satisfying. It was only due to the search for better concurrency abstractions that I ran across Erlang, a functional programming language that is used explicitly because it's good at concurrency. In fact, it's pretty much the only one out there that touts concurrency as its strength.

It uses the actor model, where processes share no data and just pass messages around. Because there's nothing shared, there's no issue of synchronization or deadlocks. While not as sexy-sounding as futures or software transactional memory, the actor model falls nicely along the lines of complex and emergent systems--systems that have locally interacting parts with a global emergent behavior. Hrm...could one of these systems be good for a small side project to do in Erlang?

How Gestalt, Mr. Brain

Artificial neural networks seemed to be the perfect thing actually. A quick, quick diversion into what they are.



A feed-forward artificial neural network is basically a network of perceptrons that can be trained to classify (ie. recognize) patterns. You give the network a pattern as an input, it can tell you the classification of that input as an output.

You can think of a perceptron much like a neuron in your brain, where it has lots of inputs and one output. It's connected to other perceptrons through these inputs and outputs and there are weights attached to the input connections. If there is a certain type pattern of input, and it passes a threshold, the perceptron 'fires' (i.e. outputs a value). This in turn might activate other perceptrons.

Even simpler, a perceptron is modeled as a function that takes a vector x as an input and outputs a number y. All it does is take the dot product of the input vector x with weights vector w, and pass it through a non-linear and continuous thresholding function, usually a sigmoid function. And you connect them up in layers, and you get an artificial neural network, that can learn to recognizeclassify patterns if you train it with examples.

It has to learn patterns by adjusting the weights between perceptrons in the network after each training example, and you tell it how wrong it was in recognizing the pattern. It does this by an algorithm called back propagation. It's the same page I lifted all these pictures from. I put all their pictures in an animated gif to illustrate (click on it to watch):



In the first part, the example propagates forward to an output. Then it propagates back the error. Lastly, it propagates forward the adjusted weights from the calculated error.

I think the shoe fits, sir

Why would this be a good fit as a subject to play with Erlang? Well, if you'll notice, each perceptron only takes input from its neighboring perceptrons, and only outputs to its neighbors. This is very much in line with the actor model of concurrency. Each process would be a perceptron, and would act as an autonomous agent that only interacts with other processes it comes into contact with--in this case, only other perceptrons it's connected to.

In addition, you'll also notice that in the animation, the perceptron values are calculated neuron by neuron. In a concurrent system, there's no reason to do this! You can actually do the calculation layer by layer, since the calculations of any individual perceptron only comes from the outputs of the perceptrons in the layers before it. Therefore, all outputs for perceptrons in a layer can be calculated in parallel.

Notice, however, that layers need to be calculated serially. I had originally thought that with the learning process propagating back and forth, maybe it could be pipelined. On closer examination, however, the best one can do is to feed-forward the next input one layer behind the adjusting of weights, to make the learning process go faster.

So I'm going to give it a shot on the side, and document it along the way, since a quick search on google revealed that though people talked about it, no one's ever really given some snippets on it. Wish me luck!

Erlang and Neural Networks Part I
Erlang and Neural Networks Part II
Erlang and Neural Networks Part III

Friday, March 23, 2007

Stream Copy YouTube, Revver, Etc.

For lots of times in the past, I was always annoyed that I couldn't save content offline, and always had to view it online--especially when there's no guarantee that the content will stay there. So, I was a little bemused, but not altogether surprised, that you can save streaming copies of videos using Ruby. The source code is fairly short...maybe 20 lines or so. And while I haven't tried it out, I've actually been able to read it through, and it's nice to be able to read the works for people far better than me, even if it's just table scraps.

Well, if you want to try it out, the balloon is here. A balloon is a web page that has ruby embedded in it, so that you can run it in ruby. Just make sure you have ruby installed on your system, and follow the instructions on the balloon.

Friday, March 16, 2007

Keep users from looking at other people's data with a simple ownership filter

Happy St. Patrick's day everyone!

Well. Everyone's pretty familiar with authentication. That's where you force the users to login, before you'll show any of the pages. Usually, this is achieved with a before_filter, so that you're not checking if a user has logged in in the beginning of each action in the controller. This keeps your code mighty DRY. But what about ownership of data? Within any web app, you have data that's owned by some users, and other data that's owned by other users. Just because they're logged in doesn't mean that they should be able to see other users' data.

Oh, these tables of mine

A good example are friends in a social network app. Each user has a set of Friend records in the database that belongs to them. (btw, don't use the User table below in your own app. you never want to store cleartext passwords in the database. Check out authentication tutorials)
create_table :users, :type => "InnoDB" do |t|
t.column :username, :string
t.column :password, :string
end

create_table :friends, :type => "InnoDB" do |t|
t.column :user_id, :string
t.column :name, :string
t.column :email_address, :string
end

create_table :posts, :type => "InnoDB" do |t|
t.column :user_id, :string
t.column :timestamp, :datetime
t.column :body, :text
end

Your first instinct sucks

You only want those records of friends that belong to them to be available to them. So what's the first thing that you're inclined to do? Assume that you have the User record as an indication of being logged in the session data.
class FriendController < friends =" Friend.find(:all," conditions =""> ["user_id = ?", session[:user].id])
end

def show
@friend = Friend.find(params[:id])
unless @friend.user_id == session[:user].id
flash[:error] = "That friend does not exist"
redirect_to :action => :list
end
end
end

In list, you want to make sure that the list of friends returned belongs to the user, and that's why you find all by the user_id. In show, a user can easily change the URL's id number to reflect another record. You want to check whether that friend actually belongs to them.

While this is all good and well, the problem is, you'd have to do this for every method that you write. We are a lazy kind, so there HAS to be a better way.

Scope it, my brotha from anotha motha

Of course, the Rails geniuses have come up with with_scope() for all ActionControllers.
class FriendController < find =""> { :conditions => ["user_id = ?", session[:user].id] }) do
@friends = Friend.find(:all)
end
end

def show
Friend.with_scope(:find => { :conditions => ["user_id = ?", session[:user].id] }) do
@friend = Friend.find(params[:id])
end
if @friend.nil?
flash[:error] = "That friend does not exist"
redirect_to :action => :list
end
end
end

"But hold on, there's still duplication!" This is only part of the solution. with_scope() is useful if you have multiple database finds within the same block. That way you don't need to keep putting it in the conditions. So how do you get rid of the duplications? With filters, of course.

Add a sprinkle of filter magic

I personally liken filters to programming 'common sense' into the classes. It's what's intuitively understood to have to be done before and after every action. Luckily, there's a filter called around_filter that we can use.
class FriendController < find =""> { :conditions => ["user_id = ?", session[:user].id] }) do
yield
end
end

def list
@friends = Friend.find(:all)
end

def show
@friend = Friend.find(params[:id])
if @friend.nil?
flash[:error] = "That friend does not exist"
redirect_to :action => :list
end
end
end

So it should be pretty obvious what happened. The around_filter allows you to do one responsibility, both before and after every action in the controller. When the method yields, it gives control to one of the actions below. So you're essentially wrapping every action in the with_scope() defined in the filter.

Yay, that's pretty cool. The code's been DRY'd. We're done, right? But you know as well as I, that because there's more text after this sentence, we can actually take it a step further.

I pull out the method inside, served it and fried

Of course, you have more than one ActiveRecord model that's owned by the user, and in this case, there's another one called Post. So instead of repeating ownership_filter method in every ActiveRecord Object, let's pull it out of FriendController into a class of its own, so that other controllers can use it, using some easy meta programming. Note that you now have a require up top and around filter changed.
require 'ownership_filter'

class FriendController < friends =" Friend.find(:all)" friend =" Friend.find(params[:id])" action =""> :list
end
end
end

And this is where we extracted the method to...a file named "ownership_filter.rb" You can put this in your app/controller directory.
class OwnershipFilter
def filter(controller)
model_class_name = controller.controller_name.capitalize.to_sym # => :Friend
model_class = Object.const_get(model_class_name) # => Friend class
model_class.with_scope(:find => { :conditions => ["account_id = ?", controller.session[:user].id] }) do
yield
end
end
end

It actually took me a while to find out how to do this. I knew you could call methods dynamically with send(), but how do you dynamically get a class? Good thing for posts on ruby-talk. So basically, you take the controller's name and you turn it into a symbol :Friend that is used to find the class, using const_get(), that the constant :Friend refers to, namely, the Friend class.

After that, it's the same as before, you call with_scope() with it. So now, you can use this with any of the controllers that you have in the same ways as you did with the friend controller. I haven't tried it yet with the finds pushed down to the ActiveRecords, but I think it should work the same way. Tip!

Update: I saw that the method I described above is actually an anti-pattern according to Jamis Buck. I've posted subsequently on this topic.

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