View man pages in Preview

It’s not a new concept, but here is my take on it:

 1 function man {
 2     # We can get the actual path to the man command here, so we can override
 3     # it with our function name.
 4     MAN=`which man`
 5     # Change these two if you are not on OS X.
 6     CACHE_DIR="${HOME}/Library/Caches/manpages"
 7     OPEN="open"
 8     
 9     # If we don't have any arguments, use the nice man error message
10     if [ ! $1 ]; then
11         $MAN
12         return
13     fi
14     
15     # If we have an argument that clashes with what we are wanting to be
16     # able to do, pass the whole command through.
17     for ARG in $*; do
18         case $ARG in 
19             -[dfkKwtWP])
20                 $MAN $*
21                 return;;
22         esac
23     done
24     
25     # Make sure our cache directory exists.
26     mkdir -p $CACHE_DIR
27     # Get the man page(s) that match our query.
28     MAN_FILES=`$MAN -w $*`
29     for MAN_FILE in $MAN_FILES; do
30         # Get the name of the man file, and the section.
31         MAN_PAGE=`basename "$MAN_FILE" | cut -d \. -f 1-2 | sed 's/\./(/' | sed 's/$/)/'`
32         # Our PDF will be in this location
33         PDF_FILE="${CACHE_DIR}/${MAN_PAGE}"
34         
35         # If we actually have a man file that matches
36         if [ -n "$MAN_FILE" ]; then
37             # See if the man file is newer than our cached PDF, and if it is,
38             # then generate a new PDF. This works even if $PDF_FILE does not
39             # exist.
40             if [ $MAN_FILE -nt $PDF_FILE ]; then
41                 $MAN -t $* | pstopdf -i -o "$PDF_FILE"
42             fi
43             # Then display the file.
44             $OPEN "$PDF_FILE"
45         fi
46     done
47 }

On UI sins

My sister likes to back up DVDs that her children use all of the time: they are old enough to change discs, but they tend to get scratched. So, I have been looking into backup solutions for her to use on her new MacBook.

I came across Aimersoft DVD Backup, and ran it. Not looking too bad to begin with.

The actual window, however, is appalling:

Aimersoft DVD Backup(Unregistered)

It is a little hard to see, but the window is not actually connected to the titlebar. You can actually see the objects that are in obscured windows in the gap between them!

Finally, the text from the close confirmation sheet just cracked me up:

Surely, they can tell if a copying task is in progress, and display a dialog then. If not, then just quit immediately!

On Django and Check Constraints

I’ve come to love Django, and now I seem to be spending not only my work time, but also my own time working on one django project or another. Today at work I came across the need to have check constraints in a database. For instance, this can be used to ensure that the start of an event is before the end of the event, or that a certain value has a particular range of values.

For the SQL savvy, it can look like:

CREATE TABLE event (
…more columns here…
start datetime,
finish datetime,
count integer CHECK (count >= 0),
CONSTRAINT event_starts_before_finish CHECK (start < finish)
);

There are two types of constraint here: the column-level constraint, which in this instance can be done with django, and the table-level constraint, which in many systems cannot be a part of a column definition. In PostgreSQL, my DBMS of choice, it is possible to define a constraint that affects more than one column as part of a column, but I prefer not to. Note also that I am using the syntax form that allows me to name the constraint. This means I can alter or drop it later.

As I mentioned, django can do the first type of constraint, as long as it is a > 0 constraint, using one of the field types that subclasses PositiveInteger. However, there is no functionality built into django to do the latter. And I would like to use them.

It is possible to just add the constraints to an already existing database: indeed, that is what I did for work. Having the constraints at the database level means that, since I have more than one interface to my datastore (don’t ask: one of them is for an old SOAP interface I need to keep around), I want to ensure that even if someone accesses it outside of django, they cannot put in data that breaks these constraints. Similarly, if I use an interface other than the admin interface, or heaven forbid, open up the database in raw form, I cannot accidentally put in data that breaks this validation.

But, pure database level constraints don’t give very nice feedback in django. It is nicer to have the pretty red boxes around my field than the traceback. So, I want the validation to occur on the field level as well. As long as I am using django’s forms (and my API for RESTful access will use them for validation), then I will have these errors nicely presented.

So, to that end, I have created some code that allows for the definition and enforcement of both of these types of constraint.

The column form allows for a new keyword argument to a field:

count = models.IntegerField(constraint=">= 0")

Notably, the string that can be passed in must conform to the pattern “cmp value”, where cmp is one of the comparison operators (<, >, <=, >=, =, !=), and value is a valid value for this column type. It will be passed to the to_python() method of this field when comparing. There must be a string between the two parts.

The other form is a new attribute on the Meta class of a model.

check_constraints = (‘start < finish’,)  

This must be a tuple of strings, where a string is of the form “column cmp column”. Again, there must be a space either side of cmp, and each column name must be a valid column. Not meeting these criteria will result in a validation error.

From these definitions, the database constraints will be applied, and validation of forms will also occur.

I have deliberately made the constraints simple (ie, not callable objects) so that they can easily be converted to database constraints. For instance, they can effectively be transferred straight through to the database (with the addition of the column name in the case of the column constraint).

I am going to create a ticket in the django trac, and submit a patch. Guessing I should write up some test cases, though!

Setup Django with Passenger Prefpane

I am loving Django for web development. I didn’t have it set up to serve my (development) projects automatically until just now.

I had installed the Passenger Prefpane, which greatly simplifies the management of VirtualHost-based serving of sites, at least for Rails and other ruby-based frameworks. With a little work, you can use the same setup to serve Django projects.

Rather than re-detail the setup, I’ll just point you to the mod_passenger setup, and the Passenger Prefpane setup pages.

Now, to set up a Django project: obviously you need a django project. Create one, and note where it is located. I stick all of mine in ~/Sites.

