Archive for December, 2009

Hello Rack

Posted 15 Dec 2009 — by admin
Category ruby

What is Rack?

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

- Rack API Docs


Create and name your file config.ru If rack isn’t installed get it with this command

gem install rack

In your config.ru file

require 'rubygems'
require 'rack'

class HelloRack
  def call(env)
    [200, {"Content-Type" => "text/html"}, "Hello Rack!"]
  end
end

Rack::Handler::Mongrel.run HelloRack.new, :P ort => 8888

Check out http://m.onkey.org/2008/11/17/ruby-on-rack-1

The survey for people who make websites

Posted 15 Dec 2009 — by admin
Category Web Development

I took the survey!


Click here to take it →

Placing an Authenticity Token in a Rails Form

Posted 14 Dec 2009 — by admin
Category Ruby on Rails
 <%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Managing Timestamps in MySQL with a Trigger

Posted 10 Dec 2009 — by admin
Category Databases

MySQL doesn’t support having two columns with time stamping on both initialization and/or on updating at the same time. It would be nice to be able to do *this* where the created_at column gets the current_timestamp on initialization and the updated_at gets changed on updating the row.

# like so doesn't work...
create table entries(
  body blob,
  created_at datetime default current_timestamp,
  updated_at timestamp default current_timestamp on update current_timestamp
);

Seems like a feature a lot of folks would like. There are two work-arounds. The first is baking it into your application code with something like

create table entries(
  body blob,
  created_at datetime default null,
  updated_at timestamp default current_timestamp on update current_timestamp
);
insert into entries (body, created_at) values ('hello world', now());

The second way is to create a trigger and call the trigger on your insert action on a row.

create table entries (
  body  blob,
  created_at datetime default null,
  updated_at timestamp default null on update current_timestamp
);
create trigger init_created_at before insert on entries for each row set new.created_at = now();

Now whenever a new row is created the trigger will be executed and set the time to the current timestamp. You can forget about the created_at column in your code because it’s not meant to be changed.

Grab a Twitter Status without the Twitter API

Posted 09 Dec 2009 — by admin
Category php

Quick and dirty way to grab the users status messages without having to go through the twitter api (not having to authenticate that is). You can grab the RSS feed and indicate the number of statuses returned with the count param. I wrote this function for my blog in PHP. It uses the curl extension so if it’s not installed type

apt-get install php5-curl

Otherwise you’ll have to use the fsockopen function. Then it’s just a matter of parsing the XML and getting at what data you want. I just want one status so I’m accessing the element directly, rather than looping over the returned data set.

<php
function latest_twitter_status_message(){
        // grab the rss feed link from some user, like me and indicate the count in the url
	$host = "http://twitter.com/statuses/user_timeline/11036982.rss?count=1";
	// using curl
	$ch = curl_init($host);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	$data = curl_exec($ch);
	curl_close($ch);
	$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);
	return "{$doc->channel->item[0]->description}";
}

Mod_Python and Web.py on Ubuntu

Posted 09 Dec 2009 — by admin
Category Python

Download

First install mod_python for Apache and then restart/reload the server.

apt-get install libapache2-mod-python
/etc/init.d/apache2 force-reload
apache2ctl restart

Next grab the web.py framework from webpy.org. You can grab the tar or use easy_install depending on your setup.

wget http://webpy.org/static/web.py-0.33.tar.gz
tar xzvf web.py.tar.gz
cd web
sudo python setup.py install
# or if you use easy_install
easy_install web.py

Download this file http://www.aminus.net/browser/modpython_gateway.py?rev=106&format=raw This python package can (with this version) go anywhere in your python path “sys.path”. However, I placed it in the wsgiref directory. I’m running python2.6 so I did the following

# after downloading
mv modpython_gateway.py /usr/lib/python2.6/wsgiref/modpython_gateway.py

It’s important to remember that in the VirtualHost file you create the PythonHandler directive will need to reference this module. If you place it outside of the wsgiref directory remember to change the directive as well.

The VirtualHost

Now we need to create a VirtualHost for our application. You can run web.py apps without apache and this is good for development mode. To do this the command is

python pcode.py 4567

where the pcode.py is your web.py application filename and the 4567 is the port number you want to start the server on. I think it defaults to 8080. If you’re running apache or another web server port 80 will be in use. This is where mod_python (or cgi or fastcgi) come into play.

<VirtualHost *>
  ServerName py.seanbehan.com
  DocumentRoot /var/www/python/myapp

   #Aliases can trip you up! Pay attention here
   Alias /myapp /var/www/python/myapp
   <Directory /var/www/python/myapp>
      <IfModule python_module>
        PythonPath "sys.path +['/var/www/python/myapp']"
        AddHandler python-program .py
        # modpython_gateway is a file you'll need to download and place in wsgiref
        PythonHandler wsgiref.modpython_gateway::handler
        # This is your python program
        PythonOption wsgi.application pcode::main
        PythonOption SCRIPT_NAME /myapp
        PythonDebug on
      </IfModule>
    </Directory>