Add a file to the root of this project, called passenger_wsgi.py. It needs to contain the following data:

1 import os, sys
2 sys.path.append('/Users/matt/Sites') # Replace with your directory
3 os.environ['DJANGO_SETTINGS_MODULE'] = 'testing.settings' # replace with your projectname.
4 import django.core.handlers.wsgi
5 application = django.core.handlers.wsgi.WSGIHandler()

Now, add the site to the Passenger prefpane. My site is the testing.local site:

Now visit the address and ensure that it works. You should get the basic you need to set up django message.

To get the admin media served by the standard apache setup, I created a link inside the /Library/WebServer/Documents directory to /Library/Python/2.5/site-packages/django/contrib/admin/media. This can be done inside the Terminal:

sudo ln -s /Library/Python/2.5/site-packages/django/contrib/admin/media /Library/WebServer/Documents/admin-media/

Then, change the ADMIN_MEDIA setting in your django projects to http://localhost/admin-media/. This is probably the weakest point in the setup, as it will only work for pages served to your machine, not others on your network.

1 # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
2 # trailing slash.
3 # Examples: "http://foo.com/media/", "/media/".
4 ADMIN_MEDIA_PREFIX = 'http://localhost/admin-media/'

I had some issues with mod_passenger serving the data for localhost (and arne, my actual machine’s name) from the first installed VirtualHost. To overcome this, I put in a new file into /etc/apache2/other/localhost.conf, which looks like:

1 <VirtualHost *:80>
2   DocumentRoot "/Library/WebServer/Documents"
3   <directory "/Library/WebServer/Documents">
4     Order allow,deny
5     Allow from all
6   </directory>
7 </VirtualHost>

This forces unnamed, or other sites to work as intended. Including the /User/*/Sites directories.

Prowl

Prowl is awesome. Growl notifications can be forwarded to your iPhone.

But you can get notifications from anywhere. A Perl script is included, but that didn’t work on my server. So I wrote one in Ruby:

 1 #! /usr/bin/ruby
 2 
 3 # A ruby class for sending notifications to Prowl.
 4 
 5 require 'uri'
 6 require 'net/http'
 7 require 'net/https'
 8 
 9 class String
10   def urlencode
11     gsub( /[^a-zA-Z0-9\-_\.!~*'()]/n ) {|x| sprintf('%%%02x', x[0]) }
12   end
13 end
14 
15 class Hash
16   def urlencode
17     collect { |k,v| "#{k.to_s.urlencode}=#{v.to_s.urlencode}" }.join('&')
18   end
19 end
20 
21 class Prowler
22   def initialize user, pass
23     @url = URI.parse('https://prowl.weks.net/api/add_notification.php')
24     @username = user
25     @password = pass
26     
27     @http = Net::HTTP.new(@url.host, @url.port)
28     @http.use_ssl = true
29   end
30 
31   def send_notification app, evt, desc
32     
33 
34     options = {
35       'application' => app,
36       'event' => evt,
37       'description' => desc
38     }
39     
40     req = Net::HTTP::Get.new("#{@url.path}?#{options.urlencode}")
41     req.basic_auth @username, @password
42     @http.request(req)
43   end
44 
45 end
46 
47 # How to use?
48 # p = Prowler.new('username', 'password')
49 # p.send_notification('App','Event','Desc')

Logos

Started up a new iPhone app today. The logo at the bottom of the screen looked a bit familiar:

Here is the logo from the Adelaide City Council (which has been in use for about 7 years):

Wonder which came first…

If I overlay one one the other, we see they are not identical:

]

Fix Redmine not showing repository data

For some time, the git repository I am using to track changes for my Django-Management TextMate bundle was not working correctly in Redmine. I was able to connect it up using the settings, but was getting errors about the files not being found.

It turns out that git was not in my path. Putting a link from /usr/local/bin/git to /usr/bin/git fixed that all up.

TextMate return codes

From the TextMate manual:

These functions only work when the initial output option is not set as “Show as HTML”. The list of functions is as follows:

  • exit_discard
  • exit_replace_text
  • exit_replace_document
  • exit_insert_text
  • exit_insert_snippet
  • exit_show_html
  • exit_show_tool_tip
  • exit_create_new_document  

This is all well and good, but what about when you are in another language?

Simple. Just ensure your exit code matches. The values start at 200, for exit_discard, and 205 is exit_show_html.

This is probably not the best way to do it, as these may change in the future. But, I couldn’t think of another way, at least not offline.

Reasons PHP sucks #753

Another good example of a PHP “quirk” is the way PHP handles constants. It was one of the major factors affecting performance. Just removing all the constants allowed us to improve the performance by almost 2x (we left one constant to be precise).

From The Need for Speed.

That’s right - PHP is up to 2X faster if you don’t use constants. You know, that means hardcode values in…

Patch for Mercurial.tmbundle

 1 diff -r 5e13047a2284 Support/hg_commit.rb
 2     --- a/Support/hg_commit.rb	Mon Apr 27 11:38:15 2009 +0930
 3     +++ b/Support/hg_commit.rb	Mon Apr 27 11:39:00 2009 +0930
 4     @@ -79,7 +79,7 @@
 5        commit_paths_array = matches_to_paths(commit_matches)
 6        commit_status = matches_to_status(commit_matches).join(":")
 7        commit_path_text = commit_paths_array.collect{|path| path.quote_filename_for_shell }.join(" ")
 8     -  commit_args = %x{"#{commit_tool}" --status #{commit_status} #{commit_path_text} }
 9     +  commit_args = %x{"#{commit_tool}" --diff-cmd hg,diff --status #{commit_status} #{commit_path_text} }
10      
11        status = $CHILD_STATUS
12        if status != 0
13