</VirtualHost>

Web.py Application

Web.py applications can be very simple. Everything can be placed in one file. In this example I created a file “pcode.py” and saved it to “/var/www/python/myapp/pcode.py”. The contents look like this

import web #this is the web.py frameword
web.webapi.internalerror = web.debugerror #lets capture errors for debugging

# map paths to classes
urls = (
    "/", "hello"
)

# this is the main from the PythonOption wsgi.application pcode::main from our VirtualHost
main = web.application(urls, globals()).wsgifunc()

class hello:
    def GET(self):
        #  web.header... otherwise you'll be prompted to save the file rather than view it in the browser
        web.header('Content-type','text/html')
        yield "Finally got web.py to work!"

if __name__ == "__main__":
    main.run()

Save the file, reload apache and visit the location on the web (In my case py.seanbehan.com/pcode.py/). Remember to include that last “/” after the pcode.py. You might get a “not found” message from web.py otherwise.

Pretty URLs

You can get pretty urls like “py.seanbehan.com/hello/world” if you use the mod_rewrite apache module.

a2enmod rewrite

You can either set up the rewrite rules in your VirtualHost or in a .htaccess file. I’ll do the .htaccess so I don’t have to reload the server for the changes to take effect.

In the same directory as your pcode.py file create a file “.htaccess” and in it place this code

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteBase /
  RewriteCond %{REQUEST_URI} !^/icons
  RewriteCond %{REQUEST_URI} !^/favicon.ico$
  RewriteCond %{REQUEST_URI} !^(/.*)+code.py/
  RewriteRule ^(.*)$ pcode.py/$1 [PT]
</IfModule>

Troubleshooting

I ran into some trouble with the Alias in the VirtualHost file. It looks like this

Alias /myapp /var/www/python/myapp

This will map incoming urls to the full path on the filesystem so that your python program will run properly. I kept getting the not found error message from web.py without it. There might be a better way to set this up but this is how I got it to work.

Here are some additional resources I found helpful
http://wiki.slicehost.com/doku.php?id=install_mod_wsgi_on_ubuntu_gutsy

http://webpy.org/install
http://dready.org/blog/2009/01/29/webpy-with-mod_python-on-apache/
http://www.devisland.net/help/webpy.shtml

Updating Your Twitter Status with cURL and a Bash Function

Posted 07 Dec 2009 — by admin
Category Linux, mac os x

I’m usually at the command line so I wrote a little a bash function so that i can type

tweet this is really neat but kind of pointless

and it will update my twitter status! some characters trip it up but in general it’s useful for most of my tweets. The tweet function just spits out the arguments passed to it for the status parameter for the API call to twitter.

Add the following to the .bash_profile file and reload the terminal (don’t forget to add your email and pwd where appropriate).

tweet() {
   curl -u your_twitter_email_addr:your_twitter_passwd -d status="$*" http://twitter.com/statuses/update.xml
 }
 

*** Twitter still uses http basic authentication for their API. However, they are moving away from it in favor of oAuth. So I’m not sure how long this fun will last :{

Me in 3D

Posted 06 Dec 2009 — by admin
Category Data Visualization

My friend Andy made this 3D rendering of me using LIDAR (Laser Detection and Ranging). In the first image you can see me holding up my hand along with a number of file cabinets. The cube in the center is a table used to calibrate the device.

Sean Behan in 3D

In this shot I’m holding up a backpack.
sean_in_3d_2

The rendering software can manipulate the points and map the scene from any angle after the data capture. In these next shots I’m isolated from the background.

iso_sean4

iso_sean5

Ruby on Rails, jQuery and YUI API Docs Available as Mac OS X Dictionary Binaries

Posted 05 Dec 2009 — by admin
Category Documentation

I came across an awesome tool this morning. Priit Haamer has chunked Ruby on Rails, jQuery, and some of YUI documentation into native Mac OS X dictionary binaries. This lets you search those API docs from Spotlight, TextMate, any application that uses the dictionary app!

I have tested the Ruby on Rails API within TextMate. Hover over any function and hit ctl+cmd+d and a little popup will give you a glimpse at the API docs. Seems like a nice alternative to ACK or the normal TextMate function lookup.

More information and installation instructions are available at Priit’s site http://www.priithaamer.com/blog

Here is a nice video of the tool

http://www.vimeo.com/3848473

My First Data Visualization McCain V. Obama Election Results

Posted 03 Dec 2009 — by admin
Category Data Visualization

Here is my first data visualization. I used the Processing programming language and an SVG map of the United States.

McCain V. Obama